/
resource_ibm_resource_tag.go
306 lines (263 loc) · 8.66 KB
/
resource_ibm_resource_tag.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package globaltagging
import (
"context"
"fmt"
"os"
"strings"
"github.com/IBM/platform-services-go-sdk/globaltaggingv1"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
)
const (
resourceID = "resource_id"
tags = "tags"
resourceType = "resource_type"
tagType = "tag_type"
acccountID = "acccount_id"
service = "service"
)
func ResourceIBMResourceTag() *schema.Resource {
return &schema.Resource{
Create: resourceIBMResourceTagCreate,
Read: resourceIBMResourceTagRead,
Update: resourceIBMResourceTagUpdate,
Delete: resourceIBMResourceTagDelete,
Importer: &schema.ResourceImporter{},
CustomizeDiff: customdiff.Sequence(
func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error {
return flex.ResourceTagsCustomizeDiff(diff)
},
),
Schema: map[string]*schema.Schema{
resourceID: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.InvokeValidator("ibm_resource_tag", resourceID),
Description: "CRN of the resource on which the tags should be attached",
},
tags: {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString, ValidateFunc: validate.InvokeValidator("ibm_resource_tag", tags)},
Set: flex.ResourceIBMVPCHash,
Description: "List of tags associated with resource instance",
},
resourceType: {
Type: schema.TypeString,
Optional: true,
Description: "Resource type on which the tags should be attached",
},
tagType: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validate.InvokeValidator("ibm_resource_tag", tagType),
Description: "Type of the tag. Only allowed values are: user, or service or access (default value : user)",
},
acccountID: {
Type: schema.TypeString,
Computed: true,
Description: "The ID of the account that owns the resources to be tagged (required if tag-type is set to service)",
},
},
}
}
func ResourceIBMResourceTagValidator() *validate.ResourceValidator {
tagTypeAllowedValues := "service,access,user"
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: resourceID,
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Required: true,
Regexp: `^crn:v1(:[a-zA-Z0-9 \-\._~\*\+,;=!$&'\(\)\/\?#\[\]@]*){8}$|^[0-9]+$`,
MinValueLength: 1,
MaxValueLength: 1024})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: tags,
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Optional: true,
Regexp: `^[A-Za-z0-9:_ .-]+$`,
MinValueLength: 1,
MaxValueLength: 128})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "tag_type",
ValidateFunctionIdentifier: validate.ValidateAllowedStringValue,
Type: validate.TypeString,
Optional: true,
AllowedValues: tagTypeAllowedValues})
ibmResourceTagValidator := validate.ResourceValidator{ResourceName: "ibm_resource_tag", Schema: validateSchema}
return &ibmResourceTagValidator
}
func resourceIBMResourceTagCreate(d *schema.ResourceData, meta interface{}) error {
var rType, tType string
resources := []globaltaggingv1.Resource{}
userDetails, err := meta.(conns.ClientSession).BluemixUserDetails()
if err != nil {
return err
}
accountID := userDetails.UserAccount
gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1()
if err != nil {
return fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err)
}
resourceID := d.Get(resourceID).(string)
if v, ok := d.GetOk(resourceType); ok && v != nil {
rType = v.(string)
}
r := globaltaggingv1.Resource{ResourceID: flex.PtrToString(resourceID), ResourceType: flex.PtrToString(rType)}
resources = append(resources, r)
var add []string
if v, ok := d.GetOk(tags); ok {
tags := v.(*schema.Set)
for _, t := range tags.List() {
add = append(add, fmt.Sprint(t))
}
}
AttachTagOptions := &globaltaggingv1.AttachTagOptions{}
AttachTagOptions.Resources = resources
AttachTagOptions.TagNames = add
if v, ok := d.GetOk(tagType); ok && v != nil {
tType = v.(string)
AttachTagOptions.TagType = flex.PtrToString(tType)
if tType == service {
AttachTagOptions.AccountID = flex.PtrToString(accountID)
}
}
// Fetch tags from schematics only if they are user tags
if strings.TrimSpace(tagType) == "" || tagType == "user" {
schematicTags := os.Getenv("IC_ENV_TAGS")
var envTags []string
if schematicTags != "" {
envTags = strings.Split(schematicTags, ",")
add = append(add, envTags...)
}
}
if len(add) > 0 {
_, resp, err := gtClient.AttachTag(AttachTagOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error attaching resource tags : %v\n%s", resp, err)
}
}
if strings.HasPrefix(resourceID, "crn:") {
d.SetId(resourceID)
} else {
d.SetId(fmt.Sprintf("%s/%s", resourceID, rType))
}
return resourceIBMResourceTagRead(d, meta)
}
func resourceIBMResourceTagRead(d *schema.ResourceData, meta interface{}) error {
var rID, rType, tType string
userDetails, err := meta.(conns.ClientSession).BluemixUserDetails()
if err != nil {
return err
}
acctID := userDetails.UserAccount
if strings.HasPrefix(d.Id(), "crn:") {
rID = d.Id()
} else {
parts, err := flex.VmIdParts(d.Id())
if err != nil {
return err
}
if len(parts) < 2 {
return fmt.Errorf("[ERROR] Incorrect ID %s: Id should be a combination of resourceID/resourceType", d.Id())
}
rID = parts[0]
rType = parts[1]
}
if v, ok := d.GetOk(tagType); ok && v != nil {
tType = v.(string)
if tType == service {
d.Set(acccountID, acctID)
}
}
tagList, err := flex.GetGlobalTagsUsingSearchAPI(meta, rID, rType, tType)
if err != nil {
return fmt.Errorf("[ERROR] Error getting resource tags for: %s with error : %s", rID, err)
}
d.Set(resourceID, rID)
d.Set(resourceType, rType)
d.Set(tags, tagList)
return nil
}
func resourceIBMResourceTagUpdate(d *schema.ResourceData, meta interface{}) error {
var rID, rType, tType string
if strings.HasPrefix(d.Id(), "crn:") {
rID = d.Id()
} else {
parts, err := flex.VmIdParts(d.Id())
if err != nil {
return err
}
rID = parts[0]
rType = parts[1]
}
if v, ok := d.GetOk(tagType); ok && v != nil {
tType = v.(string)
}
if _, ok := d.GetOk(tags); ok {
oldList, newList := d.GetChange(tags)
err := flex.UpdateGlobalTagsUsingCRN(oldList, newList, meta, rID, rType, tType)
if err != nil {
return fmt.Errorf("[ERROR] Error on create of resource tags: %s", err)
}
}
return resourceIBMResourceTagRead(d, meta)
}
func resourceIBMResourceTagDelete(d *schema.ResourceData, meta interface{}) error {
var rID, rType string
if strings.HasPrefix(d.Id(), "crn:") {
rID = d.Id()
} else {
parts, err := flex.VmIdParts(d.Id())
if err != nil {
return err
}
rID = parts[0]
rType = parts[1]
}
gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1()
if err != nil {
return fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err)
}
var remove []string
removeTags := d.Get(tags).(*schema.Set)
remove = make([]string, len(removeTags.List()))
for i, v := range removeTags.List() {
remove[i] = fmt.Sprint(v)
}
if len(remove) > 0 {
resources := []globaltaggingv1.Resource{}
r := globaltaggingv1.Resource{ResourceID: flex.PtrToString(rID), ResourceType: flex.PtrToString(rType)}
resources = append(resources, r)
detachTagOptions := &globaltaggingv1.DetachTagOptions{
Resources: resources,
TagNames: remove,
}
_, resp, err := gtClient.DetachTag(detachTagOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error detaching resource tags %v: %s\n%s", remove, err, resp)
}
for _, v := range remove {
delTagOptions := &globaltaggingv1.DeleteTagOptions{
TagName: flex.PtrToString(v),
}
_, resp, err := gtClient.DeleteTag(delTagOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error deleting resource tag %v: %s\n%s", v, err, resp)
}
}
}
return nil
}