-
Notifications
You must be signed in to change notification settings - Fork 11
/
digital_ocean.go
61 lines (49 loc) · 1.18 KB
/
digital_ocean.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"context"
"fmt"
"html/template"
"os"
"github.com/digitalocean/godo"
"golang.org/x/oauth2"
)
const tmpl = `
{{ range $_, $d := .Instances -}}
Host {{ $.Prefix }}{{ $d.Name }}
HostName {{ ( index $d.Networks.V4 0).IPAddress }}
{{ end}}
Host {{ .Prefix }}*
User {{ .User }}
`
func generateDigitalOcean(prefix string) {
tokenSource := &TokenSource{}
oauthClient := oauth2.NewClient(context.Background(), tokenSource)
client := godo.NewClient(oauthClient)
droplets, _, err := client.Droplets.List(context.TODO(), &godo.ListOptions{PerPage: 200})
checkErr(err)
templateData := struct {
Prefix string
User string
Instances []godo.Droplet
}{
Prefix: prefix,
User: sshUser,
Instances: droplets,
}
t := template.Must(template.New("tmpl").Parse(tmpl))
err = t.Execute(os.Stdout, templateData)
checkErr(err)
}
type TokenSource struct{}
func (t *TokenSource) Token() (*oauth2.Token, error) {
envVar := "DIGITAL_OCEAN_TOKEN"
envToken := os.Getenv(envVar)
if envToken == "" {
fmt.Printf("Please provide a personal access token as %s\n", envVar)
os.Exit(1)
}
token := &oauth2.Token{
AccessToken: envToken,
}
return token, nil
}