0

I have one lambda from which I am accessing one cross account by assume role

sts = boto3.client('sts')
sts.assume_role(RoleArn='A', RoleSessionName='aaa')

Now I did some operation after accessing this

Like I get some instance information .

  ec2 = boto3.client('ec2')
  desc = ec2.describe_instaces() #this all are  working fine

Now I want to back my lambda role(B) and store this data.

 sts2 = boto3.client('sts')
 sts2.assume_role(RoleArn='B', RoleSessionName='bbb')

and want to store desc those instance data into one s3 bucket of my current lambda account.

I tried these but it is not able to store the data...Is there any way I can able to force expire the assume role and get my current access role to store the data

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74

1 Answers1

2

When an IAM Role is assigned to an AWS Lambda function, a set of temporary credentials will be automatically provided to the function. The code within the function can then use these credentials simply by calling AWS services, eg:

ec2_client = boto3.client('ec2')

When you assume a role, a new set of credentials is returned.

response = sts.assume_role(RoleArn='A', RoleSessionName='aaa')

The response will then contain:

{
    'Credentials': {
        'AccessKeyId': 'string',
        'SecretAccessKey': 'string',
        'SessionToken': 'string',
        'Expiration': datetime(2015, 1, 1)
    },
    'AssumedRoleUser': {
        'AssumedRoleId': 'string',
        'Arn': 'string'
    },
    'PackedPolicySize': 123
}

If you wish to use those assumed credentials in a subsequent call to AWS, you will need to create a Session object and then use that Session to create a new Client:

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

assumed_client = session.client('ec2')
instances_response = assumed_client.describe_instances()    

Bottom line: Calling assume-role does not actually change your credentials. Rather, you need use the returned credentials to create a new client object. Therefore, there is no concept of "expiring" any credentials.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • great now if I want to put the data of instances in account of rolearn 'B" then I no need to do assume role of my account B am I right as account of rolearn B where my lambda iis running – Rajarshi Das Jun 23 '19 at 05:55
  • Yes. If your Lambda function is running in Account B, then there is no need to assume a role. The code will automatically use the role that was assigned to the Lambda function. – John Rotenstein Jun 23 '19 at 06:50