Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/iam.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2017 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import re
7
8 try:
9 import botocore
10 except ImportError:
11 pass # Modules are responsible for handling this.
12
13 from ansible.module_utils.common.text.converters import to_native
14
15 from .arn import parse_aws_arn
16 from .arn import validate_aws_arn
17 from .botocore import is_boto3_error_code
18 from .errors import AWSErrorHandler
19 from .exceptions import AnsibleAWSError
20 from .retries import AWSRetry
21 from .tagging import ansible_dict_to_boto3_tag_list
22 from .transformation import AnsibleAWSResource
23 from .transformation import AnsibleAWSResourceList
24 from .transformation import BotoResource
25 from .transformation import BotoResourceList
26 from .transformation import boto3_resource_list_to_ansible_dict
27 from .transformation import boto3_resource_to_ansible_dict
28
29
30 class AnsibleIAMError(AnsibleAWSError):
31 pass
32
33
34 class IAMErrorHandler(AWSErrorHandler):
35 _CUSTOM_EXCEPTION = AnsibleIAMError
36
37 @classmethod
38 def _is_missing(cls):
39 return is_boto3_error_code("NoSuchEntity")
40
41
42 @IAMErrorHandler.deletion_error_handler("detach group policy")
43 @AWSRetry.jittered_backoff()
44 def detach_iam_group_policy(client, arn, group):
45 client.detach_group_policy(PolicyArn=arn, GroupName=group)
46 return True
47
48
49 @IAMErrorHandler.deletion_error_handler("detach role policy")
50 @AWSRetry.jittered_backoff()
51 def detach_iam_role_policy(client, arn, role):
52 client.detach_role_policy(PolicyArn=arn, RoleName=role)
53 return True
54
55
56 @IAMErrorHandler.deletion_error_handler("detach user policy")
57 @AWSRetry.jittered_backoff()
58 def detach_iam_user_policy(client, arn, user):
59 client.detach_user_policy(PolicyArn=arn, UserName=user)
60 return True
61
62
63 @AWSRetry.jittered_backoff()
64 def _get_iam_instance_profiles(client, **kwargs):
65 return client.get_instance_profile(**kwargs)["InstanceProfile"]
66
67
68 @AWSRetry.jittered_backoff()
69 def _list_iam_instance_profiles(client, **kwargs):
70 paginator = client.get_paginator("list_instance_profiles")
71 return paginator.paginate(**kwargs).build_full_result()["InstanceProfiles"]
72
73
74 @AWSRetry.jittered_backoff()
75 def _list_iam_instance_profiles_for_role(client, **kwargs):
76 paginator = client.get_paginator("list_instance_profiles_for_role")
77 return paginator.paginate(**kwargs).build_full_result()["InstanceProfiles"]
78
79
80 @IAMErrorHandler.list_error_handler("list policies for role", [])
81 @AWSRetry.jittered_backoff()
82 def list_iam_role_policies(client, role_name):
83 paginator = client.get_paginator("list_role_policies")
84 return paginator.paginate(RoleName=role_name).build_full_result()["PolicyNames"]
85
86
87 @IAMErrorHandler.list_error_handler("list policies attached to role", [])
88 @AWSRetry.jittered_backoff()
89 def list_iam_role_attached_policies(client, role_name):
90 paginator = client.get_paginator("list_attached_role_policies")
91 return paginator.paginate(RoleName=role_name).build_full_result()["AttachedPolicies"]
92
93
94 @IAMErrorHandler.list_error_handler("list users", [])
95 @AWSRetry.jittered_backoff()
96 def list_iam_users(client, path=None):
97 args = {}
98 if path is not None:
99 args = {"PathPrefix": path}
100 paginator = client.get_paginator("list_users")
101 return paginator.paginate(**args).build_full_result()["Users"]
102
103
104 @IAMErrorHandler.common_error_handler("list all managed policies")
105 @AWSRetry.jittered_backoff()
106 def list_iam_managed_policies(client, **kwargs):
107 paginator = client.get_paginator("list_policies")
108 return paginator.paginate(**kwargs).build_full_result()["Policies"]
109
110
111 list_managed_policies = list_iam_managed_policies
112
113
114 @IAMErrorHandler.list_error_handler("list entities for policy", [])
115 @AWSRetry.jittered_backoff()
116 def list_iam_entities_for_policy(client, arn):
117 paginator = client.get_paginator("list_entities_for_policy")
118 return paginator.paginate(PolicyArn=arn).build_full_result()
119
120
121 @IAMErrorHandler.list_error_handler("list roles", [])
122 @AWSRetry.jittered_backoff()
123 def list_iam_roles(client, path=None):
124 args = {}
125 if path:
126 args["PathPrefix"] = path
127 paginator = client.get_paginator("list_roles")
128 return paginator.paginate(**args).build_full_result()["Roles"]
129
130
131 @IAMErrorHandler.list_error_handler("list mfa devices", [])
132 @AWSRetry.jittered_backoff()
133 def list_iam_mfa_devices(client, user=None):
134 args = {}
135 if user:
136 args["UserName"] = user
137 paginator = client.get_paginator("list_mfa_devices")
138 return paginator.paginate(**args).build_full_result()["MFADevices"]
139
140
141 @IAMErrorHandler.list_error_handler("get role")
142 @AWSRetry.jittered_backoff()
143 def get_iam_role(client, name):
144 return client.get_role(RoleName=name)["Role"]
145
146
147 @IAMErrorHandler.list_error_handler("get group")
148 @AWSRetry.jittered_backoff()
149 def get_iam_group(client, name):
150 paginator = client.get_paginator("get_group")
151 return paginator.paginate(GroupName=name).build_full_result()
152
153
154 @IAMErrorHandler.list_error_handler("get access keys for user", [])
155 @AWSRetry.jittered_backoff()
156 def get_iam_access_keys(client, user):
157 results = client.list_access_keys(UserName=user)
158 return normalize_iam_access_keys(results.get("AccessKeyMetadata", []))
159
160
161 @IAMErrorHandler.list_error_handler("get user")
162 @AWSRetry.jittered_backoff()
163 def get_iam_user(client, user, normalize=True):
164 results = client.get_user(UserName=user)
165 if normalize:
166 return normalize_iam_user(results.get("User", []))
167 return results.get("User", [])
168
169
170 @IAMErrorHandler.list_error_handler("get user tags")
171 @AWSRetry.jittered_backoff()
172 def list_iam_user_tags(client, user):
173 results = client.list_user_tags(UserName=user)
174 return results.get("Tags", [])
175
176
177 def find_iam_managed_policy_by_name(client, name):
178 policies = list_iam_managed_policies(client)
179 for policy in policies:
180 if policy["PolicyName"] == name:
181 return policy
182 return None
183
184
185 def get_iam_managed_policy_by_name(client, name):
186 # get_policy() requires an ARN, and list_policies() doesn't return all fields, so we need to do both :(
187 policy = find_iam_managed_policy_by_name(client, name)
188 if policy is None:
189 return None
190 return get_iam_managed_policy_by_arn(client, policy["Arn"])
191
192
193 @IAMErrorHandler.common_error_handler("get policy")
194 @AWSRetry.jittered_backoff()
195 def get_iam_managed_policy_by_arn(client, arn):
196 policy = client.get_policy(PolicyArn=arn)["Policy"]
197 return policy
198
199
200 @IAMErrorHandler.common_error_handler("list policy versions")
201 @AWSRetry.jittered_backoff()
202 def list_iam_managed_policy_versions(client, arn):
203 return client.list_policy_versions(PolicyArn=arn)["Versions"]
204
205
206 @IAMErrorHandler.common_error_handler("get policy version")
207 @AWSRetry.jittered_backoff()
208 def get_iam_managed_policy_version(client, arn, version):
209 return client.get_policy_version(PolicyArn=arn, VersionId=version)["PolicyVersion"]
210
211
212 def convert_managed_policy_names_to_arns(client, policy_names):
213 if all(validate_aws_arn(policy, service="iam") for policy in policy_names if policy is not None):
214 return policy_names
215 allpolicies = {}
216 policies = list_iam_managed_policies(client)
217
218 for policy in policies:
219 allpolicies[policy["PolicyName"]] = policy["Arn"]
220 allpolicies[policy["Arn"]] = policy["Arn"]
221 try:
222 return [allpolicies[policy] for policy in policy_names if policy is not None]
223 except KeyError as e:
224 raise AnsibleIAMError(message="Failed to find policy by name:" + str(e), exception=e) from e
225
226
227 def get_aws_account_id(module):
228 """Given an AnsibleAWSModule instance, get the active AWS account ID"""
229
230 return get_aws_account_info(module)[0]
231
232
233 def get_aws_account_info(module):
234 """Given an AnsibleAWSModule instance, return the account information
235 (account id and partition) we are currently working on
236
237 get_account_info tries too find out the account that we are working
238 on. It's not guaranteed that this will be easy so we try in
239 several different ways. Giving either IAM or STS privileges to
240 the account should be enough to permit this.
241
242 Tries:
243 - sts:GetCallerIdentity
244 - iam:GetUser
245 - sts:DecodeAuthorizationMessage
246 """
247 account_id = None
248 partition = None
249 try:
250 sts_client = module.client("sts", retry_decorator=AWSRetry.jittered_backoff())
251 caller_id = sts_client.get_caller_identity(aws_retry=True)
252 account_id = caller_id.get("Account")
253 partition = caller_id.get("Arn").split(":")[1]
254 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError):
255 try:
256 iam_client = module.client("iam", retry_decorator=AWSRetry.jittered_backoff())
257 _arn, partition, _service, _reg, account_id, _resource = iam_client.get_user(aws_retry=True)["User"][
258 "Arn"
259 ].split(":")
260 except is_boto3_error_code("AccessDenied") as e:
261 try:
262 except_msg = to_native(e.message)
263 except AttributeError:
264 except_msg = to_native(e)
265 result = parse_aws_arn(except_msg)
266 if result is None or result["service"] != "iam":
267 module.fail_json_aws(
268 e,
269 msg="Failed to get AWS account information, Try allowing sts:GetCallerIdentity or iam:GetUser permissions.",
270 )
271 account_id = result.get("account_id")
272 partition = result.get("partition")
273 except ( # pylint: disable=duplicate-except
274 botocore.exceptions.BotoCoreError,
275 botocore.exceptions.ClientError,
276 ) as e:
277 module.fail_json_aws(
278 e,
279 msg="Failed to get AWS account information, Try allowing sts:GetCallerIdentity or iam:GetUser permissions.",
280 )
281
282 if account_id is None or partition is None:
283 module.fail_json(
284 msg="Failed to get AWS account information, Try allowing sts:GetCallerIdentity or iam:GetUser permissions.",
285 )
286
287 return (to_native(account_id), to_native(partition))
288
289
290 @IAMErrorHandler.common_error_handler("create instance profile")
291 @AWSRetry.jittered_backoff()
292 def create_iam_instance_profile(client, name, path, tags):
293 boto3_tags = ansible_dict_to_boto3_tag_list(tags or {})
294 path = path or "/"
295 result = client.create_instance_profile(InstanceProfileName=name, Path=path, Tags=boto3_tags)
296 return result["InstanceProfile"]
297
298
299 @IAMErrorHandler.deletion_error_handler("delete instance profile")
300 @AWSRetry.jittered_backoff()
301 def delete_iam_instance_profile(client, name):
302 client.delete_instance_profile(InstanceProfileName=name)
303 # Error Handler will return False if the resource didn't exist
304 return True
305
306
307 @IAMErrorHandler.common_error_handler("add role to instance profile")
308 @AWSRetry.jittered_backoff()
309 def add_role_to_iam_instance_profile(client, profile_name, role_name):
310 client.add_role_to_instance_profile(InstanceProfileName=profile_name, RoleName=role_name)
311 return True
312
313
314 @IAMErrorHandler.deletion_error_handler("remove role from instance profile")
315 @AWSRetry.jittered_backoff()
316 def remove_role_from_iam_instance_profile(client, profile_name, role_name):
317 client.remove_role_from_instance_profile(InstanceProfileName=profile_name, RoleName=role_name)
318 # Error Handler will return False if the resource didn't exist
319 return True
320
321
322 @IAMErrorHandler.list_error_handler("list instance profiles", [])
323 def list_iam_instance_profiles(client, name=None, prefix=None, role=None):
324 """
325 Returns a list of IAM instance profiles in boto3 format.
326 Profiles need to be converted to Ansible format using normalize_iam_instance_profile before being displayed.
327
328 See also: normalize_iam_instance_profile
329 """
330 if role:
331 return _list_iam_instance_profiles_for_role(client, RoleName=role)
332 if name:
333 # Unlike the others this returns a single result, make this a list with 1 element.
334 return [_get_iam_instance_profiles(client, InstanceProfileName=name)]
335 if prefix:
336 return _list_iam_instance_profiles(client, PathPrefix=prefix)
337 return _list_iam_instance_profiles(client)
338
339
340 @IAMErrorHandler.common_error_handler("tag instance profile")
341 @AWSRetry.jittered_backoff()
342 def tag_iam_instance_profile(client, name, tags):
343 if not tags:
344 return
345 boto3_tags = ansible_dict_to_boto3_tag_list(tags or {})
346 client.tag_instance_profile(InstanceProfileName=name, Tags=boto3_tags)
347
348
349 @IAMErrorHandler.common_error_handler("untag instance profile")
350 @AWSRetry.jittered_backoff()
351 def untag_iam_instance_profile(client, name, tags):
352 if not tags:
353 return
354 client.untag_instance_profile(InstanceProfileName=name, TagKeys=tags)
355
356
357 @IAMErrorHandler.common_error_handler("tag managed policy")
358 @AWSRetry.jittered_backoff()
359 def tag_iam_policy(client, arn, tags):
360 if not tags:
361 return
362 boto3_tags = ansible_dict_to_boto3_tag_list(tags or {})
363 client.tag_policy(PolicyArn=arn, Tags=boto3_tags)
364
365
366 @IAMErrorHandler.common_error_handler("untag managed policy")
367 @AWSRetry.jittered_backoff()
368 def untag_iam_policy(client, arn, tags):
369 if not tags:
370 return
371 client.untag_policy(PolicyArn=arn, TagKeys=tags)
372
373
374 def _validate_iam_name(resource_type, name=None):
375 if name is None:
376 return None
377 LENGTHS = {"role": 64, "user": 64}
378 regex = r"[\w+=,.@-]+"
379 max_length = LENGTHS.get(resource_type, 128)
380 if len(name) > max_length:
381 return f"Length of {resource_type} name may not exceed {max_length}"
382 if not re.fullmatch(regex, name):
383 return f"{resource_type} name must match pattern {regex}"
384 return None
385
386
387 def _validate_iam_path(resource_type, path=None):
388 if path is None:
389 return None
390 regex = r"\/([\w+=,.@-]+\/)*"
391 max_length = 512
392 if len(path) > max_length:
393 return f"Length of {resource_type} path may not exceed {max_length}"
394 if not path.endswith("/") or not path.startswith("/"):
395 return f"{resource_type} path must begin and end with /"
396 if not re.fullmatch(regex, path):
397 return f"{resource_type} path must match pattern {regex}"
398 return None
399
400
401 def validate_iam_identifiers(resource_type, name=None, path=None):
402 name_problem = _validate_iam_name(resource_type, name)
403 if name_problem:
404 return name_problem
405 path_problem = _validate_iam_path(resource_type, path)
406 if path_problem:
407 return path_problem
408
409 return None
410
411
412 def normalize_iam_mfa_device(device: BotoResource) -> AnsibleAWSResource:
413 """Converts IAM MFA Device from the CamelCase boto3 format to the snake_case Ansible format"""
414 # MFA Devices don't support Tags (as of 1.34.52)
415 return boto3_resource_to_ansible_dict(device)
416
417
418 def normalize_iam_mfa_devices(devices: BotoResourceList) -> AnsibleAWSResourceList:
419 """Converts a list of IAM MFA Devices from the CamelCase boto3 format to the snake_case Ansible format"""
420 # MFA Devices don't support Tags (as of 1.34.52)
421 return boto3_resource_list_to_ansible_dict(devices)
422
423
424 def normalize_iam_user(user: BotoResource) -> AnsibleAWSResource:
425 """Converts IAM users from the CamelCase boto3 format to the snake_case Ansible format"""
426 return boto3_resource_to_ansible_dict(user)
427
428
429 def normalize_iam_policy(policy: BotoResource) -> AnsibleAWSResource:
430 """Converts IAM policies from the CamelCase boto3 format to the snake_case Ansible format"""
431 return boto3_resource_to_ansible_dict(policy)
432
433
434 def normalize_iam_group(group: BotoResource) -> AnsibleAWSResource:
435 """Converts IAM Groups from the CamelCase boto3 format to the snake_case Ansible format"""
436 # Groups don't support Tags (as of 1.34.52)
437 return boto3_resource_to_ansible_dict(group, force_tags=False)
438
439
440 def normalize_iam_access_key(access_key: BotoResource) -> AnsibleAWSResource:
441 """Converts IAM access keys from the CamelCase boto3 format to the snake_case Ansible format"""
442 # Access Keys don't support Tags (as of 1.34.52)
443 return boto3_resource_to_ansible_dict(access_key, force_tags=False)
444
445
446 def normalize_iam_access_keys(access_keys: BotoResourceList) -> AnsibleAWSResourceList:
447 """Converts a list of IAM access keys from the CamelCase boto3 format to the snake_case Ansible format"""
448 # Access Keys don't support Tags (as of 1.34.52)
449 if not access_keys:
450 return access_keys
451 access_keys = boto3_resource_list_to_ansible_dict(access_keys, force_tags=False)
452 return sorted(access_keys, key=lambda d: d.get("create_date", None))
453
454
455 def normalize_iam_instance_profile(profile: BotoResource) -> AnsibleAWSResource:
456 """
457 Converts a boto3 format IAM instance profile into "Ansible" format
458 """
459 transforms = {"Roles": _normalize_iam_roles}
460 transformed_profile = boto3_resource_to_ansible_dict(profile, nested_transforms=transforms)
461 return transformed_profile
462
463
464 def normalize_iam_role(role: BotoResource, _v7_compat: bool = False) -> AnsibleAWSResource:
465 """
466 Converts a boto3 format IAM instance role into "Ansible" format
467
468 _v7_compat is deprecated and will be removed in release after 2026-05-01 DO NOT USE.
469 """
470 transforms = {"InstanceProfiles": _normalize_iam_instance_profiles}
471 ignore_list = ["AssumeRolePolicyDocument"]
472 transformed_role = boto3_resource_to_ansible_dict(role, nested_transforms=transforms, ignore_list=ignore_list)
473 if _v7_compat and role.get("AssumeRolePolicyDocument"):
474 transformed_role["assume_role_policy_document_raw"] = role["AssumeRolePolicyDocument"]
475 return transformed_role
476
477
478 def _normalize_iam_instance_profiles(profiles: BotoResourceList) -> AnsibleAWSResourceList:
479 if not profiles:
480 return profiles
481 return [normalize_iam_instance_profile(p) for p in profiles]
482
483
484 def _normalize_iam_roles(roles: BotoResourceList) -> AnsibleAWSResourceList:
485 if not roles:
486 return roles
487 return [normalize_iam_role(r) for r in roles]