Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/kms_key.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: kms_key
10 version_added: 5.0.0
11 short_description: Perform various KMS key management tasks
12 description:
13 - Manage role/user access to a KMS key.
14 - Not designed for encrypting/decrypting.
15 - Prior to release 5.0.0 this module was called M(community.aws.aws_kms).
16 The usage did not change.
17 - This module was originally added to C(community.aws) in release 1.0.0.
18 options:
19 alias:
20 description:
21 - An alias for a key.
22 - For safety, even though KMS does not require keys to have an alias, this module expects all
23 new keys to be given an alias to make them easier to manage. Existing keys without an alias
24 may be referred to by O(key_id). Use M(amazon.aws.kms_key_info) to find key ids.
25 - Note that passing a O(key_id) and O(alias) will only cause a new alias to be added, an alias will never be renamed.
26 - The V(alias/) prefix is optional.
27 - Required if O(key_id) is not given.
28 required: false
29 aliases:
30 - key_alias
31 type: str
32 key_id:
33 description:
34 - Key ID or ARN of the key.
35 - One of O(alias) or O(key_id) are required.
36 required: false
37 aliases:
38 - key_arn
39 type: str
40 enable_key_rotation:
41 description:
42 - Whether the key should be automatically rotated every year.
43 required: false
44 type: bool
45 state:
46 description:
47 - Whether a key should be present or absent.
48 - Note that making an existing key V(absent) only schedules a key for deletion.
49 - Passing a key that is scheduled for deletion with O(state=present) will cancel key deletion.
50 required: false
51 choices:
52 - present
53 - absent
54 default: present
55 type: str
56 enabled:
57 description: Whether or not a key is enabled.
58 default: true
59 type: bool
60 description:
61 description:
62 - A description of the CMK.
63 - Use a description that helps you decide whether the CMK is appropriate for a task.
64 type: str
65 multi_region:
66 description:
67 - Whether to create a multi-Region primary key or not.
68 default: false
69 type: bool
70 version_added: 5.5.0
71 pending_window:
72 description:
73 - The number of days between requesting deletion of the CMK and when it will actually be deleted.
74 - Only used when O(state=absent) and the CMK has not yet been deleted.
75 - Valid values are between V(7) and V(30) (inclusive).
76 - 'See also: U(https://docs.aws.amazon.com/kms/latest/APIReference/API_ScheduleKeyDeletion.html#KMS-ScheduleKeyDeletion-request-PendingWindowInDays)'
77 type: int
78 aliases: ['deletion_delay']
79 version_added: 1.4.0
80 version_added_collection: community.aws
81 purge_grants:
82 description:
83 - Whether the O(grants) argument should cause grants not in the list to be removed.
84 default: false
85 type: bool
86 grants:
87 description:
88 - A list of grants to apply to the key. Each item must contain O(grants.grantee_principal).
89 Each item can optionally contain O(grants.retiring_principal), O(grants.operations), O(grants.constraints),
90 O(grants.name).
91 - O(grants.grantee_principal) and O(grants.retiring_principal) must be ARNs.
92 - 'For full documentation of suboptions see the boto3 documentation:'
93 - 'U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kms.html#KMS.Client.create_grant)'
94 type: list
95 elements: dict
96 default: []
97 suboptions:
98 grantee_principal:
99 description: The full ARN of the principal being granted permissions.
100 required: true
101 type: str
102 retiring_principal:
103 description: The full ARN of the principal permitted to revoke/retire the grant.
104 type: str
105 operations:
106 type: list
107 elements: str
108 description:
109 - A list of operations that the grantee may perform using the CMK.
110 choices: ['Decrypt', 'Encrypt', 'GenerateDataKey', 'GenerateDataKeyWithoutPlaintext', 'ReEncryptFrom', 'ReEncryptTo',
111 'CreateGrant', 'RetireGrant', 'DescribeKey', 'Verify', 'Sign']
112 constraints:
113 description:
114 - Constraints is a dict containing V(encryption_context_subset) or V(encryption_context_equals),
115 either or both being a dict specifying an encryption context match.
116 See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) or
117 U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kms.html#KMS.Client.create_grant)
118 type: dict
119 name:
120 description:
121 - A friendly name for the grant.
122 - Use this value to prevent the unintended creation of duplicate grants when retrying this request.
123 type: str
124 policy:
125 description:
126 - Policy to apply to the KMS key.
127 - See U(https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)
128 type: json
129 key_spec:
130 aliases:
131 - customer_master_key_spec
132 description:
133 - Specifies the type of KMS key to create.
134 - The specification is not changeable once the key is created.
135 type: str
136 default: SYMMETRIC_DEFAULT
137 choices: ['SYMMETRIC_DEFAULT', 'RSA_2048', 'RSA_3072', 'RSA_4096', 'ECC_NIST_P256', 'ECC_NIST_P384', 'ECC_NIST_P521', 'ECC_SECG_P256K1']
138 version_added: 2.1.0
139 version_added_collection: community.aws
140 key_usage:
141 description:
142 - Determines the cryptographic operations for which you can use the KMS key.
143 - The usage is not changeable once the key is created.
144 type: str
145 default: ENCRYPT_DECRYPT
146 choices: ['ENCRYPT_DECRYPT', 'SIGN_VERIFY']
147 version_added: 2.1.0
148 version_added_collection: community.aws
149 author:
150 - Ted Timmons (@tedder)
151 - Will Thames (@willthames)
152 - Mark Chappell (@tremble)
153 extends_documentation_fragment:
154 - amazon.aws.common.modules
155 - amazon.aws.region.modules
156 - amazon.aws.tags
157 - amazon.aws.boto3
158
159 notes:
160 - There are known inconsistencies in the amount of time required for updates of KMS keys to be fully reflected on AWS.
161 This can cause issues when running duplicate tasks in succession or using the M(amazon.aws.kms_key_info) module to fetch key metadata
162 shortly after modifying keys.
163 For this reason, it is recommended to use the return data from this module (M(amazon.aws.kms_key)) to fetch a key's metadata.
164 - The C(policies) return key was removed in amazon.aws release 8.0.0.
165 """
166
167 EXAMPLES = r"""
168 # Create a new KMS key
169 - amazon.aws.kms_key:
170 alias: mykey
171 tags:
172 Name: myKey
173 Purpose: protect_stuff
174
175 # Create a new multi-region KMS key
176 - amazon.aws.kms_key:
177 alias: mykey
178 multi_region: true
179 tags:
180 Name: myKey
181 Purpose: protect_stuff
182
183 # Update previous key with more tags
184 - amazon.aws.kms_key:
185 alias: mykey
186 tags:
187 Name: myKey
188 Purpose: protect_stuff
189 Owner: security_team
190
191 # Update a known key with grants allowing an instance with the billing-prod IAM profile
192 # to decrypt data encrypted with the environment: production, application: billing
193 # encryption context
194 - amazon.aws.kms_key:
195 key_id: abcd1234-abcd-1234-5678-ef1234567890
196 grants:
197 - name: billing_prod
198 grantee_principal: arn:aws:iam::123456789012:role/billing_prod
199 constraints:
200 encryption_context_equals:
201 environment: production
202 application: billing
203 operations:
204 - Decrypt
205 - RetireGrant
206
207 - name: Update IAM policy on an existing KMS key
208 amazon.aws.kms_key:
209 alias: my-kms-key
210 policy: '{"Version": "2012-10-17", "Id": "my-kms-key-permissions", "Statement": [ { <SOME STATEMENT> } ]}'
211 state: present
212
213 - name: Example using lookup for policy json
214 amazon.aws.kms_key:
215 alias: my-kms-key
216 policy: "{{ lookup('template', 'kms_iam_policy_template.json.j2') }}"
217 state: present
218 """
219
220 RETURN = r"""
221 key_id:
222 description: ID of key.
223 type: str
224 returned: always
225 sample: "abcd1234-abcd-1234-5678-ef1234567890"
226 key_arn:
227 description: ARN of key.
228 type: str
229 returned: always
230 sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
231 key_state:
232 description:
233 - The state of the key.
234 - Will be one of C('Creating'), C('Enabled'), C('Disabled'), C('PendingDeletion'), C('PendingImport'),
235 C('PendingReplicaDeletion'), C('Unavailable'), or C('Updating').
236 type: str
237 returned: always
238 sample: "PendingDeletion"
239 key_usage:
240 description: The cryptographic operations for which you can use the key.
241 type: str
242 returned: always
243 sample: "ENCRYPT_DECRYPT"
244 origin:
245 description: The source of the key's key material. When this value is C(AWS_KMS),
246 AWS KMS created the key material. When this value is C(EXTERNAL), the
247 key material was imported or the CMK lacks key material.
248 type: str
249 returned: always
250 sample: "AWS_KMS"
251 aws_account_id:
252 description: The AWS Account ID that the key belongs to.
253 type: str
254 returned: always
255 sample: "1234567890123"
256 creation_date:
257 description: Date and time of creation of the key.
258 type: str
259 returned: always
260 sample: "2017-04-18T15:12:08.551000+10:00"
261 deletion_date:
262 description: Date and time after which KMS deletes this KMS key.
263 type: str
264 returned: when RV(key_state) is PendingDeletion
265 sample: "2017-04-18T15:12:08.551000+10:00"
266 version_added: 3.3.0
267 version_added_collection: community.aws
268 description:
269 description: Description of the key.
270 type: str
271 returned: always
272 sample: "My Key for Protecting important stuff"
273 enabled:
274 description: Whether the key is enabled. True if RV(key_state) is V(Enabled).
275 type: bool
276 returned: always
277 sample: false
278 enable_key_rotation:
279 description: Whether the automatic annual key rotation is enabled. Returns None if key rotation status can't be determined.
280 type: bool
281 returned: always
282 sample: false
283 aliases:
284 description: List of aliases associated with the key.
285 type: list
286 returned: always
287 sample:
288 - aws/acm
289 - aws/ebs
290 key_policies:
291 description: List of policy documents for the key. Empty when access is denied even if there are policies.
292 type: list
293 returned: always
294 elements: dict
295 sample:
296 Version: "2012-10-17"
297 Id: "auto-ebs-2"
298 Statement:
299 - Sid: "Allow access through EBS for all principals in the account that are authorized to use EBS"
300 Effect: "Allow"
301 Principal:
302 AWS: "*"
303 Action:
304 - "kms:Encrypt"
305 - "kms:Decrypt"
306 - "kms:ReEncrypt*"
307 - "kms:GenerateDataKey*"
308 - "kms:CreateGrant"
309 - "kms:DescribeKey"
310 Resource: "*"
311 Condition:
312 StringEquals:
313 kms:CallerAccount: "123456789012"
314 kms:ViaService: "ec2.ap-southeast-2.amazonaws.com"
315 - Sid: "Allow direct access to key metadata to the account"
316 Effect: "Allow"
317 Principal:
318 AWS: "arn:aws:iam::123456789012:root"
319 Action:
320 - "kms:Describe*"
321 - "kms:Get*"
322 - "kms:List*"
323 - "kms:RevokeGrant"
324 Resource: "*"
325 version_added: 3.3.0
326 version_added_collection: community.aws
327 tags:
328 description: Dictionary of tags applied to the key. Empty when access is denied even if there are tags.
329 type: dict
330 returned: always
331 sample:
332 Name: myKey
333 Purpose: protecting_stuff
334 grants:
335 description: List of grants associated with a key.
336 type: list
337 elements: dict
338 returned: always
339 contains:
340 constraints:
341 description: Constraints on the encryption context that the grant allows.
342 See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) for further details
343 type: dict
344 returned: always
345 sample:
346 encryption_context_equals:
347 "aws:lambda:_function_arn": "arn:aws:lambda:ap-southeast-2:123456789012:function:xyz"
348 creation_date:
349 description: Date of creation of the grant.
350 type: str
351 returned: always
352 sample: "2017-04-18T15:12:08+10:00"
353 grant_id:
354 description: The unique ID for the grant.
355 type: str
356 returned: always
357 sample: "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234"
358 grantee_principal:
359 description: The principal that receives the grant's permissions.
360 type: str
361 returned: always
362 sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
363 issuing_account:
364 description: The AWS account under which the grant was issued.
365 type: str
366 returned: always
367 sample: "arn:aws:iam::123456789012:root"
368 key_id:
369 description: The key ARN to which the grant applies.
370 type: str
371 returned: always
372 sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
373 name:
374 description: The friendly name that identifies the grant.
375 type: str
376 returned: always
377 sample: "xyz"
378 operations:
379 description: The list of operations permitted by the grant.
380 type: list
381 returned: always
382 sample:
383 - Decrypt
384 - RetireGrant
385 retiring_principal:
386 description: The principal that can retire the grant.
387 type: str
388 returned: always
389 sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
390 changes_needed:
391 description: Grant types that would be changed/were changed.
392 type: dict
393 returned: always
394 sample: { "role": "add", "role grant": "add" }
395 had_invalid_entries:
396 description: Whether there are invalid (non-ARN) entries in the KMS entry. These don't count as a change, but will be removed if any changes are being made.
397 type: bool
398 returned: always
399 multi_region:
400 description:
401 - Indicates whether the CMK is a multi-Region C(True) or regional C(False) key.
402 - This value is True for multi-Region primary and replica CMKs and False for regional CMKs.
403 type: bool
404 version_added: 5.5.0
405 returned: always
406 sample: False
407 customer_master_key_spec:
408 description: Specifies the type of KMS key to create.
409 type: str
410 returned: always
411 sample: "SYMMETRIC_DEFAULT"
412 encryption_algorithms:
413 description: The encryption algorithms that the KMS key supports.
414 type: list
415 elements: str
416 returned: always
417 sample: ["SYMMETRIC_DEFAULT"]
418 key_manager:
419 description: The manager of the KMS key.
420 type: str
421 returned: always
422 sample: "AWS"
423 key_spec:
424 description: Specifies the type of KMS key to create.
425 type: str
426 returned: always
427 sample: "SYMMETRIC_DEFAULT"
428 """
429
430 import json
431
432 try:
433 import botocore
434 except ImportError:
435 pass # caught by AnsibleAWSModule
436
437 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
438
439 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
440 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
441 from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies
442 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
443 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
444 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
445 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
446
447
448 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
449 def get_kms_keys_with_backoff(connection):
450 paginator = connection.get_paginator("list_keys")
451 return paginator.paginate().build_full_result()
452
453
454 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
455 def get_kms_aliases_with_backoff(connection):
456 paginator = connection.get_paginator("list_aliases")
457 return paginator.paginate().build_full_result()
458
459
460 def get_kms_aliases_lookup(connection):
461 _aliases = dict()
462 for alias in get_kms_aliases_with_backoff(connection)["Aliases"]:
463 # Not all aliases are actually associated with a key
464 if "TargetKeyId" in alias:
465 # strip off leading 'alias/' and add it to key's aliases
466 if alias["TargetKeyId"] in _aliases:
467 _aliases[alias["TargetKeyId"]].append(alias["AliasName"][6:])
468 else:
469 _aliases[alias["TargetKeyId"]] = [alias["AliasName"][6:]]
470 return _aliases
471
472
473 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
474 def get_kms_tags_with_backoff(connection, key_id, **kwargs):
475 return connection.list_resource_tags(KeyId=key_id, **kwargs)
476
477
478 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
479 def get_kms_grants_with_backoff(connection, key_id):
480 params = dict(KeyId=key_id)
481 paginator = connection.get_paginator("list_grants")
482 return paginator.paginate(**params).build_full_result()
483
484
485 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
486 def get_kms_metadata_with_backoff(connection, key_id):
487 return connection.describe_key(KeyId=key_id)
488
489
490 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
491 def list_key_policies_with_backoff(connection, key_id):
492 paginator = connection.get_paginator("list_key_policies")
493 return paginator.paginate(KeyId=key_id).build_full_result()
494
495
496 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
497 def get_key_policy_with_backoff(connection, key_id, policy_name):
498 return connection.get_key_policy(KeyId=key_id, PolicyName=policy_name)
499
500
501 def get_kms_tags(connection, module, key_id):
502 # Handle pagination here as list_resource_tags does not have
503 # a paginator
504 kwargs = {}
505 tags = []
506 more = True
507 while more:
508 try:
509 tag_response = get_kms_tags_with_backoff(connection, key_id, **kwargs)
510 tags.extend(tag_response["Tags"])
511 except is_boto3_error_code("AccessDeniedException"):
512 tag_response = {}
513 except (
514 botocore.exceptions.ClientError,
515 botocore.exceptions.BotoCoreError,
516 ) as e: # pylint: disable=duplicate-except
517 module.fail_json_aws(e, msg="Failed to obtain key tags")
518 if tag_response.get("NextMarker"):
519 kwargs["Marker"] = tag_response["NextMarker"]
520 else:
521 more = False
522 return tags
523
524
525 def get_kms_policies(connection, module, key_id):
526 try:
527 policies = list_key_policies_with_backoff(connection, key_id)["PolicyNames"]
528 return [get_key_policy_with_backoff(connection, key_id, policy)["Policy"] for policy in policies]
529 except is_boto3_error_code("AccessDeniedException"):
530 return []
531 except (
532 botocore.exceptions.ClientError,
533 botocore.exceptions.BotoCoreError,
534 ) as e: # pylint: disable=duplicate-except
535 module.fail_json_aws(e, msg="Failed to obtain key policies")
536
537
538 def camel_to_snake_grant(grant):
539 """camel_to_snake_grant snakifies everything except the encryption context"""
540 constraints = grant.get("Constraints", {})
541 result = camel_dict_to_snake_dict(grant)
542 if "EncryptionContextEquals" in constraints:
543 result["constraints"]["encryption_context_equals"] = constraints["EncryptionContextEquals"]
544 if "EncryptionContextSubset" in constraints:
545 result["constraints"]["encryption_context_subset"] = constraints["EncryptionContextSubset"]
546 return result
547
548
549 def get_key_details(connection, module, key_id):
550 try:
551 result = get_kms_metadata_with_backoff(connection, key_id)["KeyMetadata"]
552 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
553 module.fail_json_aws(e, msg="Failed to obtain key metadata")
554 result["KeyArn"] = result.pop("Arn")
555
556 try:
557 aliases = get_kms_aliases_lookup(connection)
558 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
559 module.fail_json_aws(e, msg="Failed to obtain aliases")
560
561 try:
562 current_rotation_status = connection.get_key_rotation_status(KeyId=key_id)
563 result["enable_key_rotation"] = current_rotation_status.get("KeyRotationEnabled")
564 except is_boto3_error_code(["AccessDeniedException", "UnsupportedOperationException"]):
565 result["enable_key_rotation"] = None
566 result["aliases"] = aliases.get(result["KeyId"], [])
567
568 result = camel_dict_to_snake_dict(result)
569
570 # grants and tags get snakified differently
571 try:
572 result["grants"] = [
573 camel_to_snake_grant(grant) for grant in get_kms_grants_with_backoff(connection, key_id)["Grants"]
574 ]
575 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
576 module.fail_json_aws(e, msg="Failed to obtain key grants")
577 tags = get_kms_tags(connection, module, key_id)
578 result["tags"] = boto3_tag_list_to_ansible_dict(tags, "TagKey", "TagValue")
579 policies = get_kms_policies(connection, module, key_id)
580 result["key_policies"] = [json.loads(policy) for policy in policies]
581 return result
582
583
584 def convert_grant_params(grant, key):
585 grant_params = dict(KeyId=key["key_arn"], GranteePrincipal=grant["grantee_principal"])
586 if grant.get("operations"):
587 grant_params["Operations"] = grant["operations"]
588 if grant.get("retiring_principal"):
589 grant_params["RetiringPrincipal"] = grant["retiring_principal"]
590 if grant.get("name"):
591 grant_params["Name"] = grant["name"]
592 if grant.get("constraints"):
593 grant_params["Constraints"] = dict()
594 if grant["constraints"].get("encryption_context_subset"):
595 grant_params["Constraints"]["EncryptionContextSubset"] = grant["constraints"]["encryption_context_subset"]
596 if grant["constraints"].get("encryption_context_equals"):
597 grant_params["Constraints"]["EncryptionContextEquals"] = grant["constraints"]["encryption_context_equals"]
598 return grant_params
599
600
601 def different_grant(existing_grant, desired_grant):
602 if existing_grant.get("grantee_principal") != desired_grant.get("grantee_principal"):
603 return True
604 if existing_grant.get("retiring_principal") != desired_grant.get("retiring_principal"):
605 return True
606 if set(existing_grant.get("operations", [])) != set(desired_grant.get("operations")):
607 return True
608 if existing_grant.get("constraints") != desired_grant.get("constraints"):
609 return True
610 return False
611
612
613 def compare_grants(existing_grants, desired_grants, purge_grants=False):
614 existing_dict = dict((eg["name"], eg) for eg in existing_grants)
615 desired_dict = dict((dg["name"], dg) for dg in desired_grants)
616 to_add_keys = set(desired_dict.keys()) - set(existing_dict.keys())
617 if purge_grants:
618 to_remove_keys = set(existing_dict.keys()) - set(desired_dict.keys())
619 else:
620 to_remove_keys = set()
621 to_change_candidates = set(existing_dict.keys()) & set(desired_dict.keys())
622 for candidate in to_change_candidates:
623 if different_grant(existing_dict[candidate], desired_dict[candidate]):
624 to_add_keys.add(candidate)
625 to_remove_keys.add(candidate)
626
627 to_add = []
628 to_remove = []
629 for key in to_add_keys:
630 grant = desired_dict[key]
631 to_add.append(grant)
632 for key in to_remove_keys:
633 grant = existing_dict[key]
634 to_remove.append(grant)
635 return to_add, to_remove
636
637
638 def start_key_deletion(connection, module, key_metadata):
639 if key_metadata["KeyState"] == "PendingDeletion":
640 return False
641
642 if module.check_mode:
643 return True
644
645 deletion_params = {"KeyId": key_metadata["Arn"]}
646 if module.params.get("pending_window"):
647 deletion_params["PendingWindowInDays"] = module.params.get("pending_window")
648
649 try:
650 connection.schedule_key_deletion(**deletion_params)
651 return True
652 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
653 module.fail_json_aws(e, msg="Failed to schedule key for deletion")
654
655
656 def cancel_key_deletion(connection, module, key):
657 key_id = key["key_arn"]
658 if key["key_state"] != "PendingDeletion":
659 return False
660
661 if module.check_mode:
662 return True
663
664 try:
665 connection.cancel_key_deletion(KeyId=key_id)
666 # key is disabled after deletion cancellation
667 # set this so that ensure_enabled_disabled works correctly
668 key["key_state"] = "Disabled"
669 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
670 module.fail_json_aws(e, msg="Failed to cancel key deletion")
671
672 return True
673
674
675 def ensure_enabled_disabled(connection, module, key, enabled):
676 desired_state = "Enabled"
677 if not enabled:
678 desired_state = "Disabled"
679
680 if key["key_state"] == desired_state:
681 return False
682
683 key_id = key["key_arn"]
684 if not module.check_mode:
685 if enabled:
686 try:
687 connection.enable_key(KeyId=key_id)
688 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
689 module.fail_json_aws(e, msg="Failed to enable key")
690 else:
691 try:
692 connection.disable_key(KeyId=key_id)
693 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
694 module.fail_json_aws(e, msg="Failed to disable key")
695
696 return True
697
698
699 def update_alias(connection, module, key, alias):
700 alias = canonicalize_alias_name(alias)
701
702 if alias is None:
703 return False
704
705 key_id = key["key_arn"]
706 aliases = get_kms_aliases_with_backoff(connection)["Aliases"]
707 # We will only add new aliases, not rename existing ones
708 if alias in [_alias["AliasName"] for _alias in aliases]:
709 return False
710
711 if not module.check_mode:
712 try:
713 connection.create_alias(TargetKeyId=key_id, AliasName=alias)
714 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
715 module.fail_json_aws(e, msg="Failed create key alias")
716
717 return True
718
719
720 def update_description(connection, module, key, description):
721 if description is None:
722 return False
723 if key["description"] == description:
724 return False
725
726 key_id = key["key_arn"]
727 if not module.check_mode:
728 try:
729 connection.update_key_description(KeyId=key_id, Description=description)
730 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
731 module.fail_json_aws(e, msg="Failed to update key description")
732
733 return True
734
735
736 def update_tags(connection, module, key, desired_tags, purge_tags):
737 if desired_tags is None:
738 return False
739
740 to_add, to_remove = compare_aws_tags(key["tags"], desired_tags, purge_tags)
741 if not (bool(to_add) or bool(to_remove)):
742 return False
743
744 key_id = key["key_arn"]
745 if not module.check_mode:
746 if to_remove:
747 try:
748 connection.untag_resource(KeyId=key_id, TagKeys=to_remove)
749 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
750 module.fail_json_aws(e, msg="Unable to remove tag")
751 if to_add:
752 try:
753 tags = ansible_dict_to_boto3_tag_list(
754 module.params["tags"],
755 tag_name_key_name="TagKey",
756 tag_value_key_name="TagValue",
757 )
758 connection.tag_resource(KeyId=key_id, Tags=tags)
759 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
760 module.fail_json_aws(e, msg="Unable to add tag to key")
761
762 return True
763
764
765 def update_policy(connection, module, key, policy):
766 if policy is None:
767 return False
768 try:
769 new_policy = json.loads(policy)
770 except ValueError as e:
771 module.fail_json_aws(e, msg="Unable to parse new policy as JSON")
772
773 key_id = key["key_arn"]
774 try:
775 keyret = connection.get_key_policy(KeyId=key_id, PolicyName="default")
776 original_policy = json.loads(keyret["Policy"])
777 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError):
778 # If we can't fetch the current policy assume we're making a change
779 # Could occur if we have PutKeyPolicy without GetKeyPolicy
780 original_policy = {}
781
782 if not compare_policies(original_policy, new_policy):
783 return False
784
785 if not module.check_mode:
786 try:
787 connection.put_key_policy(KeyId=key_id, PolicyName="default", Policy=policy)
788 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
789 module.fail_json_aws(e, msg="Unable to update key policy")
790
791 return True
792
793
794 def update_key_rotation(connection, module, key, enable_key_rotation):
795 if enable_key_rotation is None:
796 return False
797 key_id = key["key_arn"]
798
799 try:
800 current_rotation_status = connection.get_key_rotation_status(KeyId=key_id)
801 if current_rotation_status.get("KeyRotationEnabled") == enable_key_rotation:
802 return False
803 except is_boto3_error_code("AccessDeniedException"):
804 pass
805 except (
806 botocore.exceptions.ClientError,
807 botocore.exceptions.BotoCoreError,
808 ) as e: # pylint: disable=duplicate-except
809 module.fail_json_aws(e, msg="Unable to get current key rotation status")
810
811 if not module.check_mode:
812 try:
813 if enable_key_rotation:
814 connection.enable_key_rotation(KeyId=key_id)
815 else:
816 connection.disable_key_rotation(KeyId=key_id)
817 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
818 module.fail_json_aws(e, msg="Failed to enable/disable key rotation")
819
820 return True
821
822
823 def update_grants(connection, module, key, desired_grants, purge_grants):
824 existing_grants = key["grants"]
825
826 to_add, to_remove = compare_grants(existing_grants, desired_grants, purge_grants)
827 if not (bool(to_add) or bool(to_remove)):
828 return False
829
830 key_id = key["key_arn"]
831 if not module.check_mode:
832 for grant in to_remove:
833 try:
834 connection.retire_grant(KeyId=key_id, GrantId=grant["grant_id"])
835 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
836 module.fail_json_aws(e, msg="Unable to retire grant")
837 for grant in to_add:
838 grant_params = convert_grant_params(grant, key)
839 try:
840 connection.create_grant(**grant_params)
841 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
842 module.fail_json_aws(e, msg="Unable to create grant")
843
844 return True
845
846
847 def update_key(connection, module, key):
848 changed = False
849
850 changed |= cancel_key_deletion(connection, module, key)
851 changed |= ensure_enabled_disabled(connection, module, key, module.params["enabled"])
852 changed |= update_alias(connection, module, key, module.params["alias"])
853 changed |= update_description(connection, module, key, module.params["description"])
854 changed |= update_tags(connection, module, key, module.params["tags"], module.params.get("purge_tags"))
855 changed |= update_policy(connection, module, key, module.params.get("policy"))
856 changed |= update_grants(connection, module, key, module.params.get("grants"), module.params.get("purge_grants"))
857 changed |= update_key_rotation(connection, module, key, module.params.get("enable_key_rotation"))
858
859 # make results consistent with kms_facts before returning
860 result = get_key_details(connection, module, key["key_arn"])
861 result["changed"] = changed
862 return result
863
864
865 def create_key(connection, module):
866 key_usage = module.params.get("key_usage")
867 key_spec = module.params.get("key_spec")
868 multi_region = module.params.get("multi_region")
869 tags_list = ansible_dict_to_boto3_tag_list(
870 module.params["tags"] or {},
871 # KMS doesn't use 'Key' and 'Value' as other APIs do.
872 tag_name_key_name="TagKey",
873 tag_value_key_name="TagValue",
874 )
875 params = dict(
876 BypassPolicyLockoutSafetyCheck=False,
877 Tags=tags_list,
878 KeyUsage=key_usage,
879 CustomerMasterKeySpec=key_spec,
880 Origin="AWS_KMS",
881 MultiRegion=multi_region,
882 )
883
884 if module.check_mode:
885 return {"changed": True}
886
887 if module.params.get("description"):
888 params["Description"] = module.params["description"]
889 if module.params.get("policy"):
890 params["Policy"] = module.params["policy"]
891 try:
892 result = connection.create_key(**params)["KeyMetadata"]
893 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
894 module.fail_json_aws(e, msg="Failed to create initial key")
895
896 key = get_key_details(connection, module, result["KeyId"])
897 update_alias(connection, module, key, module.params["alias"])
898 update_key_rotation(connection, module, key, module.params.get("enable_key_rotation"))
899
900 ensure_enabled_disabled(connection, module, key, module.params.get("enabled"))
901 update_grants(connection, module, key, module.params.get("grants"), False)
902
903 # make results consistent with kms_facts
904 result = get_key_details(connection, module, key["key_id"])
905 result["changed"] = True
906 return result
907
908
909 def delete_key(connection, module, key_metadata):
910 changed = False
911
912 changed |= start_key_deletion(connection, module, key_metadata)
913
914 result = get_key_details(connection, module, key_metadata["Arn"])
915 result["changed"] = changed
916 return result
917
918
919 def canonicalize_alias_name(alias):
920 if alias is None:
921 return None
922 if alias.startswith("alias/"):
923 return alias
924 return "alias/" + alias
925
926
927 def fetch_key_metadata(connection, module, key_id, alias):
928 # Note - fetching a key's metadata is very inconsistent shortly after any sort of update to a key has occurred.
929 # Combinations of manual waiters, checking expecting key values to actual key value, and static sleeps
930 # have all been exhausted, but none of those available options have solved the problem.
931 # Integration tests will wait for 10 seconds to combat this issue.
932 # See https://github.com/ansible-collections/community.aws/pull/1052.
933
934 alias = canonicalize_alias_name(alias)
935
936 try:
937 # Fetch by key_id where possible
938 if key_id:
939 return get_kms_metadata_with_backoff(connection, key_id)["KeyMetadata"]
940 # Or try alias as a backup
941 return get_kms_metadata_with_backoff(connection, alias)["KeyMetadata"]
942
943 except connection.exceptions.NotFoundException:
944 return None
945 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
946 module.fail_json_aws(e, "Failed to fetch key metadata.")
947
948
949 def validate_params(module, key_metadata):
950 # We can't create keys with a specific ID, if we can't access the key we'll have to fail
951 if module.params.get("state") == "present" and module.params.get("key_id") and not key_metadata:
952 module.fail_json(msg=f"Could not find key with id {module.params.get('key_id')} to update")
953 if module.params.get("multi_region") and key_metadata and module.params.get("state") == "present":
954 module.fail_json(msg="You cannot change the multi-region property on an existing key.")
955
956
957 def main():
958 argument_spec = dict(
959 alias=dict(aliases=["key_alias"]),
960 pending_window=dict(aliases=["deletion_delay"], type="int"),
961 key_id=dict(aliases=["key_arn"]),
962 description=dict(),
963 enabled=dict(type="bool", default=True),
964 multi_region=dict(type="bool", default=False),
965 tags=dict(type="dict", aliases=["resource_tags"]),
966 purge_tags=dict(type="bool", default=True),
967 grants=dict(type="list", default=[], elements="dict"),
968 policy=dict(type="json"),
969 purge_grants=dict(type="bool", default=False),
970 state=dict(default="present", choices=["present", "absent"]),
971 enable_key_rotation=(dict(type="bool")),
972 key_spec=dict(
973 type="str",
974 default="SYMMETRIC_DEFAULT",
975 aliases=["customer_master_key_spec"],
976 choices=[
977 "SYMMETRIC_DEFAULT",
978 "RSA_2048",
979 "RSA_3072",
980 "RSA_4096",
981 "ECC_NIST_P256",
982 "ECC_NIST_P384",
983 "ECC_NIST_P521",
984 "ECC_SECG_P256K1",
985 ],
986 ),
987 key_usage=dict(
988 type="str",
989 default="ENCRYPT_DECRYPT",
990 choices=["ENCRYPT_DECRYPT", "SIGN_VERIFY"],
991 ),
992 )
993
994 module = AnsibleAWSModule(
995 supports_check_mode=True,
996 argument_spec=argument_spec,
997 required_one_of=[["alias", "key_id"]],
998 )
999
1000 kms = module.client("kms")
1001
1002 key_metadata = fetch_key_metadata(kms, module, module.params.get("key_id"), module.params.get("alias"))
1003 validate_params(module, key_metadata)
1004
1005 if module.params.get("state") == "absent":
1006 if key_metadata is None:
1007 module.exit_json(changed=False)
1008 result = delete_key(kms, module, key_metadata)
1009 module.exit_json(**result)
1010
1011 if key_metadata:
1012 key_details = get_key_details(kms, module, key_metadata["Arn"])
1013 result = update_key(kms, module, key_details)
1014 module.exit_json(**result)
1015
1016 result = create_key(kms, module)
1017 module.exit_json(**result)
1018
1019
1020 if __name__ == "__main__":
1021 main()