Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/kms_key_info.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_info
10 version_added: 5.0.0
11 short_description: Gather information about AWS KMS keys
12 description:
13 - Gather information about AWS KMS keys including tags and grants.
14 - Prior to release 5.0.0 this module was called M(community.aws.aws_kms_info).
15 The usage did not change.
16 - This module was originally added to C(community.aws) in release 1.0.0.
17 author:
18 - "Will Thames (@willthames)"
19 options:
20 alias:
21 description:
22 - Alias for key.
23 - Mutually exclusive with O(key_id) and O(filters).
24 required: false
25 aliases:
26 - key_alias
27 type: str
28 version_added: 1.4.0
29 version_added_collection: community.aws
30 key_id:
31 description:
32 - Key ID or ARN of the key.
33 - Mutually exclusive with O(alias) and O(filters).
34 required: false
35 aliases:
36 - key_arn
37 type: str
38 version_added: 1.4.0
39 version_added_collection: community.aws
40 filters:
41 description:
42 - A dict of filters to apply. Each dict item consists of a filter key and a filter value.
43 The filters aren't natively supported by boto3, but are supported to provide similar
44 functionality to other modules. Standard tag filters (V(tag-key), V(tag-value) and
45 V(tag:tagName)) are available, as are V(key-id) and V(alias)
46 - Mutually exclusive with O(alias) and O(key_id).
47 type: dict
48 pending_deletion:
49 description: Whether to get full details (tags, grants etc.) of keys pending deletion.
50 default: false
51 type: bool
52 notes:
53 - The C(policies) return key was removed in amazon.aws release 8.0.0.
54 extends_documentation_fragment:
55 - amazon.aws.common.modules
56 - amazon.aws.region.modules
57 - amazon.aws.boto3
58 """
59
60 EXAMPLES = r"""
61 # Note: These examples do not set authentication details, see the AWS Guide for details.
62
63 # Gather information about all KMS keys
64 - amazon.aws.kms_key_info:
65
66 # Gather information about all keys with a Name tag
67 - amazon.aws.kms_key_info:
68 filters:
69 tag-key: Name
70
71 # Gather information about all keys with a specific name
72 - amazon.aws.kms_key_info:
73 filters:
74 "tag:Name": Example
75 """
76
77 RETURN = r"""
78 kms_keys:
79 description: List of keys.
80 type: complex
81 returned: always
82 contains:
83 key_id:
84 description: ID of key.
85 type: str
86 returned: always
87 sample: "abcd1234-abcd-1234-5678-ef1234567890"
88 key_arn:
89 description: ARN of key.
90 type: str
91 returned: always
92 sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
93 key_manager:
94 description: The manager of the KMS key.
95 type: str
96 returned: always
97 sample: "AWS"
98 key_spec:
99 description: Specifies the type of KMS key to create.
100 type: str
101 returned: always
102 sample: "SYMMETRIC_DEFAULT"
103 key_state:
104 description:
105 - The state of the key.
106 - Will be one of C('Creating'), C('Enabled'), C('Disabled'), C('PendingDeletion'), C('PendingImport'),
107 C('PendingReplicaDeletion'), C('Unavailable'), or C('Updating').
108 type: str
109 returned: always
110 sample: "PendingDeletion"
111 key_usage:
112 description: The cryptographic operations for which you can use the key.
113 type: str
114 returned: always
115 sample: "ENCRYPT_DECRYPT"
116 origin:
117 description: The source of the key's key material. When this value is C(AWS_KMS),
118 AWS KMS created the key material. When this value is C(EXTERNAL), the
119 key material was imported or the CMK lacks key material.
120 type: str
121 returned: always
122 sample: "AWS_KMS"
123 aws_account_id:
124 description: The AWS Account ID that the key belongs to.
125 type: str
126 returned: always
127 sample: "123456789012"
128 creation_date:
129 description: Date and time of creation of the key.
130 type: str
131 returned: always
132 sample: "2017-04-18T15:12:08.551000+10:00"
133 deletion_date:
134 description: Date and time after which KMS deletes this KMS key.
135 type: str
136 returned: when RV(kms_keys.key_state) is PendingDeletion
137 sample: "2017-04-18T15:12:08.551000+10:00"
138 version_added: 3.3.0
139 version_added_collection: community.aws
140 description:
141 description: Description of the key.
142 type: str
143 returned: always
144 sample: "My Key for Protecting important stuff"
145 enabled:
146 description: Whether the key is enabled. True if RV(kms_keys.key_state) is V(Enabled).
147 type: bool
148 returned: always
149 sample: false
150 enable_key_rotation:
151 description: Whether the automatic annual key rotation is enabled. Returns None if key rotation status can't be determined.
152 type: bool
153 returned: always
154 sample: false
155 aliases:
156 description: List of aliases associated with the key.
157 type: list
158 returned: always
159 sample:
160 - aws/acm
161 - aws/ebs
162 tags:
163 description: Dictionary of tags applied to the key. Empty when access is denied even if there are tags.
164 type: dict
165 returned: always
166 sample:
167 Name: myKey
168 Purpose: protecting_stuff
169 key_policies:
170 description: List of policy documents for the key. Empty when access is denied even if there are policies.
171 type: list
172 returned: always
173 elements: dict
174 sample:
175 Version: "2012-10-17"
176 Id: "auto-ebs-2"
177 Statement:
178 - Sid: "Allow access through EBS for all principals in the account that are authorized to use EBS"
179 Effect: "Allow"
180 Principal:
181 AWS: "*"
182 Action:
183 - "kms:Encrypt"
184 - "kms:Decrypt"
185 - "kms:ReEncrypt*"
186 - "kms:GenerateDataKey*"
187 - "kms:CreateGrant"
188 - "kms:DescribeKey"
189 Resource: "*"
190 Condition:
191 StringEquals:
192 kms:CallerAccount: "123456789012"
193 kms:ViaService: "ec2.ap-southeast-2.amazonaws.com"
194 - Sid: "Allow direct access to key metadata to the account"
195 Effect: "Allow"
196 Principal:
197 AWS: "arn:aws:iam::123456789012:root"
198 Action:
199 - "kms:Describe*"
200 - "kms:Get*"
201 - "kms:List*"
202 - "kms:RevokeGrant"
203 Resource: "*"
204 version_added: 3.3.0
205 version_added_collection: community.aws
206 grants:
207 description: List of grants associated with a key.
208 type: list
209 elements: dict
210 returned: always
211 contains:
212 constraints:
213 description: Constraints on the encryption context that the grant allows.
214 See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) for further details
215 type: dict
216 returned: always
217 sample:
218 encryption_context_equals:
219 "aws:lambda:_function_arn": "arn:aws:lambda:ap-southeast-2:123456789012:function:xyz"
220 creation_date:
221 description: Date of creation of the grant.
222 type: str
223 returned: always
224 sample: "2017-04-18T15:12:08+10:00"
225 grant_id:
226 description: The unique ID for the grant.
227 type: str
228 returned: always
229 sample: "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234"
230 grantee_principal:
231 description: The principal that receives the grant's permissions.
232 type: str
233 returned: always
234 sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
235 issuing_account:
236 description: The AWS account under which the grant was issued.
237 type: str
238 returned: always
239 sample: "arn:aws:iam::123456789012:root"
240 key_id:
241 description: The key ARN to which the grant applies.
242 type: str
243 returned: always
244 sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
245 name:
246 description: The friendly name that identifies the grant.
247 type: str
248 returned: always
249 sample: "xyz"
250 operations:
251 description: The list of operations permitted by the grant.
252 type: list
253 elements: str
254 returned: always
255 sample: [
256 "Decrypt",
257 "GenerateDataKey"
258 ]
259 retiring_principal:
260 description: The principal that can retire the grant.
261 type: str
262 returned: always
263 sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
264 customer_master_key_spec:
265 description: Describes the type of key material in the KMS key.
266 type: str
267 returned: always
268 sample: "SYMMETRIC_DEFAULT"
269 encryption_algorithms:
270 description: The encryption algorithms that the KMS key supports.
271 type: list
272 elements: str
273 returned: always
274 sample: ["SYMMETRIC_DEFAULT"]
275 multi_region:
276 description: Indicates whether the KMS key is a multi-Region (True) or regional (False) key.
277 type: bool
278 returned: always
279 sample: false
280 """
281
282 import json
283
284 try:
285 import botocore
286 except ImportError:
287 pass # Handled by AnsibleAWSModule
288
289 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
290
291 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
292 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
293 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
294 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
295
296 # Caching lookup for aliases
297 _aliases = dict()
298
299
300 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
301 def get_kms_keys_with_backoff(connection):
302 paginator = connection.get_paginator("list_keys")
303 return paginator.paginate().build_full_result()
304
305
306 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
307 def get_kms_aliases_with_backoff(connection):
308 paginator = connection.get_paginator("list_aliases")
309 return paginator.paginate().build_full_result()
310
311
312 def get_kms_aliases_lookup(connection):
313 if not _aliases:
314 for alias in get_kms_aliases_with_backoff(connection)["Aliases"]:
315 # Not all aliases are actually associated with a key
316 if "TargetKeyId" in alias:
317 # strip off leading 'alias/' and add it to key's aliases
318 if alias["TargetKeyId"] in _aliases:
319 _aliases[alias["TargetKeyId"]].append(alias["AliasName"][6:])
320 else:
321 _aliases[alias["TargetKeyId"]] = [alias["AliasName"][6:]]
322 return _aliases
323
324
325 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
326 def get_kms_tags_with_backoff(connection, key_id, **kwargs):
327 return connection.list_resource_tags(KeyId=key_id, **kwargs)
328
329
330 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
331 def get_kms_grants_with_backoff(connection, key_id, **kwargs):
332 params = dict(KeyId=key_id)
333 if kwargs.get("tokens"):
334 params["GrantTokens"] = kwargs["tokens"]
335 paginator = connection.get_paginator("list_grants")
336 return paginator.paginate(**params).build_full_result()
337
338
339 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
340 def get_kms_metadata_with_backoff(connection, key_id):
341 return connection.describe_key(KeyId=key_id)
342
343
344 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
345 def list_key_policies_with_backoff(connection, key_id):
346 paginator = connection.get_paginator("list_key_policies")
347 return paginator.paginate(KeyId=key_id).build_full_result()
348
349
350 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
351 def get_key_policy_with_backoff(connection, key_id, policy_name):
352 return connection.get_key_policy(KeyId=key_id, PolicyName=policy_name)
353
354
355 @AWSRetry.jittered_backoff(retries=5, delay=5, backoff=2.0)
356 def get_enable_key_rotation_with_backoff(connection, key_id):
357 try:
358 current_rotation_status = connection.get_key_rotation_status(KeyId=key_id)
359 except is_boto3_error_code(["AccessDeniedException", "UnsupportedOperationException"]):
360 return None
361
362 return current_rotation_status.get("KeyRotationEnabled")
363
364
365 def canonicalize_alias_name(alias):
366 if alias is None:
367 return None
368 if alias.startswith("alias/"):
369 return alias
370 return "alias/" + alias
371
372
373 def get_kms_tags(connection, module, key_id):
374 # Handle pagination here as list_resource_tags does not have
375 # a paginator
376 kwargs = {}
377 tags = []
378 more = True
379 while more:
380 try:
381 tag_response = get_kms_tags_with_backoff(connection, key_id, **kwargs)
382 tags.extend(tag_response["Tags"])
383 except is_boto3_error_code("AccessDeniedException"):
384 tag_response = {}
385 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
386 module.fail_json_aws(e, msg="Failed to obtain key tags")
387 if tag_response.get("NextMarker"):
388 kwargs["Marker"] = tag_response["NextMarker"]
389 else:
390 more = False
391 return tags
392
393
394 def get_kms_policies(connection, module, key_id):
395 try:
396 policies = list_key_policies_with_backoff(connection, key_id)["PolicyNames"]
397 return [get_key_policy_with_backoff(connection, key_id, policy)["Policy"] for policy in policies]
398 except is_boto3_error_code("AccessDeniedException"):
399 return []
400 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
401 module.fail_json_aws(e, msg="Failed to obtain key policies")
402
403
404 def key_matches_filter(key, filtr):
405 if filtr[0] == "key-id":
406 return filtr[1] == key["key_id"]
407 if filtr[0] == "tag-key":
408 return filtr[1] in key["tags"]
409 if filtr[0] == "tag-value":
410 return filtr[1] in key["tags"].values()
411 if filtr[0] == "alias":
412 return filtr[1] in key["aliases"]
413 if filtr[0].startswith("tag:"):
414 tag_key = filtr[0][4:]
415 if tag_key not in key["tags"]:
416 return False
417 return key["tags"].get(tag_key) == filtr[1]
418
419
420 def key_matches_filters(key, filters):
421 if not filters:
422 return True
423 else:
424 return all(key_matches_filter(key, filtr) for filtr in filters.items())
425
426
427 def get_key_details(connection, module, key_id, tokens=None):
428 if not tokens:
429 tokens = []
430 try:
431 result = get_kms_metadata_with_backoff(connection, key_id)["KeyMetadata"]
432 # Make sure we have the canonical ARN, we might have been passed an alias
433 key_id = result["Arn"]
434 except is_boto3_error_code("NotFoundException"):
435 return None
436 except is_boto3_error_code("AccessDeniedException"): # pylint: disable=duplicate-except
437 module.warn(f"Permission denied fetching key metadata ({key_id})")
438 return None
439 except (
440 botocore.exceptions.ClientError,
441 botocore.exceptions.BotoCoreError,
442 ) as e: # pylint: disable=duplicate-except
443 module.fail_json_aws(e, msg="Failed to obtain key metadata")
444 result["KeyArn"] = result.pop("Arn")
445
446 try:
447 aliases = get_kms_aliases_lookup(connection)
448 except is_boto3_error_code("AccessDeniedException"):
449 module.warn("Permission denied fetching key aliases")
450 aliases = {}
451 except (
452 botocore.exceptions.ClientError,
453 botocore.exceptions.BotoCoreError,
454 ) as e: # pylint: disable=duplicate-except
455 module.fail_json_aws(e, msg="Failed to obtain aliases")
456 # We can only get aliases for our own account, so we don't need the full ARN
457 result["aliases"] = aliases.get(result["KeyId"], [])
458 result["enable_key_rotation"] = get_enable_key_rotation_with_backoff(connection, key_id)
459
460 if module.params.get("pending_deletion"):
461 return camel_dict_to_snake_dict(result)
462
463 try:
464 result["grants"] = get_kms_grants_with_backoff(connection, key_id, tokens=tokens)["Grants"]
465 except is_boto3_error_code("AccessDeniedException"):
466 module.warn(f"Permission denied fetching key grants ({key_id})")
467 result["grants"] = []
468 except (
469 botocore.exceptions.ClientError,
470 botocore.exceptions.BotoCoreError,
471 ) as e: # pylint: disable=duplicate-except
472 module.fail_json_aws(e, msg="Failed to obtain key grants")
473
474 tags = get_kms_tags(connection, module, key_id)
475
476 result = camel_dict_to_snake_dict(result)
477 result["tags"] = boto3_tag_list_to_ansible_dict(tags, "TagKey", "TagValue")
478 policies = get_kms_policies(connection, module, key_id)
479 result["key_policies"] = [json.loads(policy) for policy in policies]
480 return result
481
482
483 def get_kms_info(connection, module):
484 if module.params.get("key_id"):
485 key_id = module.params.get("key_id")
486 details = get_key_details(connection, module, key_id)
487 if details:
488 return [details]
489 return []
490 elif module.params.get("alias"):
491 alias = canonicalize_alias_name(module.params.get("alias"))
492 details = get_key_details(connection, module, alias)
493 if details:
494 return [details]
495 return []
496 else:
497 try:
498 keys = get_kms_keys_with_backoff(connection)["Keys"]
499 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
500 module.fail_json_aws(e, msg="Failed to obtain keys")
501 return [get_key_details(connection, module, key["KeyId"]) for key in keys]
502
503
504 def main():
505 argument_spec = dict(
506 alias=dict(aliases=["key_alias"]),
507 key_id=dict(aliases=["key_arn"]),
508 filters=dict(type="dict"),
509 pending_deletion=dict(type="bool", default=False),
510 )
511
512 module = AnsibleAWSModule(
513 argument_spec=argument_spec, mutually_exclusive=[["alias", "filters", "key_id"]], supports_check_mode=True
514 )
515
516 try:
517 connection = module.client("kms")
518 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
519 module.fail_json_aws(e, msg="Failed to connect to AWS")
520
521 all_keys = get_kms_info(connection, module)
522 filtered_keys = [key for key in all_keys if key_matches_filters(key, module.params["filters"])]
523 ret_params = dict(kms_keys=filtered_keys)
524
525 module.exit_json(**ret_params)
526
527
528 if __name__ == "__main__":
529 main()