0
votes

I have multiple AWS accounts and I am trying to run script against all accounts from central account / instance profile.

I am having trouble assuming role / targeting the other accounts with role that has been created and allowed to an instance profile in python boto3 script.

I have tried 2 functions below but the script always runs against local account where instance resides. How should I tell the python script to run against target account ?

def access_sub_account(access_key, secret_key, account_id, role_arn):
    client = boto3.client('sts', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
    response = client.assume_role(RoleArn=arn:aws:iam::12345678910:role/Role, RoleSessionName='CTOpsLambdaAuditRole')

    return response['Credentials']['AccessKeyId'], \
              response['Credentials']['SecretAccessKey'], \
              response['Credentials']['SessionToken']

    arn_role='arn:aws:iam::12345678910:role/Role'
arn_session='Role'

def assume_role(arn, session_name):
    """aws sts assume-role --role-arn arn:aws:iam::00000000000000:role/example-role --role-session-name example-role"""

    client = boto3.client('sts')
    assume_account_id = client.get_caller_identity()["Account"]
    print("Current Account ID",assume_account_id)

    response = client.assume_role(RoleArn=arn, RoleSessionName=session_name)

    session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
                      aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                      aws_session_token=response['Credentials']['SessionToken'])

    client = session.client('sts')
    assume_account_id = client.get_caller_identity()["Account"]
    print('Account ID Assumed:',assume_account_id)

I can see the role is correct if I set this but script runs against local account where instance profile is

assume_role(arn_role, arn_session)
account_id = boto3.client('sts').get_caller_identity()['Account']

updated: when print the response it give the correct role and keys. script continues to use local profile from instance on local account, do I need to export the credentials to ~/.aws/credentials ?

Response is: {'Credentials': {'AccessKeyId': 'ABCDEGHJJJJJJJSSSSSS', 'SecretAccessKey': '123456789876543212344567898765653322', 'SessionToken': 'sessiontokenblahblah==', 'Expiration': datetime.datetime(2020, 1, 23, 16, 44, 32, tzinfo=tzlocal())}, 'AssumedRoleUser': {'AssumedRoleId': 'AccesskeyId:Role', 'Arn': 'arn:aws:sts::123456789:assumed-role/Role/Role'}, 'ResponseMetadata': {'RequestId': '3f8839b4-3df7-11ea-85e2-316d5eca0a34', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '3f8839b4-3df7-11ea-85e2-316d5eca0a34', 'content-type': 'text/xml', 'content-length': '1095', 'date': 'Thu, 23 Jan 2020 15:44:31 GMT'}, 'RetryAttempts': 0}}

I was able to get it to assume updating the .aws/config and credentials and adding to code below, issue now is run against both accounts

boto3.setup_default_session(profile_name='Role')
    session = boto3.session.Session()
    temp_credentials = session.get_credentials().get_frozen_credentials()
1
How to ignore the default profile associated with instance profile ? - DeclanG

1 Answers

0
votes

Specify the individual AWS account number along with access key and secret in the script, which will allow you connect to the account. I tried to execute boto3 scripts from Jenkins servers to multiple AWS accounts

  • Passed AWS account number, secret key and access key as environment variable so no need to define in the script. you can try either ways.