Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_keyvault.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Zim Kalinowski, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_keyvault
14 version_added: "0.1.2"
15 short_description: Manage Key Vault instance
16 description:
17 - Create, update and delete instance of Key Vault.
18
19 options:
20 resource_group:
21 description:
22 - The name of the Resource Group to which the server belongs.
23 required: True
24 type: str
25 vault_name:
26 description:
27 - Name of the vault.
28 - It is mutually exclusive with I(hsm_name)
29 required: False
30 type: str
31 hsm_name:
32 description:
33 - Name of the HSM.
34 - It is mutually exclusive with I(vault_name)
35 required: False
36 type: str
37 administrators:
38 description:
39 - List of administrator OID's for data plane operations for Managed HSM.
40 - It is mutually exclusive with I(vault_name)
41 required: False
42 type: list
43 elements: str
44 default: []
45 identity:
46 description:
47 - Identity for the HSM, not valid for vault_name.
48 - It is mutually exclusive with I(vault_name)
49 type: dict
50 version_added: '3.0.0'
51 suboptions:
52 type:
53 description:
54 - Type of the managed identity
55 choices:
56 - UserAssigned
57 - None
58 default: None
59 type: str
60 user_assigned_identity:
61 description:
62 - User Assigned Managed Identity associated to this resource
63 required: false
64 type: str
65 location:
66 description:
67 - Resource location. If not set, location from the resource group will be used as default.
68 type: str
69 vault_tenant:
70 description:
71 - The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.
72 type: str
73 aliases:
74 - tenant_id
75 sku:
76 description:
77 - SKU details.
78 type: dict
79 suboptions:
80 family:
81 description:
82 - SKU family name.
83 type: str
84 required: True
85 name:
86 description:
87 - SKU name to specify whether the key vault is a standard vault or a premium vault.
88 required: True
89 type: str
90 choices:
91 - 'standard'
92 - 'premium'
93 access_policies:
94 description:
95 - An array of 0 to 16 identities that have access to the key vault.
96 - All identities in the array must use the same tenant ID as the key vault's tenant ID.
97 - It is mutually exclusive with I(hsm_name)
98 type: list
99 elements: dict
100 suboptions:
101 tenant_id:
102 description:
103 - The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.
104 - Current keyvault C(tenant_id) value will be used if not specified.
105 type: str
106 object_id:
107 description:
108 - The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault.
109 - The object ID must be unique for the list of access policies.
110 - Please note this is not application id. Object id can be obtained by running "az ad sp show --id <application id>".
111 type: str
112 required: True
113 application_id:
114 description:
115 - Application ID of the client making request on behalf of a principal.
116 type: str
117 keys:
118 description:
119 - List of permissions to keys.
120 type: list
121 elements: str
122 choices:
123 - 'encrypt'
124 - 'decrypt'
125 - 'wrapkey'
126 - 'unwrapkey'
127 - 'sign'
128 - 'verify'
129 - 'get'
130 - 'list'
131 - 'create'
132 - 'update'
133 - 'import'
134 - 'delete'
135 - 'backup'
136 - 'restore'
137 - 'recover'
138 - 'purge'
139 secrets:
140 description:
141 - List of permissions to secrets.
142 type: list
143 elements: str
144 choices:
145 - 'get'
146 - 'list'
147 - 'set'
148 - 'delete'
149 - 'backup'
150 - 'restore'
151 - 'recover'
152 - 'purge'
153 certificates:
154 description:
155 - List of permissions to certificates.
156 type: list
157 elements: str
158 choices:
159 - 'get'
160 - 'list'
161 - 'delete'
162 - 'create'
163 - 'import'
164 - 'update'
165 - 'managecontacts'
166 - 'getissuers'
167 - 'listissuers'
168 - 'setissuers'
169 - 'deleteissuers'
170 - 'manageissuers'
171 - 'recover'
172 - 'purge'
173 - 'backup'
174 - 'restore'
175 storage:
176 description:
177 - List of permissions to storage accounts.
178 type: list
179 elements: str
180 enabled_for_deployment:
181 description:
182 - Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.
183 - It is mutually exclusive with I(hsm_name)
184 type: bool
185 enabled_for_disk_encryption:
186 description:
187 - Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.
188 - It is mutually exclusive with I(hsm_name)
189 type: bool
190 enabled_for_template_deployment:
191 description:
192 - Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.
193 - It is mutually exclusive with I(hsm_name)
194 type: bool
195 enable_soft_delete:
196 description:
197 - Property to specify whether the soft delete functionality is enabled for this key vault.
198 type: bool
199 default: True
200 enable_purge_protection:
201 description:
202 - Property specifying whether protection against purge is enabled for this vault.
203 type: bool
204 default: False
205 enable_rbac_authorization:
206 description:
207 - Property that controls how data actions are authorized.
208 - When I(enable_rbac_authorization=true), the key vault will use Role Based Access Control (RBAC) for authorization of data actions,
209 and the access policies specified in vault properties will be ignored.
210 - When I(enable_rbac_authorization=false), the key vault will use the access policies specified in vault properties,
211 and any policy stored on Azure Resource Manager will be ignored.
212 - If null or not specified, the value of this property will not change.
213 - Starting with API version 2026-02-01, Azure defaults this to true (RBAC) if not specified.
214 type: bool
215 soft_delete_retention_in_days:
216 description:
217 - Property specifying the number of days to retain deleted vaults.
218 type: int
219 recover_mode:
220 description:
221 - Create vault in recovery mode.
222 type: bool
223 public_network_access:
224 description:
225 - Property to specify whether the vault will accept traffic from public internet.
226 type: str
227 choices:
228 - Disabled
229 - Enabled
230 network_acls:
231 description:
232 - A collection of rules governing the accessibility of the vault from specific network locations.
233 type: dict
234 suboptions:
235 bypass:
236 description:
237 - Tells what traffic can bypass network rules.
238 - If not specified the default is 'AzureServices'.
239 type: str
240 choices:
241 - AzureServices
242 - None
243 default: AzureServices
244 default_action:
245 description:
246 - The default action when no rule from ipRules and from virtualNetworkRules match.
247 - This is only used after the bypass property has been evaluated.
248 type: str
249 choices:
250 - Allow
251 - Deny
252 ip_rules:
253 description:
254 - The list of IP address rules.
255 type: list
256 elements: dict
257 suboptions:
258 value:
259 description:
260 - An IPv4 address range in CIDR notation.
261 - Such as C(124.56.78.91) (simple IP address) or C(124.56.78.0/24) (all addresses that start with 124.56.78).
262 type: str
263 virtual_network_rules:
264 description:
265 - The list of virtual network rules.
266 type: list
267 elements: dict
268 suboptions:
269 id:
270 description:
271 - Full resource id of a vnet subnet.
272 type: str
273 ignore_missing_vnet_service_endpoint:
274 description:
275 - Property to specify whether NRP will ignore the check if parent subnet has serviceEndpoints configured.
276 type: bool
277 is_purge_deleted:
278 description:
279 - Whether permanently deletes the specified vault. aka Purges the deleted Azure key vault
280 - Default value is C(True)
281 - When I(is_purge_deleted) is specified, the I(location) has to be configured.
282 If not configured, the default locatioin of the resource group will be used.
283 type: bool
284 default: False
285 state:
286 description:
287 - Assert the state of the KeyVault. Use C(present) to create or update an KeyVault and C(absent) to delete it.
288 default: present
289 type: str
290 choices:
291 - absent
292 - present
293
294 extends_documentation_fragment:
295 - azure.azcollection.azure
296 - azure.azcollection.azure_tags
297
298 author:
299 - Zim Kalinowski (@zikalino)
300
301 '''
302
303 EXAMPLES = '''
304 - name: Create instance of Key Vault
305 azure_rm_keyvault:
306 resource_group: myResourceGroup
307 vault_name: samplekeyvault
308 enabled_for_deployment: true
309 enable_rbac_authorization: true
310 vault_tenant: 72f98888-8666-4144-9199-2d7cd0111111
311 sku:
312 name: standard
313 family: A
314 access_policies:
315 - tenant_id: 72f98888-8666-4144-9199-2d7cd0111111
316 object_id: 99998888-8666-4144-9199-2d7cd0111111
317 keys:
318 - get
319 - list
320 '''
321
322 RETURN = '''
323 id:
324 description:
325 - The Azure Resource Manager resource ID for the key vault.
326 returned: always
327 type: str
328 sample: id
329 '''
330
331 import time
332 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
333
334 try:
335 from azure.core.polling import LROPoller
336 from azure.core.exceptions import ResourceNotFoundError
337 from azure.mgmt.keyvault import KeyVaultManagementClient
338 from azure.mgmt.keyvault.models import (ManagedServiceIdentity, UserAssignedIdentity, NetworkRuleSet,
339 NetworkRuleBypassOptions, NetworkRuleAction, ManagedHsmProperties,
340 ManagedHsm, ManagedHsmSku)
341 except ImportError:
342 # This is handled in azure_rm_common
343 pass
344
345
346 class Actions:
347 NoAction, Create, Update, Delete = range(4)
348
349
350 class AzureRMVaults(AzureRMModuleBaseExt):
351 """Configuration class for an Azure RM Key Vault resource"""
352
353 def __init__(self):
354 self.module_arg_spec = dict(
355 resource_group=dict(
356 type='str',
357 required=True
358 ),
359 vault_name=dict(
360 type='str'
361 ),
362 hsm_name=dict(
363 type='str'
364 ),
365 location=dict(
366 type='str'
367 ),
368 vault_tenant=dict(
369 type='str',
370 aliases=['tenant_id']
371 ),
372 sku=dict(
373 type='dict'
374 ),
375 administrators=dict(
376 type='list',
377 default=[],
378 elements='str'
379 ),
380 identity=dict(
381 type='dict',
382 options=dict(
383 type=dict(
384 type='str',
385 choices=['UserAssigned', 'None'],
386 default='None'
387 ),
388 user_assigned_identity=dict(
389 type="str",
390 ),
391 ),
392 ),
393 access_policies=dict(
394 type='list',
395 elements='dict',
396 options=dict(
397 tenant_id=dict(type='str'),
398 object_id=dict(type='str', required=True),
399 application_id=dict(type='str'),
400 # FUTURE: add `choices` support once choices supports lists of values
401 keys=dict(
402 type='list',
403 elements='str',
404 no_log=True,
405 choices=['encrypt', 'decrypt', 'wrapkey', 'unwrapkey', 'sign', 'verify', 'get',
406 'list', 'create', 'update', 'import', 'delete', 'backup', 'restore', 'recover', 'purge']
407 ),
408 secrets=dict(
409 type='list',
410 elements='str',
411 no_log=True,
412 choices=['get', 'list', 'set', 'delete', 'backup', 'restore', 'recover', 'purge']
413 ),
414 certificates=dict(
415 type='list',
416 elements='str',
417 choices=['get', 'list', 'delete', 'create', 'import', 'update', 'managecontacts',
418 'getissuers', 'listissuers', 'setissuers', 'deleteissuers', 'manageissuers', 'recover', 'purge', 'backup', 'restore']
419 ),
420 storage=dict(type='list', elements='str')
421 )
422 ),
423 enabled_for_deployment=dict(
424 type='bool'
425 ),
426 enabled_for_disk_encryption=dict(
427 type='bool'
428 ),
429 enabled_for_template_deployment=dict(
430 type='bool'
431 ),
432 enable_soft_delete=dict(
433 type='bool',
434 default=True
435 ),
436 enable_rbac_authorization=dict(
437 type='bool'
438 ),
439 soft_delete_retention_in_days=dict(
440 type='int'
441 ),
442 enable_purge_protection=dict(
443 type='bool',
444 default=False
445 ),
446 recover_mode=dict(
447 type='bool'
448 ),
449 public_network_access=dict(
450 type='str',
451 choices=['Disabled', 'Enabled']
452 ),
453 network_acls=dict(
454 type='dict',
455 options=dict(
456 bypass=dict(type='str', choices=['AzureServices', 'None'], default='AzureServices'),
457 default_action=dict(type='str', choices=['Allow', 'Deny']),
458 ip_rules=dict(
459 type='list',
460 elements='dict',
461 options=dict(
462 value=dict(type='str'),
463 )
464 ),
465 virtual_network_rules=dict(
466 type='list',
467 elements='dict',
468 options=dict(
469 id=dict(type='str'),
470 ignore_missing_vnet_service_endpoint=dict(type='bool')
471 )
472 )
473 )
474 ),
475 is_purge_deleted=dict(
476 type='bool',
477 default=False
478 ),
479 state=dict(
480 type='str',
481 default='present',
482 choices=['present', 'absent']
483 )
484 )
485
486 self.module_required_if = [['state', 'present', ['vault_tenant']]]
487
488 self.resource_group = None
489 self.vault_name = None
490 self.hsm_name = None
491 self.parameters = dict()
492 self.tags = None
493 self.identity = None
494 self.administrators = None
495 self.is_purge_deleted = None
496
497 self.results = dict(changed=False)
498 self.mgmt_client = None
499 self.state = None
500 self.to_do = Actions.NoAction
501 self._managed_identity = None
502
503 required_one_of = [('vault_name', 'hsm_name')]
504 mutually_exclusive = [('vault_name', 'hsm_name'),
505 ('vault_name', 'identity'),
506 ('vault_name', 'administrators'),
507 ('hsm_name', 'enabled_for_deployment'),
508 ('hsm_name', 'enabled_for_disk_encryption'),
509 ('hsm_name', 'enabled_for_template_deployment'),
510 ('hsm_name', 'access_policies')]
511
512 super(AzureRMVaults, self).__init__(derived_arg_spec=self.module_arg_spec,
513 supports_check_mode=True,
514 supports_tags=True,
515 mutually_exclusive=mutually_exclusive,
516 required_one_of=required_one_of,
517 required_if=self.module_required_if)
518
519 @property
520 def managed_identity(self):
521 if not self._managed_identity:
522 self._managed_identity = {"identity": ManagedServiceIdentity,
523 "user_assigned": UserAssignedIdentity
524 }
525 return self._managed_identity
526
527 def exec_module(self, **kwargs):
528 """Main module execution method"""
529
530 # translate Ansible input to SDK-formatted dict in self.parameters
531 for key in list(self.module_arg_spec.keys()) + ['tags']:
532 if hasattr(self, key):
533 setattr(self, key, kwargs[key])
534 elif kwargs[key] is not None:
535 if key == "location":
536 self.parameters["location"] = kwargs[key]
537 elif key == "vault_tenant":
538 self.parameters.setdefault("properties", {})["tenant_id"] = kwargs[key]
539 elif key == "sku" and self.vault_name is not None:
540 self.parameters.setdefault("properties", {})["sku"] = kwargs[key]
541 elif key == "sku" and self.hsm_name is not None:
542 self.parameters["sku"] = kwargs[key]
543 elif key == "public_network_access":
544 self.parameters.setdefault("properties", {})["public_network_access"] = kwargs[key]
545 elif key == "network_acls":
546 self.parameters.setdefault("properties", {})["network_acls"] = kwargs[key]
547 elif key == "access_policies":
548 access_policies = kwargs[key]
549 for policy in access_policies:
550 if 'keys' in policy:
551 policy.setdefault("permissions", {})["keys"] = policy["keys"]
552 policy.pop("keys", None)
553 if 'secrets' in policy:
554 policy.setdefault("permissions", {})["secrets"] = policy["secrets"]
555 policy.pop("secrets", None)
556 if 'certificates' in policy:
557 policy.setdefault("permissions", {})["certificates"] = policy["certificates"]
558 policy.pop("certificates", None)
559 if 'storage' in policy:
560 policy.setdefault("permissions", {})["storage"] = policy["storage"]
561 policy.pop("storage", None)
562 if policy.get('tenant_id') is None:
563 # default to key vault's tenant, since that's all that's currently supported anyway
564 policy['tenant_id'] = kwargs['vault_tenant']
565 self.parameters.setdefault("properties", {})["access_policies"] = access_policies
566 elif key == "enabled_for_deployment":
567 self.parameters.setdefault("properties", {})["enabled_for_deployment"] = kwargs[key]
568 elif key == "enabled_for_disk_encryption":
569 self.parameters.setdefault("properties", {})["enabled_for_disk_encryption"] = kwargs[key]
570 elif key == "enabled_for_template_deployment":
571 self.parameters.setdefault("properties", {})["enabled_for_template_deployment"] = kwargs[key]
572 elif key == "enable_soft_delete":
573 self.parameters.setdefault("properties", {})["enable_soft_delete"] = kwargs[key]
574 elif key == "enable_rbac_authorization":
575 self.parameters.setdefault("properties", {})["enable_rbac_authorization"] = kwargs[key]
576 elif key == "enable_purge_protection":
577 self.parameters.setdefault("properties", {})["enable_purge_protection"] = kwargs[key]
578 elif key == "soft_delete_retention_in_days":
579 self.parameters.setdefault("properties", {})["soft_delete_retention_in_days"] = kwargs[key]
580 elif key == "recover_mode":
581 self.parameters.setdefault("properties", {})["create_mode"] = 'recover' if kwargs[key] else 'default'
582
583 old_response = None
584 response = None
585
586 self.mgmt_client = self.get_mgmt_svc_client(KeyVaultManagementClient,
587 base_url=self._cloud_environment.endpoints.resource_manager,
588 api_version="2026-02-01")
589
590 resource_group = self.get_resource_group(self.resource_group)
591
592 if "location" not in self.parameters:
593 self.parameters["location"] = resource_group.location
594
595 old_response = self.get_instance()
596
597 curr_identity = old_response.get('identity') if old_response else None
598 update_identity, identity_result = self.update_single_managed_identity(curr_identity=curr_identity,
599 new_identity=self.identity)
600 if update_identity:
601 self.parameters["identity"] = identity_result
602
603 if not old_response:
604 self.log("Old instance doesn't exist")
605 if self.state == 'absent':
606 self.log("Old instance didn't exist")
607 else:
608 self.to_do = Actions.Create
609 if not self.parameters['properties']['enable_purge_protection']:
610 self.parameters['properties'].pop('enable_purge_protection')
611 else:
612 self.log("Instance already exists")
613 if self.state == 'absent':
614 self.to_do = Actions.Delete
615 elif self.state == 'present':
616 self.log("Need to check if instance has to be deleted or may be updated")
617 if not self.parameters['properties']['enable_purge_protection'] and \
618 ('enable_purge_protection' not in old_response['properties'] or
619 not old_response['properties']['enable_purge_protection']):
620 self.parameters['properties'].pop('enable_purge_protection')
621 for item in ['enabled_for_deployment', 'enabled_for_disk_encryption', 'enabled_for_template_deployment',
622 'enable_soft_delete', 'enable_purge_protection', 'enable_rbac_authorization']:
623 if item in self.parameters['properties'] and bool(old_response['properties'].get(item)) != bool(self.parameters['properties'][item]):
624 self.to_do = Actions.Update
625 else:
626 self.parameters['properties'][item] = old_response['properties'].get(item)
627 if ('location' in self.parameters) and (self.parameters['location'] != old_response['location']):
628 self.to_do = Actions.Update
629 elif (('tenant_id' in self.parameters['properties']) and
630 (self.parameters['properties']['tenant_id'] != old_response['properties']['tenant_id'])):
631 self.to_do = Actions.Update
632 elif (('soft_delete_retention_in_days' in self.parameters['properties']) and
633 (self.parameters['properties']['soft_delete_retention_in_days'] != old_response['properties'].get('soft_delete_retention_in_days'))):
634 self.to_do = Actions.Update
635 elif ('create_mode' in self.parameters['properties']) and (self.parameters['properties']['create_mode'] == 'recover'):
636 self.to_do = Actions.Update
637 elif 'access_policies' in self.parameters['properties']:
638 if len(self.parameters['properties']['access_policies']) != len(old_response['properties']['access_policies']):
639 self.to_do = Actions.Update
640 else:
641 # FUTURE: this list isn't really order-dependent- we should be set-ifying the rules list for order-independent comparison
642 for i in range(len(old_response['properties']['access_policies'])):
643 n = self.parameters['properties']['access_policies'][i]
644 o = old_response['properties']['access_policies'][i]
645 if n.get('tenant_id', False) != o.get('tenant_id', False):
646 self.to_do = Actions.Update
647 break
648 if n.get('object_id', None) != o.get('object_id', None):
649 self.to_do = Actions.Update
650 break
651 if n.get('application_id', None) != o.get('application_id', None):
652 self.to_do = Actions.Update
653 break
654 if sorted(n.get('permissions', {}).get('keys', []) or []) != sorted(o.get('permissions', {}).get('keys', []) or []):
655 self.to_do = Actions.Update
656 break
657 if sorted(n.get('permissions', {}).get('secrets', []) or []) != sorted(o.get('permissions', {}).get('secrets', []) or []):
658 self.to_do = Actions.Update
659 break
660 if sorted(n.get('permissions', {}).get('certificates', []) or []) != sorted(o.get('permissions', {}).get('certificates', []) or []):
661 self.to_do = Actions.Update
662 break
663 if sorted(n.get('permissions', {}).get('storage', []) or []) != sorted(o.get('permissions', {}).get('storage', []) or []):
664 self.to_do = Actions.Update
665 break
666
667 if 'public_network_access' in self.parameters['properties'] and \
668 self.parameters['properties']['public_network_access'].capitalize() != old_response['properties'].get('public_network_access'):
669 self.to_do = Actions.Update
670 else:
671 self.parameters['properties']['public_network_access'] = old_response['properties'].get('public_network_access')
672
673 if old_response['properties'].get('network_acls') is not None:
674 if old_response['properties']['network_acls'].get('ip_rules') is not None:
675 old_response['properties']['network_acls']['ip_rules'] = list()
676 for item in old_response['properties']['network_acls']['ip_rules']:
677 old_response['properties']['network_acls']['ip_rules'].append(dict(value=item['value'].split('/')[0]))
678
679 if not self.default_compare({}, self.parameters['properties'].get('network_acls'),
680 old_response['properties'].get('network_acls'), '', dict(compare=[])):
681 self.to_do = Actions.Update
682
683 update_tags, newtags = self.update_tags(old_response.get('tags', dict()))
684
685 if self.hsm_name and \
686 self.administrators != old_response["properties"]["initial_admin_object_ids"]:
687 self.to_do = Actions.Update
688
689 if update_tags:
690 self.to_do = Actions.Update
691 self.tags = newtags
692
693 if update_identity:
694 self.to_do = Actions.Update
695
696 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
697 self.log("Need to Create / Update the instance")
698
699 self.results['changed'] = True
700 if self.check_mode:
701 return self.results
702
703 self.parameters["tags"] = self.tags
704
705 if self.vault_name is not None:
706 response = self.create_update_keyvault()
707 else:
708 response = self.create_update_hsm()
709
710 if response is None:
711 response = self.get_instance()
712
713 self.log("Creation / Update done")
714 elif self.to_do == Actions.Delete:
715 self.log("Instance deleted")
716 self.results['changed'] = True
717
718 if self.check_mode:
719 return self.results
720
721 if self.vault_name is not None:
722 self.delete_keyvault()
723 else:
724 self.hsm_begin_delete()
725 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
726 # for some time after deletion -- this should be really fixed in Azure
727 while self.get_instance():
728 time.sleep(20)
729 else:
730 self.log("Instance unchanged")
731 self.results['changed'] = False
732 response = old_response
733
734 if response:
735 self.results["id"] = response["id"]
736
737 if self.is_purge_deleted:
738 purge_response = self.get_deleted(self.parameters["location"])
739 if purge_response:
740 self.results['changed'] = True
741 if not self.check_mode:
742 self.purge_deleted(self.parameters["location"])
743
744 return self.results
745
746 def create_update_keyvault(self):
747 '''
748 Creates or updates Key Vault with the specified configuration.
749
750 :return: deserialized Key Vault instance state dictionary
751 '''
752 self.log("Creating / Updating the Key Vault instance {0}".format(self.vault_name))
753
754 try:
755 response = self.mgmt_client.vaults.begin_create_or_update(resource_group_name=self.resource_group,
756 vault_name=self.vault_name,
757 parameters=self.parameters)
758 if isinstance(response, LROPoller):
759 response = self.get_poller_result(response)
760
761 except Exception as exc:
762 self.log('Error attempting to create the Key Vault instance.')
763 self.fail("Error creating the Key Vault instance: {0}".format(str(exc)))
764 return response and response.as_dict() or None
765
766 def create_update_hsm(self):
767 '''
768 Creates or updates HSM with the specified configuration.
769
770 :return: deserialized HSM instance state dictionary
771 '''
772 self.log("Creating / Updating the HSM instance {0}".format(self.hsm_name))
773
774 tenant_id = self.parameters.get('properties', {}).get('tenant_id')
775 enable_purge_protection = self.parameters.get('properties', {}).get('enable_purge_protection')
776 retention_days = self.parameters.get('properties', {}).get('soft_delete_retention_in_days')
777 administrators = self.administrators
778 bypass = None
779 default_action = None
780 public_network_access = None
781 properties = ManagedHsmProperties(tenant_id=tenant_id,
782 enable_purge_protection=enable_purge_protection,
783 soft_delete_retention_in_days=retention_days,
784 initial_admin_object_ids=administrators,
785 network_acls=_create_network_rule_set(bypass, default_action),
786 public_network_access=public_network_access)
787 sku = self.parameters.get('sku')
788 parameters = ManagedHsm(location=self.parameters.get('location'),
789 tags=self.parameters.get('tags'),
790 sku=ManagedHsmSku(name=sku.get('name'), family=sku.get('family')),
791 identity=self.parameters.get('identity'),
792 properties=properties)
793 try:
794 response = self.mgmt_client.managed_hsms.begin_create_or_update(resource_group_name=self.resource_group,
795 name=self.hsm_name,
796 parameters=parameters)
797 if isinstance(response, LROPoller):
798 response = self.get_poller_result(response)
799
800 except Exception as exc:
801 self.log('Error attempting to create the HSM instance.')
802 self.fail("Error creating the HSM instance: {0}".format(str(exc)))
803 return response and response.as_dict() or None
804
805 def delete_keyvault(self):
806 '''
807 Deletes specified Key Vault instance in the specified subscription and resource group.
808
809 :return: True
810 '''
811 self.log("Deleting the Key Vault instance {0}".format(self.vault_name))
812 try:
813 response = self.mgmt_client.vaults.delete(resource_group_name=self.resource_group,
814 vault_name=self.vault_name)
815 except Exception as e:
816 self.log('Error attempting to delete the Key Vault instance.')
817 self.fail("Error deleting the Key Vault instance: {0}".format(str(e)))
818
819 return True
820
821 def hsm_begin_delete(self):
822 '''
823 Deletes specified hsm instance in the specified subscription and resource group.
824
825 :return: True
826 '''
827 self.log("Deleting the hsm instance {0}".format(self.hsm_name))
828 try:
829 response = self.mgmt_client.managed_hsms.begin_delete(resource_group_name=self.resource_group,
830 name=self.hsm_name)
831 if isinstance(response, LROPoller):
832 self.get_poller_result(response)
833 except Exception as e:
834 self.log('Error attempting to delete the hsm instance.')
835 self.fail("Error deleting the hsm instance: {0}".format(str(e)))
836
837 return True
838
839 def get_deleted(self, location):
840 '''
841 Get deleted vault
842 :return: True or False
843 '''
844 try:
845 if self.hsm_name:
846 self.log("Get deleted hsm vault instance {0}".format(self.hsm_name))
847 self.mgmt_client.managed_hsms.get_deleted(self.hsm_name, location)
848 else:
849 self.log("Get deleted vault instance {0}".format(self.vault_name))
850 self.mgmt_client.vaults.get_deleted(self.vault_name, location)
851 except Exception as e:
852 self.log('Error attempting to get the deleted vault instance: {0}'.format(str(e)))
853 return False
854 return True
855
856 def purge_deleted(self, location):
857 '''
858 Purge vault instance in the specified subscription and resource group.
859 '''
860 try:
861 if self.hsm_name:
862 self.log("Purge the deleted hsm vault instance {0}".format(self.hsm_name))
863 response = self.mgmt_client.managed_hsms.begin_purge_deleted(self.hsm_name, location)
864 else:
865 self.log("Purge the deleted vault instance {0}".format(self.vault_name))
866 response = self.mgmt_client.vaults.begin_purge_deleted(self.vault_name, location)
867 except Exception as e:
868 self.log('Error attempting to delete the vault instance.')
869 self.fail("Error purge the vault instance: {0}".format(str(e)))
870
871 def get_instance(self):
872 '''
873 Gets the properties of the specified Key Vault or HSM.
874
875 :return: deserialized Key Vault or HSM instance state dictionary
876 '''
877 found = False
878
879 if self.vault_name is not None:
880 self.log("Checking if the Key Vault instance {0} is present".format(self.vault_name))
881 try:
882 response = self.mgmt_client.vaults.get(resource_group_name=self.resource_group,
883 vault_name=self.vault_name)
884 found = True
885 self.log("Response : {0}".format(response))
886 self.log("Key Vault instance : {0} found".format(response.name))
887 except ResourceNotFoundError as e:
888 self.log('Did not find the Key Vault instance.')
889
890 if self.hsm_name is not None:
891 self.log("Checking if the hsm instance {0} is present".format(self.hsm_name))
892 try:
893 response = self.mgmt_client.managed_hsms.get(resource_group_name=self.resource_group,
894 name=self.hsm_name)
895 found = True
896 self.log("Response : {0}".format(response))
897 self.log("HSM instance : {0} found".format(response.name))
898 except ResourceNotFoundError as e:
899 self.log('Did not find the hsm instance.')
900
901 if found is True:
902 return response.as_dict()
903
904 return False
905
906
907 def _create_network_rule_set(bypass=None, default_action=None):
908 return NetworkRuleSet(bypass=bypass or NetworkRuleBypassOptions.azure_services.value,
909 default_action=default_action or NetworkRuleAction.allow.value)
910
911
912 def main():
913 """Main execution"""
914 AzureRMVaults()
915
916
917 if __name__ == '__main__':
918 main()