-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
resource_aws_vpc_endpoint_service.go
279 lines (241 loc) · 8.58 KB
/
resource_aws_vpc_endpoint_service.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
package aws
import (
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsVpcEndpointService() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVpcEndpointServiceCreate,
Read: resourceAwsVpcEndpointServiceRead,
Update: resourceAwsVpcEndpointServiceUpdate,
Delete: resourceAwsVpcEndpointServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"acceptance_required": {
Type: schema.TypeBool,
Required: true,
},
"network_load_balancer_arns": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"allowed_principals": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"service_name": {
Type: schema.TypeString,
Computed: true,
},
"service_type": {
Type: schema.TypeString,
Computed: true,
},
"availability_zones": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Set: schema.HashString,
},
"private_dns_name": {
Type: schema.TypeString,
Computed: true,
},
"base_endpoint_dns_names": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Set: schema.HashString,
},
},
}
}
func resourceAwsVpcEndpointServiceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
req := &ec2.CreateVpcEndpointServiceConfigurationInput{
AcceptanceRequired: aws.Bool(d.Get("acceptance_required").(bool)),
NetworkLoadBalancerArns: expandStringSet(d.Get("network_load_balancer_arns").(*schema.Set)),
}
log.Printf("[DEBUG] Creating VPC Endpoint Service configuration: %#v", req)
resp, err := conn.CreateVpcEndpointServiceConfiguration(req)
if err != nil {
return fmt.Errorf("Error creating VPC Endpoint Service configuration: %s", err.Error())
}
d.SetId(aws.StringValue(resp.ServiceConfiguration.ServiceId))
if err := vpcEndpointServiceWaitUntilAvailable(d, conn); err != nil {
return err
}
return resourceAwsVpcEndpointServiceUpdate(d, meta)
}
func resourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
svcCfg, state, err := vpcEndpointServiceStateRefresh(conn, d.Id())()
if err != nil && state != ec2.ServiceStateFailed {
return fmt.Errorf("Error reading VPC Endpoint Service: %s", err.Error())
}
terminalStates := map[string]bool{
ec2.ServiceStateDeleted: true,
ec2.ServiceStateDeleting: true,
ec2.ServiceStateFailed: true,
}
if _, ok := terminalStates[state]; ok {
log.Printf("[WARN] VPC Endpoint Service (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return vpcEndpointServiceAttributes(d, svcCfg.(*ec2.ServiceConfiguration), conn)
}
func resourceAwsVpcEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
d.Partial(true)
svcId := d.Id()
modifyCfgReq := &ec2.ModifyVpcEndpointServiceConfigurationInput{
ServiceId: aws.String(svcId),
}
modifyCfg := false
if d.HasChange("acceptance_required") {
modifyCfgReq.AcceptanceRequired = aws.Bool(d.Get("acceptance_required").(bool))
modifyCfg = true
}
if setVpcEndpointServiceUpdateLists(d, "network_load_balancer_arns",
&modifyCfgReq.AddNetworkLoadBalancerArns, &modifyCfgReq.RemoveNetworkLoadBalancerArns) {
modifyCfg = true
}
if modifyCfg {
log.Printf("[DEBUG] Modifying VPC Endpoint Service configuration: %#v", modifyCfgReq)
if _, err := conn.ModifyVpcEndpointServiceConfiguration(modifyCfgReq); err != nil {
return fmt.Errorf("Error modifying VPC Endpoint Service configuration: %s", err.Error())
}
if err := vpcEndpointServiceWaitUntilAvailable(d, conn); err != nil {
return err
}
d.SetPartial("network_load_balancer_arns")
}
modifyPermReq := &ec2.ModifyVpcEndpointServicePermissionsInput{
ServiceId: aws.String(svcId),
}
if setVpcEndpointServiceUpdateLists(d, "allowed_principals",
&modifyPermReq.AddAllowedPrincipals, &modifyPermReq.RemoveAllowedPrincipals) {
log.Printf("[DEBUG] Modifying VPC Endpoint Service permissions: %#v", modifyPermReq)
if _, err := conn.ModifyVpcEndpointServicePermissions(modifyPermReq); err != nil {
return fmt.Errorf("Error modifying VPC Endpoint Service permissions: %s", err.Error())
}
d.SetPartial("allowed_principals")
}
d.Partial(false)
return resourceAwsVpcEndpointServiceRead(d, meta)
}
func resourceAwsVpcEndpointServiceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
log.Printf("[DEBUG] Deleting VPC Endpoint Service: %s", d.Id())
_, err := conn.DeleteVpcEndpointServiceConfigurations(&ec2.DeleteVpcEndpointServiceConfigurationsInput{
ServiceIds: aws.StringSlice([]string{d.Id()}),
})
if err != nil {
if isAWSErr(err, "InvalidVpcEndpointServiceId.NotFound", "") {
log.Printf("[DEBUG] VPC Endpoint Service %s is already gone", d.Id())
} else {
return fmt.Errorf("Error deleting VPC Endpoint Service: %s", err.Error())
}
}
stateConf := &resource.StateChangeConf{
Pending: []string{ec2.ServiceStateAvailable, ec2.ServiceStateDeleting},
Target: []string{ec2.ServiceStateDeleted},
Refresh: vpcEndpointServiceStateRefresh(conn, d.Id()),
Timeout: 10 * time.Minute,
Delay: 5 * time.Second,
MinTimeout: 5 * time.Second,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for VPC Endpoint Service %s to delete: %s", d.Id(), err.Error())
}
return nil
}
func vpcEndpointServiceStateRefresh(conn *ec2.EC2, svcId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("[DEBUG] Reading VPC Endpoint Service Configuration: %s", svcId)
resp, err := conn.DescribeVpcEndpointServiceConfigurations(&ec2.DescribeVpcEndpointServiceConfigurationsInput{
ServiceIds: aws.StringSlice([]string{svcId}),
})
if err != nil {
if isAWSErr(err, "InvalidVpcEndpointServiceId.NotFound", "") {
return false, ec2.ServiceStateDeleted, nil
}
return nil, "", err
}
svcCfg := resp.ServiceConfigurations[0]
state := aws.StringValue(svcCfg.ServiceState)
// No use in retrying if the endpoint service is in a failed state.
if state == ec2.ServiceStateFailed {
return nil, state, errors.New("VPC Endpoint Service is in a failed state")
}
return svcCfg, state, nil
}
}
func vpcEndpointServiceWaitUntilAvailable(d *schema.ResourceData, conn *ec2.EC2) error {
stateConf := &resource.StateChangeConf{
Pending: []string{ec2.ServiceStatePending},
Target: []string{ec2.ServiceStateAvailable},
Refresh: vpcEndpointServiceStateRefresh(conn, d.Id()),
Timeout: 10 * time.Minute,
Delay: 5 * time.Second,
MinTimeout: 5 * time.Second,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for VPC Endpoint Service %s to become available: %s", d.Id(), err.Error())
}
return nil
}
func vpcEndpointServiceAttributes(d *schema.ResourceData, svcCfg *ec2.ServiceConfiguration, conn *ec2.EC2) error {
d.Set("acceptance_required", svcCfg.AcceptanceRequired)
d.Set("network_load_balancer_arns", flattenStringList(svcCfg.NetworkLoadBalancerArns))
d.Set("state", svcCfg.ServiceState)
d.Set("service_name", svcCfg.ServiceName)
d.Set("service_type", svcCfg.ServiceType[0].ServiceType)
d.Set("availability_zones", flattenStringList(svcCfg.AvailabilityZones))
d.Set("private_dns_name", svcCfg.PrivateDnsName)
d.Set("base_endpoint_dns_names", flattenStringList(svcCfg.BaseEndpointDnsNames))
resp, err := conn.DescribeVpcEndpointServicePermissions(&ec2.DescribeVpcEndpointServicePermissionsInput{
ServiceId: aws.String(d.Id()),
})
if err != nil {
return err
}
d.Set("allowed_principals", flattenVpcEndpointServiceAllowedPrincipals(resp.AllowedPrincipals))
return nil
}
func setVpcEndpointServiceUpdateLists(d *schema.ResourceData, key string, a, r *[]*string) bool {
if !d.HasChange(key) {
return false
}
o, n := d.GetChange(key)
os := o.(*schema.Set)
ns := n.(*schema.Set)
add := expandStringList(ns.Difference(os).List())
if len(add) > 0 {
*a = add
}
remove := expandStringList(os.Difference(ns).List())
if len(remove) > 0 {
*r = remove
}
return true
}