-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource_huaweicloud_tms_resource_tags.go
285 lines (257 loc) · 8.47 KB
/
resource_huaweicloud_tms_resource_tags.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
package tms
import (
"context"
"log"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/chnsz/golangsdk"
tags "github.com/chnsz/golangsdk/openstack/tms/v1/resourcetags"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
// @API TMS POST /v1.0/resource-tags/batch-create
// @API TMS POST /v1.0/resource-tags/batch-delete
// @API TMS GET /v2.0/resources/{resource_id}/tags
func ResourceResourceTags() *schema.Resource {
return &schema.Resource{
CreateContext: resourceResourceTagsCreate,
ReadContext: resourceResourceTagsRead,
UpdateContext: resourceResourceTagsUpdate,
DeleteContext: resourceResourceTagsDelete,
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The project ID of the resources.",
},
"resources": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_type": {
Type: schema.TypeString,
Required: true,
Description: "The resource type.",
},
"resource_id": {
Type: schema.TypeString,
Required: true,
Description: "The resource ID.",
},
},
},
Description: "The managed resource configuration.",
},
"tags": {
Type: schema.TypeMap,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Description: "The resource tags for batch management.",
},
},
}
}
func buildResourcesInfo(resources []interface{}) []tags.Resource {
if len(resources) < 1 {
return nil
}
result := make([]tags.Resource, len(resources))
for i, val := range resources {
resource := val.(map[string]interface{})
result[i] = tags.Resource{
ResourceType: resource["resource_type"].(string),
ResourceId: resource["resource_id"].(string),
}
}
return result
}
func expandResourceTags(tagsInput map[string]interface{}) []tags.ResourceTag {
result := make([]tags.ResourceTag, 0, len(tagsInput))
for key, value := range tagsInput {
result = append(result, tags.ResourceTag{
Key: key,
Value: utils.String(value.(string)),
})
}
return result
}
func resourceResourceTagsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
client, err := cfg.TmsV1Client(region)
if err != nil {
return diag.Errorf("error creating TMS v1 client: %s", err)
}
opts := tags.BatchOpts{
ProjectId: d.Get("project_id").(string),
Resources: buildResourcesInfo(d.Get("resources").([]interface{})),
Tags: expandResourceTags(d.Get("tags").(map[string]interface{})),
}
failResp, err := tags.Create(client, opts)
if err != nil {
return diag.Errorf("error creating resource tags: %s", err)
}
if len(failResp) > 0 {
return diag.Errorf("error creating resource tags: %#v", failResp)
}
randUUID, err := uuid.GenerateUUID()
if err != nil {
return diag.Errorf("unable to generate resource ID of the TMS tags management: %s", err)
}
d.SetId(randUUID)
return resourceResourceTagsRead(ctx, d, meta)
}
func FlattenTagsToMap(tagsResp []tags.ResourceTag) map[string]interface{} {
result := make(map[string]interface{})
for _, val := range tagsResp {
result[val.Key] = *val.Value
}
return result
}
func compareTwoTags(localTags, remoteTags map[string]interface{}) (same, diff map[string]interface{}) {
same = make(map[string]interface{})
diff = make(map[string]interface{})
for localKey, localVal := range localTags {
if remoteVal, ok := remoteTags[localKey]; ok {
local, isTypeLocalOk := localVal.(string)
if !isTypeLocalOk {
log.Printf("[WARN] The type of tag key (%s) in the script is incorrect, want 'string', but got '%T'",
localKey, localVal)
continue
}
remote, isTypeRemoteOk := remoteVal.(string)
if !isTypeRemoteOk {
log.Printf("[WARN] The type of tag key (%s) in the remote response is incorrect, want 'string', but got '%T'",
localKey, remoteVal)
continue
}
if local == remote {
same[localKey] = localVal
continue
}
}
diff[localKey] = localVal
}
return
}
func resourceResourceTagsRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
client, err := cfg.TmsV2Client(region)
if err != nil {
return diag.Errorf("error creating TMS v2 client: %s", err)
}
var (
projectId = d.Get("project_id").(string)
resources = d.Get("resources").([]interface{})
resResult = make([]interface{}, 0, len(resources))
tagsInput = d.Get("tags").(map[string]interface{})
)
// Check whether all tagged resources contain the expected tags correctly. If not, inconsistent tags information
// will be printed in the log.
for _, val := range resources {
resource := val.(map[string]interface{})
resourceId := resource["resource_id"].(string)
opts := tags.QueryOpts{
ResourceId: resourceId,
ResourceType: resource["resource_type"].(string),
ProjectId: projectId,
}
resp, err := tags.Get(client, opts)
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
continue
}
return diag.Errorf("error query resource (%s) tags: %s", resourceId, err)
}
actualTags := FlattenTagsToMap(resp)
same, diff := compareTwoTags(tagsInput, actualTags)
if len(diff) > 0 {
log.Printf("[ERROR] The tags of resource (%s) don't contain some tags that are expected to need to be set."+
" It should contain tags (%#v), but some tags were not set successfully: %#v", resourceId, tagsInput,
actualTags)
}
// If the tags are queried from the resource side (even only part of tags are queried), it means that the
// creation or update action of the resource is (partially) successful.
if len(same) > 0 {
resResult = append(resResult, val)
}
}
// All tags set failed.
if len(resResult) < 1 {
return common.CheckDeletedDiag(d, golangsdk.ErrDefault404{}, "TMS tags management")
}
mErr := multierror.Append(nil,
d.Set("resources", resResult),
)
if err = mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error saving resources and tags information: %s", err)
}
return nil
}
func resourceResourceTagsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
client, err := cfg.TmsV1Client(region)
if err != nil {
return diag.Errorf("error creating TMS v1 client: %s", err)
}
var (
projectId = d.Get("project_id").(string)
oldRes, newRes = d.GetChange("resources")
oldTags, newTags = d.GetChange("tags")
)
deleteOpts := tags.BatchOpts{
ProjectId: projectId,
Resources: buildResourcesInfo(oldRes.([]interface{})),
Tags: expandResourceTags(oldTags.(map[string]interface{})),
}
failResp, err := tags.Delete(client, deleteOpts)
if err != nil {
return diag.Errorf("error deleting resource tags: %s", err)
}
if len(failResp) > 0 {
return diag.Errorf("some tags were not successfully removed: %#v", failResp)
}
opts := tags.BatchOpts{
ProjectId: projectId,
Resources: buildResourcesInfo(newRes.([]interface{})),
Tags: expandResourceTags(newTags.(map[string]interface{})),
}
failResp, err = tags.Create(client, opts)
if err != nil {
return diag.Errorf("error creating resource tags: %s", err)
}
if len(failResp) > 0 {
return diag.Errorf("some tags were not set successfully: %#v", failResp)
}
return resourceResourceTagsRead(ctx, d, meta)
}
func resourceResourceTagsDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
client, err := cfg.TmsV1Client(region)
if err != nil {
return diag.Errorf("error creating TMS v1 client: %s", err)
}
deleteOpts := tags.BatchOpts{
ProjectId: d.Get("project_id").(string),
Resources: buildResourcesInfo(d.Get("resources").([]interface{})),
Tags: expandResourceTags(d.Get("tags").(map[string]interface{})),
}
failResp, err := tags.Delete(client, deleteOpts)
if err != nil {
return common.CheckDeletedDiag(d, err, "TMS tags management")
}
if len(failResp) > 0 {
return diag.Errorf("some tags were not successfully removed: %#v", failResp)
}
return nil
}