运行AWS Lambda以在其他区域中创建实例的AMI

时间:2016-08-24 10:37:06

标签: python-2.7 amazon-web-services amazon-ec2 aws-lambda ami

我正在使用AWS Lambda为我的EC2 prod实例每天创建AMI。我在孟买地区设置了所有的infra,但 AWS不支持孟买地区的Lambda功能

所以,我选择新加坡地区设立Lambda。我按照create-AMIcleanup-ami链接在保留期后创建和删除AMI,但是,只有在新加坡地区的代码中包含指定标记的实例时,才会有效。

我的问题是:如果我的Lambda在新加坡地区,我如何为孟买实例创建AMI?

2 个答案:

答案 0 :(得分:2)

您可以在初始化boto客户端时设置区域:
ec = boto3.client('ec2', region_name='ap-south-1')

答案 1 :(得分:0)

如果您希望将AMI从一个帐户共享复制到另一个帐户。解决方法如下:

# Copying image from src_account to dest_account
SRC_ACCOUNT_ID = '111111'
DEST_ACCOUNT_ID = '222222'
IMAGE_ID = '333333'
SRC_REGION = 'us-west-1'
DEST_REGION = 'us-east-1'

# Create CrossAccountole Role in src_account which will give permission to operations in the acount
sts = boto3.client('sts')
credentials = sts.assume_role(
    RoleArn='arn:aws:iam::'+SRC_ACCOUNT_ID +':role/CrossAccountRole',
    RoleSessionName="RoleSession1"
)['Credentials']
ec2 = boto3.resource('ec2', region_name=SRC_REGION,
    aws_access_key_id = credentials['AccessKeyId'],
    aws_secret_access_key = credentials['SecretAccessKey'],
    aws_session_token = credentials['SessionToken']
)

# Access the image that needs to be copied
image = ec2.Image(IMAGE_ID)

# Share the image with the destination account
image.modify_attribute(
    ImageId = image.id,
    Attribute = 'launchPermission',
    OperationType = 'add',
    LaunchPermission = {
        'Add' : [{ 'UserId': DEST_ACCOUNT_ID }]
    }
)

# We have to now share the snapshots associated with the AMI so it can be copied
devices = image.block_device_mappings
for device in devices:
    if 'Ebs' in device:
        snapshot_id = device["Ebs"]["SnapshotId"]
        snapshot = ec2.Snapshot(snapshot_id)
        snapshot.modify_attribute(
            Attribute = 'createVolumePermission',
            CreateVolumePermission = {
                'Add' : [{ 'UserId': DEST_ACCOUNT_ID }]
            },
            OperationType = 'add',
        )

# Access destination account so we can now copy the image
credentials = sts.assume_role(
    RoleArn='arn:aws:iam::'+DEST_ACCOUNT_ID+':role/CrossAccountRole',
    RoleSessionName="RoleSession1"
)['Credentials']

# Copy image to failover regions
ec2fra = boto3.client('ec2', DEST_REGION,
    aws_access_key_id = credentials['AccessKeyId'],
    aws_secret_access_key = credentials['SecretAccessKey'],
    aws_session_token = credentials['SessionToken']
)

# Copy the shared AMI to dest region
ec2fra.copy_image(
    Name = 'MY_COPIED_IMAGE_FROM_OTHER_ACCOUNT',
    SourceImageId = image.id,
    SourceRegion = SRC_REGION
)

就这么简单:)

了解命令here