-
Notifications
You must be signed in to change notification settings - Fork 9.2k
/
resource_aws_acm_certificate.go
360 lines (314 loc) · 11.1 KB
/
resource_aws_acm_certificate.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package aws
import (
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsAcmCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAwsAcmCertificateCreate,
Read: resourceAwsAcmCertificateRead,
Update: resourceAwsAcmCertificateUpdate,
Delete: resourceAwsAcmCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"certificate_body": {
Type: schema.TypeString,
Optional: true,
StateFunc: normalizeCert,
},
"certificate_chain": {
Type: schema.TypeString,
Optional: true,
StateFunc: normalizeCert,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
StateFunc: normalizeCert,
Sensitive: true,
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"},
StateFunc: func(v interface{}) string {
// AWS Provider 1.42.0+ aws_route53_zone references may contain a
// trailing period, which generates an ACM API error
return strings.TrimSuffix(v.(string), ".")
},
},
"subject_alternative_names": {
Type: schema.TypeList,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"},
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: func(v interface{}) string {
// AWS Provider 1.42.0+ aws_route53_zone references may contain a
// trailing period, which generates an ACM API error
return strings.TrimSuffix(v.(string), ".")
},
},
},
"validation_method": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"},
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"domain_validation_options": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_record_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_record_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_record_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"validation_emails": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tagsSchema(),
},
}
}
func resourceAwsAcmCertificateCreate(d *schema.ResourceData, meta interface{}) error {
if _, ok := d.GetOk("domain_name"); ok {
if _, ok := d.GetOk("validation_method"); !ok {
return errors.New("validation_method must be set when creating a certificate")
}
return resourceAwsAcmCertificateCreateRequested(d, meta)
} else if _, ok := d.GetOk("private_key"); ok {
if _, ok := d.GetOk("certificate_body"); !ok {
return errors.New("certificate_body must be set when importing a certificate with private_key")
}
return resourceAwsAcmCertificateCreateImported(d, meta)
}
return errors.New("certificate must be imported (private_key) or created (domain_name)")
}
func resourceAwsAcmCertificateCreateImported(d *schema.ResourceData, meta interface{}) error {
acmconn := meta.(*AWSClient).acmconn
resp, err := resourceAwsAcmCertificateImport(acmconn, d, false)
if err != nil {
return fmt.Errorf("Error importing certificate: %s", err)
}
d.SetId(*resp.CertificateArn)
if v, ok := d.GetOk("tags"); ok {
params := &acm.AddTagsToCertificateInput{
CertificateArn: resp.CertificateArn,
Tags: tagsFromMapACM(v.(map[string]interface{})),
}
_, err := acmconn.AddTagsToCertificate(params)
if err != nil {
return fmt.Errorf("Error requesting certificate: %s", err)
}
}
return resourceAwsAcmCertificateRead(d, meta)
}
func resourceAwsAcmCertificateCreateRequested(d *schema.ResourceData, meta interface{}) error {
acmconn := meta.(*AWSClient).acmconn
params := &acm.RequestCertificateInput{
DomainName: aws.String(strings.TrimSuffix(d.Get("domain_name").(string), ".")),
ValidationMethod: aws.String(d.Get("validation_method").(string)),
}
if sans, ok := d.GetOk("subject_alternative_names"); ok {
subjectAlternativeNames := make([]*string, len(sans.([]interface{})))
for i, sanRaw := range sans.([]interface{}) {
subjectAlternativeNames[i] = aws.String(strings.TrimSuffix(sanRaw.(string), "."))
}
params.SubjectAlternativeNames = subjectAlternativeNames
}
log.Printf("[DEBUG] ACM Certificate Request: %#v", params)
resp, err := acmconn.RequestCertificate(params)
if err != nil {
return fmt.Errorf("Error requesting certificate: %s", err)
}
d.SetId(*resp.CertificateArn)
if v, ok := d.GetOk("tags"); ok {
params := &acm.AddTagsToCertificateInput{
CertificateArn: resp.CertificateArn,
Tags: tagsFromMapACM(v.(map[string]interface{})),
}
_, err := acmconn.AddTagsToCertificate(params)
if err != nil {
return fmt.Errorf("Error requesting certificate: %s", err)
}
}
return resourceAwsAcmCertificateRead(d, meta)
}
func resourceAwsAcmCertificateRead(d *schema.ResourceData, meta interface{}) error {
acmconn := meta.(*AWSClient).acmconn
params := &acm.DescribeCertificateInput{
CertificateArn: aws.String(d.Id()),
}
return resource.Retry(time.Duration(1)*time.Minute, func() *resource.RetryError {
resp, err := acmconn.DescribeCertificate(params)
if err != nil {
if isAWSErr(err, acm.ErrCodeResourceNotFoundException, "") {
d.SetId("")
return nil
}
return resource.NonRetryableError(fmt.Errorf("Error describing certificate: %s", err))
}
d.Set("domain_name", resp.Certificate.DomainName)
d.Set("arn", resp.Certificate.CertificateArn)
if err := d.Set("subject_alternative_names", cleanUpSubjectAlternativeNames(resp.Certificate)); err != nil {
return resource.NonRetryableError(err)
}
domainValidationOptions, emailValidationOptions, err := convertValidationOptions(resp.Certificate)
if err != nil {
return resource.RetryableError(err)
}
if err := d.Set("domain_validation_options", domainValidationOptions); err != nil {
return resource.NonRetryableError(err)
}
if err := d.Set("validation_emails", emailValidationOptions); err != nil {
return resource.NonRetryableError(err)
}
d.Set("validation_method", resourceAwsAcmCertificateGuessValidationMethod(domainValidationOptions, emailValidationOptions))
params := &acm.ListTagsForCertificateInput{
CertificateArn: aws.String(d.Id()),
}
tagResp, err := acmconn.ListTagsForCertificate(params)
if err != nil {
return resource.NonRetryableError(fmt.Errorf("error listing tags for certificate (%s): %s", d.Id(), err))
}
if err := d.Set("tags", tagsToMapACM(tagResp.Tags)); err != nil {
return resource.NonRetryableError(err)
}
return nil
})
}
func resourceAwsAcmCertificateGuessValidationMethod(domainValidationOptions []map[string]interface{}, emailValidationOptions []string) string {
// The DescribeCertificate Response doesn't have information on what validation method was used
// so we need to guess from the validation options we see...
if len(domainValidationOptions) > 0 {
return acm.ValidationMethodDns
} else if len(emailValidationOptions) > 0 {
return acm.ValidationMethodEmail
} else {
return "NONE"
}
}
func resourceAwsAcmCertificateUpdate(d *schema.ResourceData, meta interface{}) error {
acmconn := meta.(*AWSClient).acmconn
if d.HasChange("private_key") || d.HasChange("certificate_body") || d.HasChange("certificate_chain") {
_, err := resourceAwsAcmCertificateImport(acmconn, d, true)
if err != nil {
return fmt.Errorf("Error updating certificate: %s", err)
}
}
if d.HasChange("tags") {
err := setTagsACM(acmconn, d)
if err != nil {
return err
}
}
return resourceAwsAcmCertificateRead(d, meta)
}
func cleanUpSubjectAlternativeNames(cert *acm.CertificateDetail) []string {
sans := cert.SubjectAlternativeNames
vs := make([]string, 0)
for _, v := range sans {
if aws.StringValue(v) != aws.StringValue(cert.DomainName) {
vs = append(vs, aws.StringValue(v))
}
}
return vs
}
func convertValidationOptions(certificate *acm.CertificateDetail) ([]map[string]interface{}, []string, error) {
var domainValidationResult []map[string]interface{}
var emailValidationResult []string
if *certificate.Type == acm.CertificateTypeAmazonIssued {
for _, o := range certificate.DomainValidationOptions {
if o.ResourceRecord != nil {
validationOption := map[string]interface{}{
"domain_name": *o.DomainName,
"resource_record_name": *o.ResourceRecord.Name,
"resource_record_type": *o.ResourceRecord.Type,
"resource_record_value": *o.ResourceRecord.Value,
}
domainValidationResult = append(domainValidationResult, validationOption)
} else if o.ValidationEmails != nil && len(o.ValidationEmails) > 0 {
for _, validationEmail := range o.ValidationEmails {
emailValidationResult = append(emailValidationResult, *validationEmail)
}
} else if o.ValidationStatus == nil || aws.StringValue(o.ValidationStatus) == acm.DomainStatusPendingValidation {
log.Printf("[DEBUG] No validation options need to retry: %#v", o)
return nil, nil, fmt.Errorf("No validation options need to retry: %#v", o)
}
}
}
return domainValidationResult, emailValidationResult, nil
}
func resourceAwsAcmCertificateDelete(d *schema.ResourceData, meta interface{}) error {
acmconn := meta.(*AWSClient).acmconn
log.Printf("[INFO] Deleting ACM Certificate: %s", d.Id())
params := &acm.DeleteCertificateInput{
CertificateArn: aws.String(d.Id()),
}
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
_, err := acmconn.DeleteCertificate(params)
if err != nil {
if isAWSErr(err, acm.ErrCodeResourceInUseException, "") {
log.Printf("[WARN] Conflict deleting certificate in use: %s, retrying", err.Error())
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil && !isAWSErr(err, acm.ErrCodeResourceNotFoundException, "") {
return fmt.Errorf("Error deleting certificate: %s", err)
}
return nil
}
func resourceAwsAcmCertificateImport(conn *acm.ACM, d *schema.ResourceData, update bool) (*acm.ImportCertificateOutput, error) {
params := &acm.ImportCertificateInput{
PrivateKey: []byte(d.Get("private_key").(string)),
Certificate: []byte(d.Get("certificate_body").(string)),
}
if chain, ok := d.GetOk("certificate_chain"); ok {
params.CertificateChain = []byte(chain.(string))
}
if update {
params.CertificateArn = aws.String(d.Get("arn").(string))
}
log.Printf("[DEBUG] ACM Certificate Import: %#v", params)
return conn.ImportCertificate(params)
}