-
Notifications
You must be signed in to change notification settings - Fork 645
/
data_source_ibm_resource_key.go
216 lines (180 loc) · 5.87 KB
/
data_source_ibm_resource_key.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package resourcecontroller
import (
"encoding/json"
"fmt"
"log"
"sort"
"strings"
"github.com/IBM-Cloud/bluemix-go/crn"
"github.com/IBM-Cloud/bluemix-go/models"
"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"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func DataSourceIBMResourceKey() *schema.Resource {
return &schema.Resource{
Read: dataSourceIBMResourceKeyRead,
Schema: map[string]*schema.Schema{
"name": {
Description: "The name of the resource key",
Type: schema.TypeString,
Required: true,
},
"resource_instance_id": {
Type: schema.TypeString,
Optional: true,
Description: "The id of the resource instance",
ConflictsWith: []string{"resource_alias_id"},
ValidateFunc: validate.InvokeDataSourceValidator("ibm_resource_key",
"resource_instance_id"),
},
"resource_alias_id": {
Type: schema.TypeString,
Optional: true,
Description: "The id of the resource alias",
ConflictsWith: []string{"resource_instance_id"},
},
"role": {
Type: schema.TypeString,
Computed: true,
Description: "User role",
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "Status of resource key",
},
"credentials": {
Description: "Credentials asociated with the key",
Sensitive: true,
Type: schema.TypeMap,
Computed: true,
},
"credentials_json": {
Description: "Credentials asociated with the key in json string",
Type: schema.TypeString,
Sensitive: true,
Computed: true,
},
"most_recent": {
Description: "If true and multiple entries are found, the most recently created resource key is used. " +
"If false, an error is returned",
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"crn": {
Type: schema.TypeString,
Computed: true,
Description: "crn of resource key",
},
},
}
}
func DataSourceIBMResourceKeyValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "resource_instance_id",
ValidateFunctionIdentifier: validate.ValidateCloudData,
Type: validate.TypeString,
CloudDataType: "resource_instance",
CloudDataRange: []string{"service:%s"},
Optional: true})
ibmDataSourceKeyResourceValidator := validate.ResourceValidator{ResourceName: "ibm_resource_key", Schema: validateSchema}
return &ibmDataSourceKeyResourceValidator
}
func dataSourceIBMResourceKeyRead(d *schema.ResourceData, meta interface{}) error {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerAPI()
if err != nil {
return err
}
rkAPI := rsContClient.ResourceServiceKey()
name := d.Get("name").(string)
mostRecent := d.Get("most_recent").(bool)
keys, err := rkAPI.GetKeys(name)
if err != nil {
return err
}
var filteredKeys []models.ServiceKey
if d.Get("resource_instance_id") == "" {
filteredKeys = keys
} else {
crn, err := getCRN(d, meta)
if err != nil {
return err
}
for _, key := range keys {
if key.SourceCrn == *crn {
filteredKeys = append(filteredKeys, key)
}
}
}
if len(filteredKeys) == 0 {
return fmt.Errorf("[ERROR] No resource keys found with name [%s]", name)
}
var key models.ServiceKey
if len(filteredKeys) > 1 {
if mostRecent {
key = mostRecentResourceKey(filteredKeys)
} else {
return fmt.Errorf("[ERROR] More than one resource key found with name matching [%s]. "+
"Set 'most_recent' to true in your configuration to force the most recent resource key "+
"to be used", name)
}
} else {
key = filteredKeys[0]
}
d.SetId(key.ID)
if redacted, ok := key.Credentials["redacted"].(string); ok {
log.Printf("Credentials are redacted with code: %s.The User doesn't have the correct access to view the credentials. Refer to the API documentation for additional details.", redacted)
}
if roleCrn, ok := key.Parameters["role_crn"].(string); ok {
d.Set("role", roleCrn[strings.LastIndex(roleCrn, ":")+1:])
} else if roleCrn, ok := key.Credentials["iam_role_crn"].(string); ok {
d.Set("role", roleCrn[strings.LastIndex(roleCrn, ":")+1:])
}
d.Set("credentials", flex.Flatten(key.Credentials))
creds, err := json.Marshal(key.Credentials)
if err != nil {
return fmt.Errorf("[ERROR] Error marshalling resource key credentials: %s", err)
}
if err = d.Set("credentials_json", string(creds)); err != nil {
return fmt.Errorf("[ERROR] Error setting the credentials json: %s", err)
}
d.Set("status", key.State)
d.Set("crn", key.Crn.String())
return nil
}
func getCRN(d *schema.ResourceData, meta interface{}) (*crn.CRN, error) {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerAPI()
if err != nil {
return nil, err
}
if insID, ok := d.GetOk("resource_instance_id"); ok {
instance, err := rsContClient.ResourceServiceInstance().GetInstance(insID.(string))
if err != nil {
return nil, err
}
return &(instance.Crn), nil
}
alias, err := rsContClient.ResourceServiceAlias().Alias(d.Get("resource_alias_id").(string))
if err != nil {
return nil, err
}
return &(alias.CRN), nil
}
type resourceKeys []models.ServiceKey
func (k resourceKeys) Len() int { return len(k) }
func (k resourceKeys) Swap(i, j int) { k[i], k[j] = k[j], k[i] }
func (k resourceKeys) Less(i, j int) bool {
return (*k[i].CreatedAt).Before(*k[j].CreatedAt)
}
func mostRecentResourceKey(keys resourceKeys) models.ServiceKey {
sortedKeys := keys
sort.Sort(sortedKeys)
return sortedKeys[len(sortedKeys)-1]
}