/
identity_compartment_resource.go
370 lines (308 loc) · 10.6 KB
/
identity_compartment_resource.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
361
362
363
364
365
366
367
368
369
370
// Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
package provider
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform/helper/schema"
oci_identity "github.com/oracle/oci-go-sdk/identity"
)
func IdentityCompartmentResource() *schema.Resource {
return &schema.Resource{
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(90 * time.Minute), // service team states: p50: 30 min, p90: 60 min, max: 180 min
},
Create: createIdentityCompartment,
Read: readIdentityCompartment,
Update: updateIdentityCompartment,
Delete: deleteIdentityCompartment,
Schema: map[string]*schema.Schema{
// Required
// @next-break: remove customizations
// The legacy provider exposed this as read-only/computed. The API requires this param. For legacy users who are
// not supplying a value, make it optional, behind the scenes it will use the tenancy ocid if not supplied.
// If a user supplies the value, then changes it, it requires forcing new.
"compartment_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"enable_delete": {
Type: schema.TypeBool,
Optional: true,
},
"description": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
// Optional
"defined_tags": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
DiffSuppressFunc: definedTagsDiffSuppressFunction,
Elem: schema.TypeString,
},
"freeform_tags": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
Elem: schema.TypeString,
},
// Computed
"inactive_state": {
Type: schema.TypeString,
Computed: true,
},
"is_accessible": {
Type: schema.TypeBool,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"time_created": {
Type: schema.TypeString,
Computed: true,
},
// @Deprecated 01/2018: time_modified (removed). @next-break: remove
"time_modified": {
Type: schema.TypeString,
Deprecated: FieldDeprecated("time_modified"),
Computed: true,
},
},
}
}
func createIdentityCompartment(d *schema.ResourceData, m interface{}) error {
sync := &IdentityCompartmentResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).identityClient
sync.Configuration = m.(*OracleClients).configuration
return CreateResource(d, sync)
}
func readIdentityCompartment(d *schema.ResourceData, m interface{}) error {
sync := &IdentityCompartmentResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).identityClient
return ReadResource(sync)
}
func updateIdentityCompartment(d *schema.ResourceData, m interface{}) error {
sync := &IdentityCompartmentResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).identityClient
return UpdateResource(d, sync)
}
func deleteIdentityCompartment(d *schema.ResourceData, m interface{}) error {
if enableDelete, ok := d.GetOkExists("enable_delete"); !ok || !enableDelete.(bool) {
return nil
}
sync := &IdentityCompartmentResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).identityClient
sync.DisableNotFoundRetries = true
return DeleteResource(d, sync)
}
type IdentityCompartmentResourceCrud struct {
BaseCrud
Client *oci_identity.IdentityClient
Configuration map[string]string
Res *oci_identity.Compartment
DisableNotFoundRetries bool
}
func (s *IdentityCompartmentResourceCrud) ID() string {
return *s.Res.Id
}
func (s *IdentityCompartmentResourceCrud) CreatedPending() []string {
return []string{
string(oci_identity.CompartmentLifecycleStateCreating),
}
}
func (s *IdentityCompartmentResourceCrud) CreatedTarget() []string {
return []string{
string(oci_identity.CompartmentLifecycleStateActive),
}
}
func (s *IdentityCompartmentResourceCrud) DeletedPending() []string {
return []string{
string(oci_identity.CompartmentLifecycleStateDeleting),
}
}
func (s *IdentityCompartmentResourceCrud) DeletedTarget() []string {
return []string{
string(oci_identity.CompartmentLifecycleStateDeleted),
}
}
func (s *IdentityCompartmentResourceCrud) Create() error {
request := oci_identity.CreateCompartmentRequest{}
if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok {
tmp := compartmentId.(string)
request.CompartmentId = &tmp
} else { // @next-break: remove
// Prevent potentially inferring wrong TenancyOCID from InstancePrincipal
if auth := s.Configuration["auth"]; strings.ToLower(auth) == strings.ToLower(authInstancePrincipalSetting) {
return fmt.Errorf("compartment_id must be specified for this resource when using with auth as '%s'", authInstancePrincipalSetting)
}
// Maintain legacy contract of compartment_id defaulting to tenancy_ocid if not specified
c := *s.Client.ConfigurationProvider()
if c == nil {
return fmt.Errorf("cannot access tenancyOCID")
}
tenancy, err := c.TenancyOCID()
if err != nil {
return err
}
request.CompartmentId = &tenancy
}
if definedTags, ok := s.D.GetOkExists("defined_tags"); ok {
convertedDefinedTags, err := mapToDefinedTags(definedTags.(map[string]interface{}))
if err != nil {
return err
}
request.DefinedTags = convertedDefinedTags
}
if description, ok := s.D.GetOkExists("description"); ok {
tmp := description.(string)
request.Description = &tmp
}
if freeformTags, ok := s.D.GetOkExists("freeform_tags"); ok {
request.FreeformTags = objectMapToStringMap(freeformTags.(map[string]interface{}))
}
if name, ok := s.D.GetOkExists("name"); ok {
tmp := name.(string)
request.Name = &tmp
}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "identity")
response, err := s.Client.CreateCompartment(context.Background(), request)
if err != nil {
if response.RawResponse != nil && response.RawResponse.StatusCode == 409 {
// Return an error if 'enable_delete' was explicitly set to 'true' in case of automatic import on conflict
if enableDelete, ok := s.D.GetOkExists("enable_delete"); ok && enableDelete.(bool) {
return fmt.Errorf(`%s
If you define a compartment resource in your configurations with
the same name as an existing compartment with 'enable_delete' set to 'true',
the compartment will no longer be automatically imported.
If you intended to manage an existing compartment, use terraform import instead.`, err)
}
// React to name collisions or conflict errors by importing pre-existing compartment into this plan if the name matches.
if strings.Contains(err.Error(), "already exists") ||
strings.Contains(err.Error(), "Maximum number of compartment") {
// List all compartments using the datasource to find that compartment with the matching name.
// CompartmentsDataSourceCrud requires a compartment_id, so forward whatever value was used in
// the create attempt above.
s.D.Set("compartment_id", request.CompartmentId)
log.Println(fmt.Sprintf("[DEBUG] The specified compartment with name '%s' may already exist, listing compartments to lookup with name instead.",
*request.Name))
dsCrud := &IdentityCompartmentsDataSourceCrud{s.D, s.Client, nil}
if err := dsCrud.Get(); err != nil {
return err
}
for _, compartment := range dsCrud.Res.Items {
if *compartment.Name == *request.Name {
s.Res = &compartment
//Update with correct description
s.D.SetId(s.ID())
return s.Update()
}
}
// Return an error if the lookup failed, to provide user with information on which compartment id and name were used for lookup
return fmt.Errorf(`%s
failed to lookup the compartment with name: '%s' in compartment_id: '%s'.
Verify your configuration if the correct 'compartment_id' and 'name' were specified.
In most cases, the 'compartment_id' will be your 'tenancy_ocid' with the exception of nested compartments.
Refer to the 'oci_identity_compartment' documentation for more information.`, err, *request.Name, *request.CompartmentId)
}
}
return err
}
s.Res = &response.Compartment
return nil
}
func (s *IdentityCompartmentResourceCrud) Get() error {
request := oci_identity.GetCompartmentRequest{}
tmp := s.D.Id()
request.CompartmentId = &tmp
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "identity")
response, err := s.Client.GetCompartment(context.Background(), request)
if err != nil {
return err
}
s.Res = &response.Compartment
return nil
}
func (s *IdentityCompartmentResourceCrud) Update() error {
request := oci_identity.UpdateCompartmentRequest{}
tmp := s.D.Id()
request.CompartmentId = &tmp
if definedTags, ok := s.D.GetOkExists("defined_tags"); ok {
convertedDefinedTags, err := mapToDefinedTags(definedTags.(map[string]interface{}))
if err != nil {
return err
}
request.DefinedTags = convertedDefinedTags
}
if description, ok := s.D.GetOkExists("description"); ok {
tmp := description.(string)
request.Description = &tmp
}
if freeformTags, ok := s.D.GetOkExists("freeform_tags"); ok {
request.FreeformTags = objectMapToStringMap(freeformTags.(map[string]interface{}))
}
if name, ok := s.D.GetOkExists("name"); ok {
tmp := name.(string)
request.Name = &tmp
}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "identity")
response, err := s.Client.UpdateCompartment(context.Background(), request)
if err != nil {
return err
}
s.Res = &response.Compartment
return nil
}
func (s *IdentityCompartmentResourceCrud) Delete() error {
request := oci_identity.DeleteCompartmentRequest{}
tmp := s.D.Id()
request.CompartmentId = &tmp
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "identity")
_, err := s.Client.DeleteCompartment(context.Background(), request)
return err
}
func (s *IdentityCompartmentResourceCrud) SetData() error {
if s.Res.CompartmentId != nil {
s.D.Set("compartment_id", *s.Res.CompartmentId)
}
if s.Res.DefinedTags != nil {
s.D.Set("defined_tags", definedTagsToMap(s.Res.DefinedTags))
}
if s.Res.Description != nil {
s.D.Set("description", *s.Res.Description)
}
s.D.Set("freeform_tags", s.Res.FreeformTags)
if s.Res.InactiveStatus != nil {
s.D.Set("inactive_state", strconv.FormatInt(*s.Res.InactiveStatus, 10))
}
if s.Res.IsAccessible != nil {
s.D.Set("is_accessible", *s.Res.IsAccessible)
}
if s.Res.Name != nil {
s.D.Set("name", *s.Res.Name)
}
s.D.Set("state", s.Res.LifecycleState)
if s.Res.TimeCreated != nil {
s.D.Set("time_created", s.Res.TimeCreated.String())
}
return nil
}