-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (63 loc) · 1.8 KB
/
main.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"bytes"
"html/template"
"io/ioutil"
"log"
"os"
"github.com/digitalocean/godo"
"golang.org/x/oauth2"
)
func main() {
accessToken := os.Getenv("DO_KEY")
if accessToken == "" {
log.Fatal("Usage: DO_KEY environment variable must be set.")
}
peerTag := os.Getenv("DO_TAG")
if peerTag == "" {
log.Fatal("Usage: DO_TAG environment variable must be set.")
}
tmpl, _ := template.New("test").Parse(`## drophosts ##
{{range .}}{{.PrivateIPv4}} {{.Name}}.kubelocal
{{end}}## drophosts ##`)
oauthClient := oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}))
client := godo.NewClient(oauthClient)
droplets, _ := DropletListTags(client.Droplets, peerTag)
original, err := ioutil.ReadFile("/etc/hosts")
if err != nil {
log.Fatal(err)
}
var doc bytes.Buffer
tmpl.Execute(&doc, droplets)
output := UpdateHosts(string(original), doc.String())
ioutil.WriteFile("/etc/hosts", []byte(output), 0644)
}
// DropletListTags paginates through the digitalocean API to return a list of
// all droplets with the given tag
func DropletListTags(ds godo.DropletsService, tag string) ([]godo.Droplet, error) {
// create a list to hold our droplets
list := []godo.Droplet{}
// create options. initially, these will be blank
opt := &godo.ListOptions{}
for {
droplets, resp, err := ds.ListByTag(tag, opt)
if err != nil {
return nil, err
}
// append the current page's droplets to our list
for _, d := range droplets {
list = append(list, d)
}
// if we are at the last page, break out the for loop
if resp.Links == nil || resp.Links.IsLastPage() {
break
}
page, err := resp.Links.CurrentPage()
if err != nil {
return nil, err
}
// set the page we want for the next request
opt.Page = page + 1
}
return list, nil
}