Skip to content

Commit

Permalink
Assume role cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
tremble committed Nov 16, 2022
1 parent a38d6aa commit b932b4a
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 27 deletions.
29 changes: 29 additions & 0 deletions plugins/doc_fragments/assume_role.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Ansible, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)


class ModuleDocFragment:
# Note: If you're updating MODULES, PLUGINS probably needs updating too.

# Formatted for Modules
# - modules don't support 'env'
MODULES = r"""
options:
assume_role_arn:
description:
- The ARN of the IAM role to assume to perform the inventory lookup.
- You should still provide AWS credentials with enough privilege to perform the AssumeRole action.
aliases: ["iam_role_arn"]
"""

# Formatted for non-module plugins
# - modules don't support 'env'
PLUGINS = r"""
options:
assume_role_arn:
description:
- The ARN of the IAM role to assume to perform the inventory lookup.
- You should still provide AWS credentials with enough privilege to perform the AssumeRole action.
aliases: ["iam_role_arn"]
"""
28 changes: 11 additions & 17 deletions plugins/inventory/aws_ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- constructed
- amazon.aws.common.plugins
- amazon.aws.region.plugins
- amazon.aws.assume_role.plugins
description:
- Get inventory hosts from Amazon Web Services EC2.
- Uses a YAML configuration file that ends with C(aws_ec2.{yml|yaml}).
Expand All @@ -18,14 +19,6 @@
author:
- Sloane Hertel (@s-hertel)
options:
plugin:
description: Token that ensures this is a source file for the plugin.
required: True
choices: ['aws_ec2', 'amazon.aws.aws_ec2']
iam_role_arn:
description:
- The ARN of the IAM role to assume to perform the inventory lookup. You should still provide AWS
credentials with enough privilege to perform the AssumeRole action.
regions:
description:
- A list of regions in which to describe EC2 instances.
Expand Down Expand Up @@ -267,10 +260,12 @@
pass # will be captured by imported HAS_BOTO3

from ansible.module_utils._text import to_text
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict


from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
from ansible_collections.amazon.aws.plugins.plugin_utils.inventory import AWSInventoryBase


Expand Down Expand Up @@ -501,12 +496,11 @@ def _get_instances_by_region(self, regions, filters, strict_permissions):
for instance in new_instances:
instance.update(reservation_details)
instances.extend(new_instances)
except botocore.exceptions.ClientError as e:
if e.response['ResponseMetadata']['HTTPStatusCode'] == 403 and not strict_permissions:
instances = []
else:
self.fail_aws("Failed to describe instances", exception=e)
except botocore.exceptions.BotoCoreError as e:
except is_boto3_error_code('UnauthorizedOperation') as e:
if not strict_permissions:
continue
self.fail_aws("Failed to describe instances", exception=e)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
self.fail_aws("Failed to describe instances", exception=e)

all_instances.extend(instances)
Expand Down
11 changes: 4 additions & 7 deletions plugins/inventory/aws_rds.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@
default:
- creating
- available
iam_role_arn:
description:
- The ARN of the IAM role to assume to perform the inventory lookup. You should still provide
AWS credentials with enough privilege to perform the AssumeRole action.
hostvars_prefix:
description:
- The prefix for host variables names coming from AWS.
Expand All @@ -57,6 +53,7 @@
- constructed
- amazon.aws.common.plugins
- amazon.aws.region.plugins
- amazon.aws.assume_role.plugins
author:
- Sloane Hertel (@s-hertel)
'''
Expand Down Expand Up @@ -141,11 +138,11 @@ def describe_wrapper(connection, filters, strict=False):
_add_tags_for_rds_hosts(connection, results, strict)
except is_boto3_error_code('AccessDenied') as e: # pylint: disable=duplicate-except
if not strict:
results = []
else:
raise AnsibleError("Failed to query RDS: {0}".format(to_native(e)))
return []
raise AnsibleError("Failed to query RDS: {0}".format(to_native(e)))
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except
raise AnsibleError("Failed to query RDS: {0}".format(to_native(e)))

return results

return describe_wrapper
Expand Down
7 changes: 4 additions & 3 deletions plugins/plugin_utils/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,11 @@ def _freeze_iam_role(self, iam_role_arn):
role_session_name = f"ansible_aws_{self.ansible_name}_dynamic_inventory"
else:
role_session_name = "ansible_aws_dynamic_inventory"
assume_params = {"RoleArn": iam_role_arn, "RoleSessionName": role_session_name}

try:
sts = self.client("sts")
assumed_role = sts.assume_role(RoleArn=iam_role_arn, RoleSessionName=role_session_name)
assumed_role = sts.assume_role(**assume_params)
except AnsibleBotocoreError as e:
self.fail_aws(f"Unable to assume role {iam_role_arn}", exception=e)

Expand All @@ -106,7 +107,7 @@ def _freeze_iam_role(self, iam_role_arn):

def _set_frozen_credentials(self):
options = self.get_options()
iam_role_arn = options.get("iam_role_arn")
iam_role_arn = options.get("assume_role_arn")
if iam_role_arn:
self._freeze_iam_role(iam_role_arn)

Expand Down Expand Up @@ -139,7 +140,7 @@ def _boto3_regions(self, service):
# boto3 has hard coded lists of available regions for resources, however this does bit-rot
# As such we try to query the service, and fall back to ec2 for a list of regions
for resource_type in list({service, "ec2"}):
regions = self.describe_regions(resource_type)
regions = self._describe_regions(resource_type)
if regions:
return regions

Expand Down

0 comments on commit b932b4a

Please sign in to comment.