-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_disk_encryption_set.go
314 lines (270 loc) · 10.5 KB
/
resource_arm_disk_encryption_set.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
package compute
import (
"context"
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute"
"github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault"
"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/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/compute/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags"
azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmDiskEncryptionSet() *schema.Resource {
return &schema.Resource{
Create: resourceArmDiskEncryptionSetCreateUpdate,
Read: resourceArmDiskEncryptionSetRead,
Update: resourceArmDiskEncryptionSetCreateUpdate,
Delete: resourceArmDiskEncryptionSetDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.DiskEncryptionSetID(id)
return err
}),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateDiskEncryptionSetName,
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"key_vault_key_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateKeyVaultChildId,
},
"identity": {
Type: schema.TypeList,
// whilst the API Documentation shows optional - attempting to send nothing returns:
// `Required parameter 'ResourceIdentity' is missing (null)`
// hence this is required
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(compute.SystemAssigned),
}, false),
},
"principal_id": {
Type: schema.TypeString,
Computed: true,
},
"tenant_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"tags": tags.Schema(),
},
}
}
func resourceArmDiskEncryptionSetCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.DiskEncryptionSetsClient
vaultClient := meta.(*clients.Client).KeyVault.VaultsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for present of existing Disk Encryption Set %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_disk_encryption_set", *existing.ID)
}
}
keyVaultKeyId := d.Get("key_vault_key_id").(string)
keyVaultDetails, err := diskEncryptionSetRetrieveKeyVault(ctx, vaultClient, keyVaultKeyId)
if err != nil {
return fmt.Errorf("Error validating Key Vault Key %q for Disk Encryption Set: %+v", keyVaultKeyId, err)
}
if !keyVaultDetails.softDeleteEnabled {
return fmt.Errorf("Error validating Key Vault %q (Resource Group %q) for Disk Encryption Set: Soft Delete must be enabled but it isn't!", keyVaultDetails.keyVaultName, keyVaultDetails.resourceGroupName)
}
if !keyVaultDetails.purgeProtectionEnabled {
return fmt.Errorf("Error validating Key Vault %q (Resource Group %q) for Disk Encryption Set: Purge Protection must be enabled but it isn't!", keyVaultDetails.keyVaultName, keyVaultDetails.resourceGroupName)
}
location := azure.NormalizeLocation(d.Get("location").(string))
identityRaw := d.Get("identity").([]interface{})
t := d.Get("tags").(map[string]interface{})
params := compute.DiskEncryptionSet{
Location: utils.String(location),
EncryptionSetProperties: &compute.EncryptionSetProperties{
ActiveKey: &compute.KeyVaultAndKeyReference{
KeyURL: utils.String(keyVaultKeyId),
SourceVault: &compute.SourceVault{
ID: utils.String(keyVaultDetails.keyVaultId),
},
},
},
Identity: expandArmDiskEncryptionSetIdentity(identityRaw),
Tags: tags.Expand(t),
}
future, err := client.CreateOrUpdate(ctx, resourceGroup, name, params)
if err != nil {
return fmt.Errorf("Error creating Disk Encryption Set %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for creation of Disk Encryption Set %q (Resource Group %q): %+v", name, resourceGroup, err)
}
resp, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving Disk Encryption Set %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if resp.ID == nil {
return fmt.Errorf("Cannot read Disk Encryption Set %q (Resource Group %q) ID", name, resourceGroup)
}
d.SetId(*resp.ID)
return resourceArmDiskEncryptionSetRead(d, meta)
}
func resourceArmDiskEncryptionSetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.DiskEncryptionSetsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.DiskEncryptionSetID(d.Id())
if err != nil {
return err
}
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[INFO] Disk Encryption Set %q does not exist - removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error reading Disk Encryption Set %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if props := resp.EncryptionSetProperties; props != nil {
keyVaultKeyId := ""
if props.ActiveKey != nil && props.ActiveKey.KeyURL != nil {
keyVaultKeyId = *props.ActiveKey.KeyURL
}
d.Set("key_vault_key_id", keyVaultKeyId)
}
if err := d.Set("identity", flattenArmDiskEncryptionSetIdentity(resp.Identity)); err != nil {
return fmt.Errorf("Error setting `identity`: %+v", err)
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourceArmDiskEncryptionSetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.DiskEncryptionSetsClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.DiskEncryptionSetID(d.Id())
if err != nil {
return err
}
future, err := client.Delete(ctx, id.ResourceGroup, id.Name)
if err != nil {
return fmt.Errorf("Error deleting Disk Encryption Set %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for deleting Disk Encryption Set %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
return nil
}
func expandArmDiskEncryptionSetIdentity(input []interface{}) *compute.EncryptionSetIdentity {
val := input[0].(map[string]interface{})
return &compute.EncryptionSetIdentity{
Type: compute.DiskEncryptionSetIdentityType(val["type"].(string)),
}
}
func flattenArmDiskEncryptionSetIdentity(input *compute.EncryptionSetIdentity) []interface{} {
if input == nil {
return make([]interface{}, 0)
}
identityType := string(input.Type)
principalId := ""
if input.PrincipalID != nil {
principalId = *input.PrincipalID
}
tenantId := ""
if input.TenantID != nil {
tenantId = *input.TenantID
}
return []interface{}{
map[string]interface{}{
"type": identityType,
"principal_id": principalId,
"tenant_id": tenantId,
},
}
}
type diskEncryptionSetKeyVault struct {
keyVaultId string
resourceGroupName string
keyVaultName string
purgeProtectionEnabled bool
softDeleteEnabled bool
}
func diskEncryptionSetRetrieveKeyVault(ctx context.Context, client *keyvault.VaultsClient, id string) (*diskEncryptionSetKeyVault, error) {
keyVaultKeyId, err := azure.ParseKeyVaultChildID(id)
if err != nil {
return nil, err
}
keyVaultID, err := azure.GetKeyVaultIDFromBaseUrl(ctx, client, keyVaultKeyId.KeyVaultBaseUrl)
if err != nil {
return nil, fmt.Errorf("Error retrieving the Resource ID the Key Vault at URL %q: %s", keyVaultKeyId.KeyVaultBaseUrl, err)
}
if keyVaultID == nil {
return nil, fmt.Errorf("Unable to determine the Resource ID for the Key Vault at URL %q", keyVaultKeyId.KeyVaultBaseUrl)
}
// TODO: use keyvault's custom ID parse function when implemented
parsedKeyVaultID, err := azure.ParseAzureResourceID(*keyVaultID)
if err != nil {
return nil, fmt.Errorf("Error parsing ID for keyvault in Disk Encryption Set: %+v", err)
}
resourceGroup := parsedKeyVaultID.ResourceGroup
vaultName := parsedKeyVaultID.Path["vaults"]
resp, err := client.Get(ctx, resourceGroup, vaultName)
if err != nil {
return nil, fmt.Errorf("Error retrieving KeyVault %q (Resource Group %q): %+v", vaultName, resourceGroup, err)
}
purgeProtectionEnabled := false
softDeleteEnabled := false
if props := resp.Properties; props != nil {
if props.EnableSoftDelete != nil {
softDeleteEnabled = *props.EnableSoftDelete
}
if props.EnablePurgeProtection != nil {
purgeProtectionEnabled = *props.EnablePurgeProtection
}
}
return &diskEncryptionSetKeyVault{
keyVaultId: *keyVaultID,
resourceGroupName: resourceGroup,
keyVaultName: vaultName,
purgeProtectionEnabled: purgeProtectionEnabled,
softDeleteEnabled: softDeleteEnabled,
}, nil
}