-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_azuread_service_principal_password.go
272 lines (223 loc) · 8.23 KB
/
resource_arm_azuread_service_principal_password.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
package graph
import (
"fmt"
"log"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac"
"github.com/Azure/go-autorest/autorest/date"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/locks"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmActiveDirectoryServicePrincipalPassword() *schema.Resource {
return &schema.Resource{
DeprecationMessage: `The Azure Active Directory resources have been split out into their own Provider.
Information on migrating to the new AzureAD Provider can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-to-azuread.html
As such the Azure Active Directory resources within the AzureRM Provider are now deprecated and will be removed in v2.0 of the AzureRM Provider.
`,
Create: resourceArmActiveDirectoryServicePrincipalPasswordCreate,
Read: resourceArmActiveDirectoryServicePrincipalPasswordRead,
Delete: resourceArmActiveDirectoryServicePrincipalPasswordDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"service_principal_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.IsUUID,
},
"key_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.IsUUID,
},
"value": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},
"start_date": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validate.RFC3339Time,
},
"end_date": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.RFC3339Time,
},
},
}
}
func resourceArmActiveDirectoryServicePrincipalPasswordCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Graph.ServicePrincipalsClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()
objectId := d.Get("service_principal_id").(string)
value := d.Get("value").(string)
// errors will be handled by the validation
endDate, _ := time.Parse(time.RFC3339, d.Get("end_date").(string))
var keyId string
if v, ok := d.GetOk("key_id"); ok {
keyId = v.(string)
} else {
kid, err := uuid.GenerateUUID()
if err != nil {
return err
}
keyId = kid
}
credential := graphrbac.PasswordCredential{
KeyID: utils.String(keyId),
Value: utils.String(value),
EndDate: &date.Time{Time: endDate},
}
if v, ok := d.GetOk("start_date"); ok {
// errors will be handled by the validation
startDate, _ := time.Parse(time.RFC3339, v.(string))
credential.StartDate = &date.Time{Time: startDate}
}
locks.ByName(objectId, servicePrincipalResourceName)
defer locks.UnlockByName(objectId, servicePrincipalResourceName)
existingCredentials, err := client.ListPasswordCredentials(ctx, objectId)
if err != nil {
return fmt.Errorf("Error Listing Password Credentials for Service Principal %q: %+v", objectId, err)
}
updatedCredentials := make([]graphrbac.PasswordCredential, 0)
if existingCredentials.Value != nil {
for _, v := range *existingCredentials.Value {
if v.KeyID == nil {
continue
}
if *v.KeyID == keyId {
return tf.ImportAsExistsError("azurerm_azuread_service_principal_password", fmt.Sprintf("%s/%s", objectId, keyId))
}
}
updatedCredentials = *existingCredentials.Value
}
updatedCredentials = append(updatedCredentials, credential)
parameters := graphrbac.PasswordCredentialsUpdateParameters{
Value: &updatedCredentials,
}
_, err = client.UpdatePasswordCredentials(ctx, objectId, parameters)
if err != nil {
return fmt.Errorf("Error creating Password Credential %q for Service Principal %q: %+v", keyId, objectId, err)
}
d.SetId(fmt.Sprintf("%s/%s", objectId, keyId))
return resourceArmActiveDirectoryServicePrincipalPasswordRead(d, meta)
}
func resourceArmActiveDirectoryServicePrincipalPasswordRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Graph.ServicePrincipalsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id := strings.Split(d.Id(), "/")
if len(id) != 2 {
return fmt.Errorf("ID should be in the format {objectId}/{keyId} - but got %q", d.Id())
}
objectId := id[0]
keyId := id[1]
// ensure the parent Service Principal exists
servicePrincipal, err := client.Get(ctx, objectId)
if err != nil {
// the parent Service Principal has been removed - skip it
if utils.ResponseWasNotFound(servicePrincipal.Response) {
log.Printf("[DEBUG] Service Principal with Object ID %q was not found - removing from state!", objectId)
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving Service Principal ID %q: %+v", objectId, err)
}
credentials, err := client.ListPasswordCredentials(ctx, objectId)
if err != nil {
return fmt.Errorf("Error Listing Password Credentials for Service Principal with Object ID %q: %+v", objectId, err)
}
var credential *graphrbac.PasswordCredential
for _, c := range *credentials.Value {
if c.KeyID == nil {
continue
}
if *c.KeyID == keyId {
credential = &c
break
}
}
if credential == nil {
log.Printf("[DEBUG] Service Principal Password %q (Object ID %q) was not found - removing from state!", keyId, objectId)
d.SetId("")
return nil
}
// value is available in the SDK but isn't returned from the API
d.Set("key_id", credential.KeyID)
d.Set("service_principal_id", objectId)
if endDate := credential.EndDate; endDate != nil {
d.Set("end_date", endDate.Format(time.RFC3339))
}
if startDate := credential.StartDate; startDate != nil {
d.Set("start_date", startDate.Format(time.RFC3339))
}
return nil
}
func resourceArmActiveDirectoryServicePrincipalPasswordDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Graph.ServicePrincipalsClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id := strings.Split(d.Id(), "/")
if len(id) != 2 {
return fmt.Errorf("ID should be in the format {objectId}/{keyId} - but got %q", d.Id())
}
objectId := id[0]
keyId := id[1]
locks.ByName(objectId, servicePrincipalResourceName)
defer locks.UnlockByName(objectId, servicePrincipalResourceName)
// ensure the parent Service Principal exists
servicePrincipal, err := client.Get(ctx, objectId)
if err != nil {
// the parent Service Principal was removed - skip it
if utils.ResponseWasNotFound(servicePrincipal.Response) {
return nil
}
return fmt.Errorf("Error retrieving Service Principal ID %q: %+v", objectId, err)
}
existing, err := client.ListPasswordCredentials(ctx, objectId)
if err != nil {
return fmt.Errorf("Error Listing Password Credentials for Service Principal with Object ID %q: %+v", objectId, err)
}
updatedCredentials := make([]graphrbac.PasswordCredential, 0)
for _, credential := range *existing.Value {
if credential.KeyID == nil {
continue
}
if *credential.KeyID != keyId {
updatedCredentials = append(updatedCredentials, credential)
}
}
parameters := graphrbac.PasswordCredentialsUpdateParameters{
Value: &updatedCredentials,
}
_, err = client.UpdatePasswordCredentials(ctx, objectId, parameters)
if err != nil {
return fmt.Errorf("Error removing Password %q from Service Principal %q: %+v", keyId, objectId, err)
}
return nil
}