-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_openstack_compute_floatingip_associate_v2.go
301 lines (248 loc) · 8.13 KB
/
resource_openstack_compute_floatingip_associate_v2.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package openstack
import (
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
nfloatingips "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips"
)
func resourceComputeFloatingIPAssociateV2() *schema.Resource {
return &schema.Resource{
Create: resourceComputeFloatingIPAssociateV2Create,
Read: resourceComputeFloatingIPAssociateV2Read,
Delete: resourceComputeFloatingIPAssociateV2Delete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"floating_ip": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"fixed_ip": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"wait_until_associated": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceComputeFloatingIPAssociateV2Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
floatingIP := d.Get("floating_ip").(string)
fixedIP := d.Get("fixed_ip").(string)
instanceId := d.Get("instance_id").(string)
associateOpts := floatingips.AssociateOpts{
FloatingIP: floatingIP,
FixedIP: fixedIP,
}
log.Printf("[DEBUG] Associate Options: %#v", associateOpts)
err = floatingips.AssociateInstance(computeClient, instanceId, associateOpts).ExtractErr()
if err != nil {
return fmt.Errorf("Error associating Floating IP: %s", err)
}
// This API call should be synchronous, but we've had reports where it isn't.
// If the user opted in to wait for association, then poll here.
var waitUntilAssociated bool
if v, ok := d.GetOkExists("wait_until_associated"); ok {
if wua, ok := v.(bool); ok {
waitUntilAssociated = wua
}
}
if waitUntilAssociated {
log.Printf("[DEBUG] Waiting until %s is associated with %s", instanceId, floatingIP)
stateConf := &resource.StateChangeConf{
Pending: []string{"NOT_ASSOCIATED"},
Target: []string{"ASSOCIATED"},
Refresh: resourceComputeFloatingIPAssociateV2CheckAssociation(computeClient, instanceId, floatingIP),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 0,
MinTimeout: 3 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
return err
}
}
// There's an API call to get this information, but it has been
// deprecated. The Neutron API could be used, but I'm trying not
// to mix service APIs. Therefore, a faux ID will be used.
id := fmt.Sprintf("%s/%s/%s", floatingIP, instanceId, fixedIP)
d.SetId(id)
return resourceComputeFloatingIPAssociateV2Read(d, meta)
}
func resourceComputeFloatingIPAssociateV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
// Obtain relevant info from parsing the ID
floatingIP, instanceId, fixedIP, err := parseComputeFloatingIPAssociateId(d.Id())
if err != nil {
return err
}
// Now check and see whether the floating IP still exists.
// First try to do this by querying the Network API.
networkEnabled := true
networkClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
networkEnabled = false
}
var exists bool
if networkEnabled {
log.Printf("[DEBUG] Checking for Floating IP existence via Network API")
exists, err = resourceComputeFloatingIPAssociateV2NetworkExists(networkClient, floatingIP)
} else {
log.Printf("[DEBUG] Checking for Floating IP existence via Compute API")
exists, err = resourceComputeFloatingIPAssociateV2ComputeExists(computeClient, floatingIP)
}
if err != nil {
return err
}
if !exists {
d.SetId("")
}
// Next, see if the instance still exists
instance, err := servers.Get(computeClient, instanceId).Extract()
if err != nil {
if CheckDeleted(d, err, "instance") == nil {
return nil
}
}
// Finally, check and see if the floating ip is still associated with the instance.
var associated bool
for _, networkAddresses := range instance.Addresses {
for _, element := range networkAddresses.([]interface{}) {
address := element.(map[string]interface{})
if address["OS-EXT-IPS:type"] == "floating" && address["addr"] == floatingIP {
associated = true
}
}
}
if !associated {
d.SetId("")
}
// Set the attributes pulled from the composed resource ID
d.Set("floating_ip", floatingIP)
d.Set("instance_id", instanceId)
d.Set("fixed_ip", fixedIP)
d.Set("region", GetRegion(d, config))
return nil
}
func resourceComputeFloatingIPAssociateV2Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
floatingIP := d.Get("floating_ip").(string)
instanceId := d.Get("instance_id").(string)
disassociateOpts := floatingips.DisassociateOpts{
FloatingIP: floatingIP,
}
log.Printf("[DEBUG] Disssociate Options: %#v", disassociateOpts)
err = floatingips.DisassociateInstance(computeClient, instanceId, disassociateOpts).ExtractErr()
if err != nil {
return CheckDeleted(d, err, "floating ip association")
}
return nil
}
func parseComputeFloatingIPAssociateId(id string) (string, string, string, error) {
idParts := strings.Split(id, "/")
if len(idParts) < 3 {
return "", "", "", fmt.Errorf("Unable to determine floating ip association ID")
}
floatingIP := idParts[0]
instanceId := idParts[1]
fixedIP := idParts[2]
return floatingIP, instanceId, fixedIP, nil
}
func resourceComputeFloatingIPAssociateV2NetworkExists(networkClient *gophercloud.ServiceClient, floatingIP string) (bool, error) {
listOpts := nfloatingips.ListOpts{
FloatingIP: floatingIP,
}
allPages, err := nfloatingips.List(networkClient, listOpts).AllPages()
if err != nil {
return false, err
}
allFips, err := nfloatingips.ExtractFloatingIPs(allPages)
if err != nil {
return false, err
}
if len(allFips) > 1 {
return false, fmt.Errorf("There was a problem retrieving the floating IP")
}
if len(allFips) == 0 {
return false, nil
}
return true, nil
}
func resourceComputeFloatingIPAssociateV2ComputeExists(computeClient *gophercloud.ServiceClient, floatingIP string) (bool, error) {
// If the Network API isn't available, fall back to the deprecated Compute API.
allPages, err := floatingips.List(computeClient).AllPages()
if err != nil {
return false, err
}
allFips, err := floatingips.ExtractFloatingIPs(allPages)
if err != nil {
return false, err
}
for _, f := range allFips {
if f.IP == floatingIP {
return true, nil
}
}
return false, nil
}
func resourceComputeFloatingIPAssociateV2CheckAssociation(
computeClient *gophercloud.ServiceClient, instanceId, floatingIP string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
instance, err := servers.Get(computeClient, instanceId).Extract()
if err != nil {
return instance, "", err
}
var associated bool
for _, networkAddresses := range instance.Addresses {
for _, element := range networkAddresses.([]interface{}) {
address := element.(map[string]interface{})
if address["OS-EXT-IPS:type"] == "floating" && address["addr"] == floatingIP {
associated = true
}
}
}
if associated {
return instance, "ASSOCIATED", nil
}
return instance, "NOT_ASSOCIATED", nil
}
}