Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

inventory aws_ec2 - assume role using iam_role_arn parameter to describe regions #624

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
bugfixes:
- >-
aws_ec2 inventory - use the iam_role_arn configuration parameter to assume the role before trying to call DescribeRegions
if the regions configuration is not set and AWS credentials provided without enough privilege to perform the DescribeRegions action.
(https://github.com/ansible-collections/amazon.aws/issues/566).
16 changes: 15 additions & 1 deletion plugins/inventory/aws_ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@
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


# The mappings give an array of keys to get from the filter name to the value
Expand Down Expand Up @@ -423,7 +424,7 @@ def _get_connection(self, credentials, region='us-east-1'):
raise AnsibleError("Insufficient credentials found: %s" % to_native(e))
return connection

def _boto3_assume_role(self, credentials, region):
def _boto3_assume_role(self, credentials, region=None):
"""
Assume an IAM role passed by iam_role_arn parameter

Expand Down Expand Up @@ -462,6 +463,19 @@ def _boto3_conn(self, regions):
except botocore.exceptions.NoRegionError:
# above seems to fail depending on boto3 version, ignore and lets try something else
pass
except is_boto3_error_code('UnauthorizedOperation') as e: # pylint: disable=duplicate-except
if iam_role_arn is not None:
try:
# Describe regions assuming arn role
assumed_credentials = self._boto3_assume_role(credentials)
client = self._get_connection(assumed_credentials)
resp = client.describe_regions()
regions = [x['RegionName'] for x in resp.get('Regions', [])]
except botocore.exceptions.NoRegionError:
# above seems to fail depending on boto3 version, ignore and lets try something else
pass
else:
raise AnsibleError("Unauthorized operation: %s" % to_native(e))

# fallback to local list hardcoded in boto3 if still no regions
if not regions:
Expand Down