-
Notifications
You must be signed in to change notification settings - Fork 9.2k
/
group.go
260 lines (215 loc) · 7.18 KB
/
group.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
package cloudwatchlogs
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)
func ResourceGroup() *schema.Resource {
return &schema.Resource{
Create: resourceGroupCreate,
Read: resourceGroupRead,
Update: resourceGroupUpdate,
Delete: resourceGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validLogGroupName,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validLogGroupNamePrefix,
},
"retention_in_days": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntInSlice([]int{0, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653}),
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
},
CustomizeDiff: verify.SetTagsDiff,
}
}
func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).CloudWatchLogsConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))
var logGroupName string
if v, ok := d.GetOk("name"); ok {
logGroupName = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
logGroupName = resource.PrefixedUniqueId(v.(string))
} else {
logGroupName = resource.UniqueId()
}
log.Printf("[DEBUG] Creating CloudWatch Log Group: %s", logGroupName)
params := &cloudwatchlogs.CreateLogGroupInput{
LogGroupName: aws.String(logGroupName),
}
if v, ok := d.GetOk("kms_key_id"); ok {
params.KmsKeyId = aws.String(v.(string))
}
if len(tags) > 0 {
params.Tags = Tags(tags.IgnoreAWS())
}
_, err := conn.CreateLogGroup(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == cloudwatchlogs.ErrCodeResourceAlreadyExistsException {
return fmt.Errorf("Creating CloudWatch Log Group failed: %s: The CloudWatch Log Group '%s' already exists.", err, d.Get("name").(string))
}
return fmt.Errorf("Creating CloudWatch Log Group failed: %s '%s'", err, d.Get("name"))
}
d.SetId(logGroupName)
log.Println("[INFO] CloudWatch Log Group created")
if v, ok := d.GetOk("retention_in_days"); ok {
input := cloudwatchlogs.PutRetentionPolicyInput{
LogGroupName: aws.String(logGroupName),
RetentionInDays: aws.Int64(int64(v.(int))),
}
log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", logGroupName, input)
_, err = conn.PutRetentionPolicy(&input)
if err != nil {
return err
}
}
return resourceGroupRead(d, meta)
}
func resourceGroupRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).CloudWatchLogsConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig
log.Printf("[DEBUG] Reading CloudWatch Log Group: %q", d.Get("name").(string))
lg, err := LookupGroup(conn, d.Id())
if err != nil {
return err
}
if lg == nil {
log.Printf("[DEBUG] CloudWatch Group %q Not Found", d.Id())
d.SetId("")
return nil
}
d.Set("arn", TrimLogGroupARNWildcardSuffix(aws.StringValue(lg.Arn)))
d.Set("name", lg.LogGroupName)
d.Set("kms_key_id", lg.KmsKeyId)
d.Set("retention_in_days", lg.RetentionInDays)
tags, err := ListTags(conn, d.Id())
if err != nil {
return fmt.Errorf("error listing tags for CloudWatch Logs Group (%s): %s", d.Id(), err)
}
tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)
//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %w", err)
}
if err := d.Set("tags_all", tags.Map()); err != nil {
return fmt.Errorf("error setting tags_all: %w", err)
}
return nil
}
func LookupGroup(conn *cloudwatchlogs.CloudWatchLogs, name string) (*cloudwatchlogs.LogGroup, error) {
input := &cloudwatchlogs.DescribeLogGroupsInput{
LogGroupNamePrefix: aws.String(name),
}
var logGroup *cloudwatchlogs.LogGroup
err := conn.DescribeLogGroupsPages(input, func(page *cloudwatchlogs.DescribeLogGroupsOutput, lastPage bool) bool {
for _, lg := range page.LogGroups {
if aws.StringValue(lg.LogGroupName) == name {
logGroup = lg
return false
}
}
return !lastPage
})
if err != nil {
return nil, err
}
return logGroup, nil
}
func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).CloudWatchLogsConn
name := d.Id()
log.Printf("[DEBUG] Updating CloudWatch Log Group: %q", name)
if d.HasChange("retention_in_days") {
var err error
if v, ok := d.GetOk("retention_in_days"); ok {
input := cloudwatchlogs.PutRetentionPolicyInput{
LogGroupName: aws.String(name),
RetentionInDays: aws.Int64(int64(v.(int))),
}
log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", name, input)
_, err = conn.PutRetentionPolicy(&input)
} else {
log.Printf("[DEBUG] Deleting retention for CloudWatch Log Group: %q", name)
_, err = conn.DeleteRetentionPolicy(&cloudwatchlogs.DeleteRetentionPolicyInput{
LogGroupName: aws.String(name),
})
}
if err != nil {
return err
}
}
if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")
if err := UpdateTags(conn, d.Id(), o, n); err != nil {
return fmt.Errorf("error updating CloudWatch Log Group (%s) tags: %s", d.Id(), err)
}
}
if d.HasChange("kms_key_id") && !d.IsNewResource() {
_, newKey := d.GetChange("kms_key_id")
if newKey.(string) == "" {
_, err := conn.DisassociateKmsKey(&cloudwatchlogs.DisassociateKmsKeyInput{
LogGroupName: aws.String(name),
})
if err != nil {
return err
}
} else {
_, err := conn.AssociateKmsKey(&cloudwatchlogs.AssociateKmsKeyInput{
LogGroupName: aws.String(name),
KmsKeyId: aws.String(newKey.(string)),
})
if err != nil {
return err
}
}
}
return resourceGroupRead(d, meta)
}
func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).CloudWatchLogsConn
log.Printf("[INFO] Deleting CloudWatch Log Group: %s", d.Id())
_, err := conn.DeleteLogGroup(&cloudwatchlogs.DeleteLogGroupInput{
LogGroupName: aws.String(d.Get("name").(string)),
})
if err != nil {
return fmt.Errorf("Error deleting CloudWatch Log Group: %s", err)
}
log.Println("[INFO] CloudWatch Log Group deleted")
return nil
}