| 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: iam_role |
| 10 |
version_added: 1.0.0 |
| 11 |
version_added_collection: community.aws |
| 12 |
short_description: Manage AWS IAM roles |
| 13 |
description: |
| 14 |
- Manage AWS IAM roles. |
| 15 |
author: |
| 16 |
- "Rob White (@wimnat)" |
| 17 |
options: |
| 18 |
path: |
| 19 |
description: |
| 20 |
- The path of the role. |
| 21 |
- For more information about IAM paths, see the AWS IAM identifiers documentation |
| 22 |
U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html). |
| 23 |
- Updating the path on an existing role is not currently supported and will result in a |
| 24 |
warning. |
| 25 |
- O(path_prefix) and O(prefix) were added as aliases in release 7.2.0. |
| 26 |
type: str |
| 27 |
aliases: ["prefix", "path_prefix"] |
| 28 |
name: |
| 29 |
description: |
| 30 |
- The name of the role. |
| 31 |
- >- |
| 32 |
Note: Role names are unique within an account. Paths (O(path)) do B(not) affect |
| 33 |
the uniqueness requirements of O(name). For example it is not permitted to have both |
| 34 |
C(/Path1/MyRole) and C(/Path2/MyRole) in the same account. |
| 35 |
- O(role_name) was added as an alias in release 7.2.0. |
| 36 |
required: true |
| 37 |
type: str |
| 38 |
aliases: ["role_name"] |
| 39 |
description: |
| 40 |
description: |
| 41 |
- Provides a description of the role. |
| 42 |
type: str |
| 43 |
boundary: |
| 44 |
description: |
| 45 |
- The ARN of an IAM managed policy to use to restrict the permissions this role can pass on to IAM roles/users that it creates. |
| 46 |
- Boundaries cannot be set on Instance Profiles, as such if this option is specified then O(create_instance_profile) must be V(false). |
| 47 |
- This is intended for roles/users that have permissions to create new IAM objects. |
| 48 |
- For more information on boundaries, see U(https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html). |
| 49 |
aliases: [boundary_policy_arn] |
| 50 |
type: str |
| 51 |
assume_role_policy_document: |
| 52 |
description: |
| 53 |
- The trust relationship policy document that grants an entity permission to assume the role. |
| 54 |
- This parameter is required when O(state=present). |
| 55 |
type: json |
| 56 |
managed_policies: |
| 57 |
description: |
| 58 |
- A list of managed policy ARNs, or friendly names. |
| 59 |
- To remove all policies set O(purge_policies=true) and O(managed_policies=[]). |
| 60 |
- To embed an inline policy, use M(amazon.aws.iam_policy). |
| 61 |
aliases: ['managed_policy'] |
| 62 |
type: list |
| 63 |
elements: str |
| 64 |
max_session_duration: |
| 65 |
description: |
| 66 |
- The maximum duration (in seconds) of a session when assuming the role. |
| 67 |
- Valid values are between 1 and 12 hours (3600 and 43200 seconds). |
| 68 |
type: int |
| 69 |
purge_policies: |
| 70 |
description: |
| 71 |
- When O(purge_policies=true) any managed policies not listed in O(managed_policies) will be detatched. |
| 72 |
type: bool |
| 73 |
aliases: ['purge_policy', 'purge_managed_policies'] |
| 74 |
default: true |
| 75 |
state: |
| 76 |
description: |
| 77 |
- Create or remove the IAM role. |
| 78 |
default: present |
| 79 |
choices: [ present, absent ] |
| 80 |
type: str |
| 81 |
create_instance_profile: |
| 82 |
description: |
| 83 |
- If no IAM instance profile with the same O(name) exists, setting O(create_instance_profile=True) |
| 84 |
will create an IAM instance profile along with the role. |
| 85 |
- This option has been deprecated and will be removed in a release after 2026-05-01. The |
| 86 |
M(amazon.aws.iam_instance_profile) module can be used to manage instance profiles. |
| 87 |
- Defaults to V(True) |
| 88 |
type: bool |
| 89 |
delete_instance_profile: |
| 90 |
description: |
| 91 |
- When O(delete_instance_profile=true) and O(state=absent) deleting a role will also delete an |
| 92 |
instance profile with the same O(name) as the role, but only if the instance profile is |
| 93 |
associated with the role. |
| 94 |
- Only applies when O(state=absent). |
| 95 |
- This option has been deprecated and will be removed in a release after 2026-05-01. The |
| 96 |
M(amazon.aws.iam_instance_profile) module can be used to manage instance profiles. |
| 97 |
- Defaults to V(False) |
| 98 |
type: bool |
| 99 |
wait_timeout: |
| 100 |
description: |
| 101 |
- How long (in seconds) to wait for creation / update to complete. |
| 102 |
default: 120 |
| 103 |
type: int |
| 104 |
wait: |
| 105 |
description: |
| 106 |
- When O(wait=True) the module will wait for up to O(wait_timeout) seconds |
| 107 |
for IAM role creation before returning. |
| 108 |
default: True |
| 109 |
type: bool |
| 110 |
extends_documentation_fragment: |
| 111 |
- amazon.aws.common.modules |
| 112 |
- amazon.aws.region.modules |
| 113 |
- amazon.aws.tags |
| 114 |
- amazon.aws.boto3 |
| 115 |
""" |
| 116 |
|
| 117 |
EXAMPLES = r""" |
| 118 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 119 |
|
| 120 |
- name: Create a role with description and tags |
| 121 |
amazon.aws.iam_role: |
| 122 |
name: mynewrole |
| 123 |
assume_role_policy_document: "{{ lookup('file','policy.json') }}" |
| 124 |
description: This is My New Role |
| 125 |
tags: |
| 126 |
env: dev |
| 127 |
|
| 128 |
- name: "Create a role and attach a managed policy called 'PowerUserAccess'" |
| 129 |
amazon.aws.iam_role: |
| 130 |
name: mynewrole |
| 131 |
assume_role_policy_document: "{{ lookup('file','policy.json') }}" |
| 132 |
managed_policies: |
| 133 |
- arn:aws:iam::aws:policy/PowerUserAccess |
| 134 |
|
| 135 |
- name: Keep the role created above but remove all managed policies |
| 136 |
amazon.aws.iam_role: |
| 137 |
name: mynewrole |
| 138 |
assume_role_policy_document: "{{ lookup('file','policy.json') }}" |
| 139 |
managed_policies: [] |
| 140 |
|
| 141 |
- name: Delete the role |
| 142 |
amazon.aws.iam_role: |
| 143 |
name: mynewrole |
| 144 |
assume_role_policy_document: "{{ lookup('file', 'policy.json') }}" |
| 145 |
state: absent |
| 146 |
""" |
| 147 |
|
| 148 |
RETURN = r""" |
| 149 |
iam_role: |
| 150 |
description: Dictionary containing the IAM Role data. |
| 151 |
returned: success |
| 152 |
type: complex |
| 153 |
contains: |
| 154 |
path: |
| 155 |
description: The path to the role. |
| 156 |
type: str |
| 157 |
returned: always |
| 158 |
sample: / |
| 159 |
role_name: |
| 160 |
description: The friendly name that identifies the role. |
| 161 |
type: str |
| 162 |
returned: always |
| 163 |
sample: myrole |
| 164 |
role_id: |
| 165 |
description: The stable and unique string identifying the role. |
| 166 |
type: str |
| 167 |
returned: always |
| 168 |
sample: ABCDEFF4EZ4ABCDEFV4ZC |
| 169 |
arn: |
| 170 |
description: The Amazon Resource Name (ARN) specifying the role. |
| 171 |
type: str |
| 172 |
returned: always |
| 173 |
sample: "arn:aws:iam::1234567890:role/mynewrole" |
| 174 |
create_date: |
| 175 |
description: The date and time, in ISO 8601 date-time format, when the role was created. |
| 176 |
type: str |
| 177 |
returned: always |
| 178 |
sample: "2016-08-14T04:36:28+00:00" |
| 179 |
assume_role_policy_document: |
| 180 |
description: |
| 181 |
- The policy that grants an entity permission to assume the role. |
| 182 |
- | |
| 183 |
Note: the case of keys in this dictionary are no longer converted from CamelCase to |
| 184 |
snake_case. This behaviour changed in release 8.0.0. |
| 185 |
type: dict |
| 186 |
returned: always |
| 187 |
sample: { |
| 188 |
'statement': [ |
| 189 |
{ |
| 190 |
'action': 'sts:AssumeRole', |
| 191 |
'effect': 'Allow', |
| 192 |
'principal': { |
| 193 |
'service': 'ec2.amazonaws.com' |
| 194 |
}, |
| 195 |
'sid': '' |
| 196 |
} |
| 197 |
], |
| 198 |
'version': '2012-10-17' |
| 199 |
} |
| 200 |
assume_role_policy_document_raw: |
| 201 |
description: |
| 202 |
- | |
| 203 |
Note: this return value has been deprecated and will be removed in a release after |
| 204 |
2026-05-01. RV(iam_role.assume_role_policy_document) and RV(iam_role.assume_role_policy_document_raw) |
| 205 |
now use the same format. |
| 206 |
type: dict |
| 207 |
returned: always |
| 208 |
sample: { |
| 209 |
'statement': [ |
| 210 |
{ |
| 211 |
'action': 'sts:AssumeRole', |
| 212 |
'effect': 'Allow', |
| 213 |
'principal': { |
| 214 |
'service': 'ec2.amazonaws.com' |
| 215 |
}, |
| 216 |
'sid': '' |
| 217 |
} |
| 218 |
], |
| 219 |
'version': '2012-10-17' |
| 220 |
} |
| 221 |
version_added: 5.3.0 |
| 222 |
attached_policies: |
| 223 |
description: A list of dicts containing the name and ARN of the managed IAM policies attached to the role. |
| 224 |
type: list |
| 225 |
elements: dict |
| 226 |
returned: always |
| 227 |
sample: [ |
| 228 |
{ |
| 229 |
'policy_arn': 'arn:aws:iam::aws:policy/PowerUserAccess', |
| 230 |
'policy_name': 'PowerUserAccess' |
| 231 |
} |
| 232 |
] |
| 233 |
contains: |
| 234 |
policy_arn: |
| 235 |
description: The Amazon Resource Name (ARN) specifying the managed policy. |
| 236 |
type: str |
| 237 |
sample: "arn:aws:iam::123456789012:policy/test_policy" |
| 238 |
policy_name: |
| 239 |
description: The friendly name that identifies the policy. |
| 240 |
type: str |
| 241 |
sample: test_policy |
| 242 |
description: |
| 243 |
description: A description of the role. |
| 244 |
type: str |
| 245 |
returned: always |
| 246 |
sample: "This is My New Role" |
| 247 |
max_session_duration: |
| 248 |
description: The maximum duration (in seconds) of a session when assuming the role. |
| 249 |
type: int |
| 250 |
returned: always |
| 251 |
sample: 3600 |
| 252 |
role_last_used: |
| 253 |
description: Contains information about the last time that an IAM role was used. |
| 254 |
type: dict |
| 255 |
returned: always |
| 256 |
sample: { |
| 257 |
"last_used_date": "2023-11-22T21:54:29+00:00", |
| 258 |
"region": "us-east-2" |
| 259 |
} |
| 260 |
contains: |
| 261 |
last_used_date: |
| 262 |
description: The date and time, in ISO 8601 date-time format that the role was last used. |
| 263 |
type: str |
| 264 |
returned: always |
| 265 |
region: |
| 266 |
description: The name of the Amazon Web Services Region in which the role was last used. |
| 267 |
type: str |
| 268 |
returned: always |
| 269 |
tags: |
| 270 |
description: role tags |
| 271 |
type: dict |
| 272 |
returned: always |
| 273 |
sample: '{"Env": "Prod"}' |
| 274 |
""" |
| 275 |
|
| 276 |
import json |
| 277 |
|
| 278 |
from ansible_collections.amazon.aws.plugins.module_utils.arn import validate_aws_arn |
| 279 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import AnsibleIAMError |
| 280 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import IAMErrorHandler |
| 281 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import add_role_to_iam_instance_profile |
| 282 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import convert_managed_policy_names_to_arns |
| 283 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import create_iam_instance_profile |
| 284 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import delete_iam_instance_profile |
| 285 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import get_iam_role |
| 286 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import list_iam_instance_profiles |
| 287 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import list_iam_role_attached_policies |
| 288 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import normalize_iam_role |
| 289 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import remove_role_from_iam_instance_profile |
| 290 |
from ansible_collections.amazon.aws.plugins.module_utils.iam import validate_iam_identifiers |
| 291 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 292 |
from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies |
| 293 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 294 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 295 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 296 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags |
| 297 |
|
| 298 |
|
| 299 |
class AnsibleIAMAlreadyExistsError(AnsibleIAMError): |
| 300 |
pass |
| 301 |
|
| 302 |
|
| 303 |
@IAMErrorHandler.common_error_handler("wait for role creation") |
| 304 |
def wait_iam_exists(client, check_mode, role_name, wait, wait_timeout): |
| 305 |
if check_mode or wait: |
| 306 |
return |
| 307 |
|
| 308 |
delay = min(wait_timeout, 5) |
| 309 |
max_attempts = wait_timeout // delay |
| 310 |
|
| 311 |
waiter = client.get_waiter("role_exists") |
| 312 |
waiter.wait( |
| 313 |
WaiterConfig={"Delay": delay, "MaxAttempts": max_attempts}, |
| 314 |
RoleName=role_name, |
| 315 |
) |
| 316 |
|
| 317 |
|
| 318 |
def attach_policies(client, check_mode, policies_to_attach, role_name): |
| 319 |
if not policies_to_attach: |
| 320 |
return False |
| 321 |
if check_mode: |
| 322 |
return True |
| 323 |
|
| 324 |
for policy_arn in policies_to_attach: |
| 325 |
IAMErrorHandler.common_error_handler(f"attach policy {policy_arn} to role")(client.attach_role_policy)( |
| 326 |
RoleName=role_name, PolicyArn=policy_arn, aws_retry=True |
| 327 |
) |
| 328 |
return True |
| 329 |
|
| 330 |
|
| 331 |
def remove_policies(client, check_mode, policies_to_remove, role_name): |
| 332 |
if not policies_to_remove: |
| 333 |
return False |
| 334 |
if check_mode: |
| 335 |
return True |
| 336 |
|
| 337 |
for policy in policies_to_remove: |
| 338 |
IAMErrorHandler.deletion_error_handler(f"detach policy {policy} from role")(client.detach_role_policy)( |
| 339 |
RoleName=role_name, PolicyArn=policy, aws_retry=True |
| 340 |
) |
| 341 |
return True |
| 342 |
|
| 343 |
|
| 344 |
def remove_inline_policies(client, role_name): |
| 345 |
current_inline_policies = get_inline_policy_list(client, role_name) |
| 346 |
for policy in current_inline_policies: |
| 347 |
IAMErrorHandler.deletion_error_handler(f"delete policy {policy} embedded in role")(client.delete_role_policy)( |
| 348 |
RoleName=role_name, PolicyName=policy, aws_retry=True |
| 349 |
) |
| 350 |
|
| 351 |
|
| 352 |
def generate_create_params(module): |
| 353 |
params = dict() |
| 354 |
params["Path"] = module.params.get("path") or "/" |
| 355 |
params["RoleName"] = module.params.get("name") |
| 356 |
params["AssumeRolePolicyDocument"] = module.params.get("assume_role_policy_document") |
| 357 |
if module.params.get("description") is not None: |
| 358 |
params["Description"] = module.params.get("description") |
| 359 |
if module.params.get("max_session_duration") is not None: |
| 360 |
params["MaxSessionDuration"] = module.params.get("max_session_duration") |
| 361 |
if module.params.get("boundary") is not None: |
| 362 |
params["PermissionsBoundary"] = module.params.get("boundary") |
| 363 |
if module.params.get("tags") is not None: |
| 364 |
params["Tags"] = ansible_dict_to_boto3_tag_list(module.params.get("tags")) |
| 365 |
|
| 366 |
return params |
| 367 |
|
| 368 |
|
| 369 |
@IAMErrorHandler.common_error_handler("create role") |
| 370 |
def create_basic_role(module, client): |
| 371 |
""" |
| 372 |
Perform the Role creation. |
| 373 |
Assumes tests for the role existing have already been performed. |
| 374 |
""" |
| 375 |
if module.check_mode: |
| 376 |
module.exit_json(changed=True) |
| 377 |
|
| 378 |
params = generate_create_params(module) |
| 379 |
role = client.create_role(aws_retry=True, **params) |
| 380 |
# 'Description' is documented as a key of the role returned by create_role |
| 381 |
# but appears to be an AWS bug (the value is not returned using the AWS CLI either). |
| 382 |
# Get the role after creating it. |
| 383 |
# nb. doesn't use get_iam_role because we need to retry if the Role isn't there |
| 384 |
role = _get_role_with_backoff(client, params["RoleName"]) |
| 385 |
|
| 386 |
return role |
| 387 |
|
| 388 |
|
| 389 |
@IAMErrorHandler.common_error_handler("update assume role policy for role") |
| 390 |
def update_role_assumed_policy(client, check_mode, role_name, target_assumed_policy, current_assumed_policy): |
| 391 |
# Check Assumed Policy document |
| 392 |
if target_assumed_policy is None or not compare_policies(current_assumed_policy, json.loads(target_assumed_policy)): |
| 393 |
return False |
| 394 |
if check_mode: |
| 395 |
return True |
| 396 |
|
| 397 |
client.update_assume_role_policy(RoleName=role_name, PolicyDocument=target_assumed_policy, aws_retry=True) |
| 398 |
return True |
| 399 |
|
| 400 |
|
| 401 |
@IAMErrorHandler.common_error_handler("update description for role") |
| 402 |
def update_role_description(client, check_mode, role_name, target_description, current_description): |
| 403 |
# Check Description update |
| 404 |
if target_description is None or current_description == target_description: |
| 405 |
return False |
| 406 |
if check_mode: |
| 407 |
return True |
| 408 |
|
| 409 |
client.update_role(RoleName=role_name, Description=target_description, aws_retry=True) |
| 410 |
return True |
| 411 |
|
| 412 |
|
| 413 |
@IAMErrorHandler.common_error_handler("update maximum session duration for role") |
| 414 |
def update_role_max_session_duration(client, check_mode, role_name, target_duration, current_duration): |
| 415 |
# Check MaxSessionDuration update |
| 416 |
if target_duration is None or current_duration == target_duration: |
| 417 |
return False |
| 418 |
if check_mode: |
| 419 |
return True |
| 420 |
|
| 421 |
client.update_role(RoleName=role_name, MaxSessionDuration=target_duration, aws_retry=True) |
| 422 |
return True |
| 423 |
|
| 424 |
|
| 425 |
@IAMErrorHandler.common_error_handler("update permission boundary for role") |
| 426 |
def _put_role_permissions_boundary(client, **params): |
| 427 |
client.put_role_permissions_boundary(aws_retry=True, **params) |
| 428 |
|
| 429 |
|
| 430 |
@IAMErrorHandler.deletion_error_handler("remove permission boundary from role") |
| 431 |
def _delete_role_permissions_boundary(client, **params): |
| 432 |
client.delete_role_permissions_boundary(**params) |
| 433 |
|
| 434 |
|
| 435 |
def update_role_permissions_boundary(client, check_mode, role_name, permissions_boundary, current_permissions_boundary): |
| 436 |
# Check PermissionsBoundary |
| 437 |
if permissions_boundary is None or permissions_boundary == current_permissions_boundary: |
| 438 |
return False |
| 439 |
if check_mode: |
| 440 |
return True |
| 441 |
|
| 442 |
if permissions_boundary == "": |
| 443 |
_delete_role_permissions_boundary(client, RoleName=role_name) |
| 444 |
else: |
| 445 |
_put_role_permissions_boundary(client, RoleName=role_name, PermissionsBoundary=permissions_boundary) |
| 446 |
return True |
| 447 |
|
| 448 |
|
| 449 |
def update_managed_policies(client, check_mode, role_name, managed_policies, purge_policies): |
| 450 |
# Check Managed Policies |
| 451 |
if managed_policies is None: |
| 452 |
return False |
| 453 |
|
| 454 |
# Get list of current attached managed policies |
| 455 |
current_attached_policies = list_iam_role_attached_policies(client, role_name) |
| 456 |
current_attached_policies_arn_list = [policy["PolicyArn"] for policy in current_attached_policies] |
| 457 |
|
| 458 |
if len(managed_policies) == 1 and managed_policies[0] is None: |
| 459 |
managed_policies = [] |
| 460 |
|
| 461 |
policies_to_remove = set(current_attached_policies_arn_list) - set(managed_policies) |
| 462 |
policies_to_remove = policies_to_remove if purge_policies else [] |
| 463 |
policies_to_attach = set(managed_policies) - set(current_attached_policies_arn_list) |
| 464 |
|
| 465 |
changed = False |
| 466 |
if purge_policies and policies_to_remove: |
| 467 |
if check_mode: |
| 468 |
return True |
| 469 |
else: |
| 470 |
changed |= remove_policies(client, check_mode, policies_to_remove, role_name) |
| 471 |
|
| 472 |
if policies_to_attach: |
| 473 |
if check_mode: |
| 474 |
return True |
| 475 |
else: |
| 476 |
changed |= attach_policies(client, check_mode, policies_to_attach, role_name) |
| 477 |
|
| 478 |
return changed |
| 479 |
|
| 480 |
|
| 481 |
def update_basic_role(module, client, role_name, role): |
| 482 |
check_mode = module.check_mode |
| 483 |
assumed_policy = module.params.get("assume_role_policy_document") |
| 484 |
description = module.params.get("description") |
| 485 |
duration = module.params.get("max_session_duration") |
| 486 |
path = module.params.get("path") |
| 487 |
permissions_boundary = module.params.get("boundary") |
| 488 |
purge_tags = module.params.get("purge_tags") |
| 489 |
tags = module.params.get("tags") |
| 490 |
|
| 491 |
# current attributes |
| 492 |
current_assumed_policy = role.get("AssumeRolePolicyDocument") |
| 493 |
current_description = role.get("Description") |
| 494 |
current_duration = role.get("MaxSessionDuration") |
| 495 |
current_permissions_boundary = role.get("PermissionsBoundary", {}).get("PermissionsBoundaryArn", "") |
| 496 |
current_tags = role.get("Tags", []) |
| 497 |
|
| 498 |
# As of botocore 1.34.3, the APIs don't support updating the Name or Path |
| 499 |
if update_role_path(client, check_mode, role, path): |
| 500 |
module.warn( |
| 501 |
f"iam_role doesn't support updating the path: current path '{role.get('Path')}', requested path '{path}'" |
| 502 |
) |
| 503 |
|
| 504 |
changed = False |
| 505 |
|
| 506 |
# Update attributes |
| 507 |
changed |= update_role_tags(client, check_mode, role_name, tags, purge_tags, current_tags) |
| 508 |
changed |= update_role_assumed_policy(client, check_mode, role_name, assumed_policy, current_assumed_policy) |
| 509 |
changed |= update_role_description(client, check_mode, role_name, description, current_description) |
| 510 |
changed |= update_role_max_session_duration(client, check_mode, role_name, duration, current_duration) |
| 511 |
changed |= update_role_permissions_boundary( |
| 512 |
client, check_mode, role_name, permissions_boundary, current_permissions_boundary |
| 513 |
) |
| 514 |
|
| 515 |
return changed |
| 516 |
|
| 517 |
|
| 518 |
def create_or_update_role(module, client, role_name, create_instance_profile): |
| 519 |
check_mode = module.check_mode |
| 520 |
wait = module.params.get("wait") |
| 521 |
wait_timeout = module.params.get("wait_timeout") |
| 522 |
path = module.params.get("path") |
| 523 |
purge_policies = module.params.get("purge_policies") |
| 524 |
managed_policies = module.params.get("managed_policies") |
| 525 |
if managed_policies: |
| 526 |
# Attempt to list the policies early so we don't leave things behind if we can't find them. |
| 527 |
managed_policies = convert_managed_policy_names_to_arns(client, managed_policies) |
| 528 |
|
| 529 |
changed = False |
| 530 |
|
| 531 |
# Get role |
| 532 |
role = get_iam_role(client, role_name) |
| 533 |
|
| 534 |
# If role is None, create it |
| 535 |
if role is None: |
| 536 |
role = create_basic_role(module, client) |
| 537 |
wait_iam_exists(client, check_mode, role_name, wait, wait_timeout) |
| 538 |
changed = True |
| 539 |
else: |
| 540 |
changed = update_basic_role(module, client, role_name, role) |
| 541 |
wait_iam_exists(client, check_mode, role_name, wait, wait_timeout) |
| 542 |
|
| 543 |
if create_instance_profile: |
| 544 |
try: |
| 545 |
changed |= create_instance_profiles(client, check_mode, role_name, path) |
| 546 |
wait_iam_exists(client, check_mode, role_name, wait, wait_timeout) |
| 547 |
except AnsibleIAMAlreadyExistsError: |
| 548 |
module.warn(f"profile {role_name} already exists and will not be updated") |
| 549 |
|
| 550 |
changed |= update_managed_policies(client, module.check_mode, role_name, managed_policies, purge_policies) |
| 551 |
wait_iam_exists(client, check_mode, role_name, wait, wait_timeout) |
| 552 |
|
| 553 |
# Get the role again |
| 554 |
role = get_iam_role(client, role_name) |
| 555 |
role["AttachedPolicies"] = list_iam_role_attached_policies(client, role_name) |
| 556 |
camel_role = normalize_iam_role(role, _v7_compat=True) |
| 557 |
|
| 558 |
module.exit_json(changed=changed, iam_role=camel_role) |
| 559 |
|
| 560 |
|
| 561 |
def create_instance_profiles(client, check_mode, role_name, path): |
| 562 |
# Fetch existing Profiles |
| 563 |
role_profiles = list_iam_instance_profiles(client, role=role_name) |
| 564 |
# Profile already exists |
| 565 |
if any(p["InstanceProfileName"] == role_name for p in role_profiles): |
| 566 |
return False |
| 567 |
|
| 568 |
named_profile = list_iam_instance_profiles(client, name=role_name) |
| 569 |
if named_profile: |
| 570 |
raise AnsibleIAMAlreadyExistsError(f"profile {role_name} already exists") |
| 571 |
|
| 572 |
if check_mode: |
| 573 |
return True |
| 574 |
|
| 575 |
path = path or "/" |
| 576 |
# Make sure an instance profile is created |
| 577 |
create_iam_instance_profile(client, role_name, path, {}) |
| 578 |
add_role_to_iam_instance_profile(client, role_name, role_name) |
| 579 |
|
| 580 |
return True |
| 581 |
|
| 582 |
|
| 583 |
def remove_instance_profiles(client, check_mode, role_name, delete_instance_profile): |
| 584 |
"""Removes the role from instance profiles and deletes the instance profile if |
| 585 |
delete_instance_profile is set |
| 586 |
""" |
| 587 |
|
| 588 |
instance_profiles = list_iam_instance_profiles(client, role=role_name) |
| 589 |
if not instance_profiles: |
| 590 |
return False |
| 591 |
if check_mode: |
| 592 |
return True |
| 593 |
|
| 594 |
# Remove the role from the instance profile(s) |
| 595 |
for profile in instance_profiles: |
| 596 |
profile_name = profile["InstanceProfileName"] |
| 597 |
remove_role_from_iam_instance_profile(client, profile_name, role_name) |
| 598 |
if not delete_instance_profile: |
| 599 |
continue |
| 600 |
# Delete the instance profile if the role and profile names match |
| 601 |
if profile_name == role_name: |
| 602 |
delete_iam_instance_profile(client, profile_name) |
| 603 |
|
| 604 |
|
| 605 |
@IAMErrorHandler.deletion_error_handler("delete role") |
| 606 |
def destroy_role(client, check_mode, role_name, delete_profiles): |
| 607 |
role = get_iam_role(client, role_name) |
| 608 |
|
| 609 |
if role is None: |
| 610 |
return False |
| 611 |
|
| 612 |
if check_mode: |
| 613 |
return True |
| 614 |
|
| 615 |
# Before we try to delete the role we need to remove any |
| 616 |
# - attached instance profiles |
| 617 |
# - attached managed policies |
| 618 |
# - embedded inline policies |
| 619 |
remove_instance_profiles(client, check_mode, role_name, delete_profiles) |
| 620 |
update_managed_policies(client, check_mode, role_name, [], True) |
| 621 |
remove_inline_policies(client, role_name) |
| 622 |
|
| 623 |
client.delete_role(aws_retry=True, RoleName=role_name) |
| 624 |
return True |
| 625 |
|
| 626 |
|
| 627 |
@IAMErrorHandler.common_error_handler("get role") |
| 628 |
@AWSRetry.jittered_backoff(catch_extra_error_codes=["NoSuchEntity"]) |
| 629 |
def _get_role_with_backoff(client, name): |
| 630 |
client.get_role(RoleName=name)["Role"] |
| 631 |
|
| 632 |
|
| 633 |
@IAMErrorHandler.list_error_handler("list attached inline policies for role") |
| 634 |
def get_inline_policy_list(client, name): |
| 635 |
return client.list_role_policies(RoleName=name, aws_retry=True)["PolicyNames"] |
| 636 |
|
| 637 |
|
| 638 |
def update_role_path(client, check_mode, role, path): |
| 639 |
if path is None: |
| 640 |
return False |
| 641 |
if path == role.get("Path"): |
| 642 |
return False |
| 643 |
if check_mode: |
| 644 |
return True |
| 645 |
|
| 646 |
# Not currently supported by the APIs |
| 647 |
pass |
| 648 |
return True |
| 649 |
|
| 650 |
|
| 651 |
@IAMErrorHandler.common_error_handler("set tags for role") |
| 652 |
def update_role_tags(client, check_mode, role_name, new_tags, purge_tags, existing_tags): |
| 653 |
if new_tags is None: |
| 654 |
return False |
| 655 |
existing_tags = boto3_tag_list_to_ansible_dict(existing_tags) |
| 656 |
|
| 657 |
tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, new_tags, purge_tags=purge_tags) |
| 658 |
if not tags_to_remove and not tags_to_add: |
| 659 |
return False |
| 660 |
if check_mode: |
| 661 |
return True |
| 662 |
|
| 663 |
if tags_to_remove: |
| 664 |
client.untag_role(RoleName=role_name, TagKeys=tags_to_remove, aws_retry=True) |
| 665 |
if tags_to_add: |
| 666 |
client.tag_role(RoleName=role_name, Tags=ansible_dict_to_boto3_tag_list(tags_to_add), aws_retry=True) |
| 667 |
|
| 668 |
return True |
| 669 |
|
| 670 |
|
| 671 |
def validate_params(module): |
| 672 |
if module.params.get("boundary"): |
| 673 |
# We need to handle both None and True |
| 674 |
if module.params.get("create_instance_profile") is not False: |
| 675 |
module.fail_json(msg="When using a boundary policy, `create_instance_profile` must be set to `false`.") |
| 676 |
if not validate_aws_arn(module.params.get("boundary"), service="iam"): |
| 677 |
module.fail_json(msg="Boundary policy must be an ARN") |
| 678 |
if module.params.get("max_session_duration"): |
| 679 |
max_session_duration = module.params.get("max_session_duration") |
| 680 |
if max_session_duration < 3600 or max_session_duration > 43200: |
| 681 |
module.fail_json(msg="max_session_duration must be between 1 and 12 hours (3600 and 43200 seconds)") |
| 682 |
|
| 683 |
identifier_problem = validate_iam_identifiers( |
| 684 |
"role", name=module.params.get("name"), path=module.params.get("path") |
| 685 |
) |
| 686 |
if identifier_problem: |
| 687 |
module.fail_json(msg=identifier_problem) |
| 688 |
|
| 689 |
|
| 690 |
def main(): |
| 691 |
argument_spec = dict( |
| 692 |
name=dict(type="str", aliases=["role_name"], required=True), |
| 693 |
path=dict(type="str", aliases=["path_prefix", "prefix"]), |
| 694 |
assume_role_policy_document=dict(type="json"), |
| 695 |
managed_policies=dict(type="list", aliases=["managed_policy"], elements="str"), |
| 696 |
max_session_duration=dict(type="int"), |
| 697 |
state=dict(type="str", choices=["present", "absent"], default="present"), |
| 698 |
description=dict(type="str"), |
| 699 |
boundary=dict(type="str", aliases=["boundary_policy_arn"]), |
| 700 |
create_instance_profile=dict(type="bool"), |
| 701 |
delete_instance_profile=dict(type="bool"), |
| 702 |
purge_policies=dict(default=True, type="bool", aliases=["purge_policy", "purge_managed_policies"]), |
| 703 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 704 |
purge_tags=dict(type="bool", default=True), |
| 705 |
wait=dict(type="bool", default=True), |
| 706 |
wait_timeout=dict(default=120, type="int"), |
| 707 |
) |
| 708 |
|
| 709 |
module = AnsibleAWSModule( |
| 710 |
argument_spec=argument_spec, |
| 711 |
required_if=[("state", "present", ["assume_role_policy_document"])], |
| 712 |
supports_check_mode=True, |
| 713 |
) |
| 714 |
|
| 715 |
module.deprecate( |
| 716 |
"In a release after 2026-05-01 iam_role.assume_role_policy_document_raw " |
| 717 |
"will no longer be returned. Since release 8.0.0 assume_role_policy_document " |
| 718 |
"has been returned with the same format as iam_role.assume_role_policy_document_raw", |
| 719 |
date="2026-05-01", |
| 720 |
collection_name="amazon.aws", |
| 721 |
) |
| 722 |
if module.params.get("create_instance_profile") is None: |
| 723 |
module.deprecate( |
| 724 |
"In a release after 2026-05-01 the 'create_instance_profile' option will be removed. " |
| 725 |
"The amazon.aws.iam_instance_profile module can be used to manage instance profiles instead.", |
| 726 |
date="2026-05-01", |
| 727 |
collection_name="amazon.aws", |
| 728 |
) |
| 729 |
if module.params.get("delete_instance_profile") is None: |
| 730 |
module.deprecate( |
| 731 |
"In a release after 2026-05-01 the 'delete_instance_profile' option will be removed. " |
| 732 |
"The amazon.aws.iam_instance_profile module can be used to manage and delete instance " |
| 733 |
"profiles instead.", |
| 734 |
date="2026-05-01", |
| 735 |
collection_name="amazon.aws", |
| 736 |
) |
| 737 |
|
| 738 |
validate_params(module) |
| 739 |
|
| 740 |
client = module.client("iam", retry_decorator=AWSRetry.jittered_backoff()) |
| 741 |
|
| 742 |
state = module.params.get("state") |
| 743 |
role_name = module.params.get("name") |
| 744 |
|
| 745 |
create_profile = module.params.get("create_instance_profile") |
| 746 |
create_profile = True if create_profile is None else create_profile |
| 747 |
delete_profile = module.params.get("delete_instance_profile") or False |
| 748 |
|
| 749 |
try: |
| 750 |
if state == "present": |
| 751 |
create_or_update_role(module, client, role_name, create_profile) |
| 752 |
elif state == "absent": |
| 753 |
changed = destroy_role(client, module.check_mode, role_name, delete_profile) |
| 754 |
module.exit_json(changed=changed) |
| 755 |
except AnsibleIAMError as e: |
| 756 |
module.fail_json_aws_error(e) |
| 757 |
|
| 758 |
|
| 759 |
if __name__ == "__main__": |
| 760 |
main() |