-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (94 loc) · 2.4 KB
/
Copy pathmain.go
File metadata and controls
118 lines (94 loc) · 2.4 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/service/ec2"
)
func Metadata(path string) (string, error) {
resp, err := http.Get("http://169.254.169.254/latest/meta-data/" + path)
if err != nil {
return "", err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// Returns current IP address via metadata endpoint or "" on error.
func MyIP() string {
ip, _ := Metadata("public-ipv4")
return ip
}
func WaitForIP(target string) bool {
const MAX = 120 // Maximum number of seconds to wait
for i := 0; i < MAX; i++ {
ip := MyIP()
if ip == target {
log.Printf("IP updated!: %q", ip)
return true
}
log.Printf("Waiting for IP address update: %q", ip)
time.Sleep(1 * time.Second)
}
return false
}
func ThisInstanceID() (string, error) {
return Metadata("instance-id")
}
func ThisAvailabilityZone() (string, error) {
result, err := Metadata("placement/availability-zone")
if err == nil {
result = result[:len(result)-1]
}
return result, err
}
func main() {
log.SetFlags(0)
args := os.Args[1:]
if len(args) < 1 {
log.Fatal("usage: %s <PublicIP>", os.Args[0])
}
publicIP := args[0]
thisInstanceID, err := ThisInstanceID()
if err != nil {
log.Fatalf("Unable to determine instance id: %v", err)
}
thisAvailabilityZone, err := ThisAvailabilityZone()
if err != nil {
log.Fatalf("Unable to determine availability zone: %v", err)
}
log.Println("InstanceID:", thisInstanceID, "AZ:", thisAvailabilityZone)
svc := ec2.New(&aws.Config{
Region: thisAvailabilityZone,
})
desc, err := svc.DescribeAddresses(&ec2.DescribeAddressesInput{
PublicIPs: []*string{aws.String(publicIP)},
})
if err != nil {
log.Fatalf("Unable to describe EIPs: %v", err)
}
if len(desc.Addresses) != 1 {
log.Fatalf("Expected exactly 1 address, got %v", len(desc.Addresses))
}
allocation := desc.Addresses[0]
resp, err := svc.AssociateAddress(&ec2.AssociateAddressInput{
InstanceID: &thisInstanceID,
AllowReassociation: aws.Boolean(true),
AllocationID: allocation.AllocationID,
})
if err != nil {
log.Fatalf("Unable to associate allocation: %v", err)
}
log.Println("Associated:", *resp.AssociationID)
if !WaitForIP(publicIP) {
log.Fatal("Failed to see public IP update in a timely fashion.")
}
}