Instantly share code, notes, and snippets.

@geekmuse /index.py
Last active Aug 1, 2018

Embed
What would you like to do?
cross account lambda
# Steps to use:
# - For each account, create a cross-account role in the target account(s) -
# in this case I called my role "bsi_lambda_full". Make sure the target account
# roles grant sufficient IAM privs for the operations in the Lambda fxn.
# - The role that the Lambda account executes under in the master account only needs
# to grant "sts:AssumeRole" to the "lambda.amazonaws.com" AWS principal.
# - On each of the target account roles, specify the principal as the *ARN
# of the role* that the Lambda executes under in the master account.
# - Create an env var for the Lambda called "acct_nums", whose value is a
# pipe-delimited ("|") list of account numbers, e.g. 000000000000|111111111111|222222222222
# - Run it!
import os
import boto3
def lambda_handler(event, context):
print(boto3.__version__)
for acct_num in os.environ['acct_nums'].split("|"):
client = boto3.client('sts')
xa_req = client.assume_role(
RoleArn='arn:aws:iam::'+acct_num+':role/bsi_lambda_full',
RoleSessionName='bsi-lambda-'+acct_num
)
creds = xa_req['Credentials']
ec2 = boto3.resource(
'ec2',
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken'],
region_name='us-west-2'
)
for i in range(0, 10):
vol = ec2.create_volume(
Size=20,
AvailabilityZone='us-west-2b',
VolumeType='gp2',
Encrypted=False,
)
tags = ec2.create_tags(
Resources=[vol.id],
Tags=[
{
'Key': 'CreatedBy',
'Value': 'XALambda'
},
{
'Key': 'Iter',
'Value': str(i)
}
]
)
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment