forked from hashicorp/terraform-provider-aws
/
resource_aws_datasync_agent.go
270 lines (221 loc) · 7.45 KB
/
resource_aws_datasync_agent.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
package aws
import (
"fmt"
"log"
"net"
"net/http"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/datasync"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsDataSyncAgent() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDataSyncAgentCreate,
Read: resourceAwsDataSyncAgentRead,
Update: resourceAwsDataSyncAgentUpdate,
Delete: resourceAwsDataSyncAgentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"activation_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"ip_address"},
},
"ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"activation_key"},
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"tags": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAwsDataSyncAgentCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).datasyncconn
region := meta.(*AWSClient).region
activationKey := d.Get("activation_key").(string)
agentIpAddress := d.Get("ip_address").(string)
// Perform one time fetch of activation key from gateway IP address
if activationKey == "" {
if agentIpAddress == "" {
return fmt.Errorf("either activation_key or ip_address must be provided")
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Second * 10,
}
requestURL := fmt.Sprintf("http://%s/?gatewayType=SYNC&activationRegion=%s", agentIpAddress, region)
log.Printf("[DEBUG] Creating HTTP request: %s", requestURL)
request, err := http.NewRequest("GET", requestURL, nil)
if err != nil {
return fmt.Errorf("error creating HTTP request: %s", err)
}
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
log.Printf("[DEBUG] Making HTTP request: %s", request.URL.String())
response, err := client.Do(request)
if err != nil {
if err, ok := err.(net.Error); ok {
errMessage := fmt.Errorf("error making HTTP request: %s", err)
log.Printf("[DEBUG] retryable %s", errMessage)
return resource.RetryableError(errMessage)
}
return resource.NonRetryableError(fmt.Errorf("error making HTTP request: %s", err))
}
log.Printf("[DEBUG] Received HTTP response: %#v", response)
if response.StatusCode != 302 {
return resource.NonRetryableError(fmt.Errorf("expected HTTP status code 302, received: %d", response.StatusCode))
}
redirectURL, err := response.Location()
if err != nil {
return resource.NonRetryableError(fmt.Errorf("error extracting HTTP Location header: %s", err))
}
activationKey = redirectURL.Query().Get("activationKey")
return nil
})
if err != nil {
return fmt.Errorf("error retrieving activation key from IP Address (%s): %s", agentIpAddress, err)
}
if activationKey == "" {
return fmt.Errorf("empty activationKey received from IP Address: %s", agentIpAddress)
}
}
input := &datasync.CreateAgentInput{
ActivationKey: aws.String(activationKey),
Tags: expandDataSyncTagListEntry(d.Get("tags").(map[string]interface{})),
}
if v, ok := d.GetOk("name"); ok {
input.AgentName = aws.String(v.(string))
}
log.Printf("[DEBUG] Creating DataSync Agent: %s", input)
output, err := conn.CreateAgent(input)
if err != nil {
return fmt.Errorf("error creating DataSync Agent: %s", err)
}
d.SetId(aws.StringValue(output.AgentArn))
// Agent activations can take a few minutes
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
_, err := conn.DescribeAgent(&datasync.DescribeAgentInput{
AgentArn: aws.String(d.Id()),
})
if isAWSErr(err, "InvalidRequestException", "not found") {
return resource.RetryableError(err)
}
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("error waiting for DataSync Agent (%s) creation: %s", d.Id(), err)
}
return resourceAwsDataSyncAgentRead(d, meta)
}
func resourceAwsDataSyncAgentRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).datasyncconn
input := &datasync.DescribeAgentInput{
AgentArn: aws.String(d.Id()),
}
log.Printf("[DEBUG] Reading DataSync Agent: %s", input)
output, err := conn.DescribeAgent(input)
if isAWSErr(err, "InvalidRequestException", "not found") {
log.Printf("[WARN] DataSync Agent %q not found - removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading DataSync Agent (%s): %s", d.Id(), err)
}
tagsInput := &datasync.ListTagsForResourceInput{
ResourceArn: output.AgentArn,
}
log.Printf("[DEBUG] Reading DataSync Agent tags: %s", tagsInput)
tagsOutput, err := conn.ListTagsForResource(tagsInput)
if err != nil {
return fmt.Errorf("error reading DataSync Agent (%s) tags: %s", d.Id(), err)
}
d.Set("arn", output.AgentArn)
d.Set("name", output.Name)
if err := d.Set("tags", flattenDataSyncTagListEntry(tagsOutput.Tags)); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}
return nil
}
func resourceAwsDataSyncAgentUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).datasyncconn
if d.HasChange("name") {
input := &datasync.UpdateAgentInput{
AgentArn: aws.String(d.Id()),
Name: aws.String(d.Get("name").(string)),
}
log.Printf("[DEBUG] Updating DataSync Agent: %s", input)
_, err := conn.UpdateAgent(input)
if err != nil {
return fmt.Errorf("error updating DataSync Agent (%s): %s", d.Id(), err)
}
}
if d.HasChange("tags") {
oldRaw, newRaw := d.GetChange("tags")
createTags, removeTags := dataSyncTagsDiff(expandDataSyncTagListEntry(oldRaw.(map[string]interface{})), expandDataSyncTagListEntry(newRaw.(map[string]interface{})))
if len(removeTags) > 0 {
input := &datasync.UntagResourceInput{
Keys: dataSyncTagsKeys(removeTags),
ResourceArn: aws.String(d.Id()),
}
log.Printf("[DEBUG] Untagging DataSync Agent: %s", input)
if _, err := conn.UntagResource(input); err != nil {
return fmt.Errorf("error untagging DataSync Agent (%s): %s", d.Id(), err)
}
}
if len(createTags) > 0 {
input := &datasync.TagResourceInput{
ResourceArn: aws.String(d.Id()),
Tags: createTags,
}
log.Printf("[DEBUG] Tagging DataSync Agent: %s", input)
if _, err := conn.TagResource(input); err != nil {
return fmt.Errorf("error tagging DataSync Agent (%s): %s", d.Id(), err)
}
}
}
return resourceAwsDataSyncAgentRead(d, meta)
}
func resourceAwsDataSyncAgentDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).datasyncconn
input := &datasync.DeleteAgentInput{
AgentArn: aws.String(d.Id()),
}
log.Printf("[DEBUG] Deleting DataSync Agent: %s", input)
_, err := conn.DeleteAgent(input)
if isAWSErr(err, "InvalidRequestException", "not found") {
return nil
}
if err != nil {
return fmt.Errorf("error deleting DataSync Agent (%s): %s", d.Id(), err)
}
return nil
}