【问题标题】:Run AWS Lambda to create AMI of the instance in a different region运行 AWS Lambda 以在不同区域创建实例的 AMI
【发布时间】:2016-12-31 10:48:19
【问题描述】:

我每天使用 AWS Lambda 为我的 EC2 产品实例创建 AMI。我的所有基础设施都设置在孟买地区,但 AWS 尚不支持孟买地区的 Lambda 功能

所以,我选择了新加坡地区来设置 Lambda。我按照链接 create-AMIcleanup-ami 在保留期后创建和删除 AMI,但是,这仅适用于我在新加坡地区具有代码中指定标签的实例。

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

【问题讨论】:

  • 您遇到的具体问题是什么?请在您的问题中包含明确的问题陈述。您所要做的就是设置您希望 AWS 开发工具包代码使用的区域。

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


【解决方案1】:

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

【讨论】:

  • 我对 python boto 还是很陌生。这有效。谢谢
【解决方案2】:

如果您希望将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2017-11-11
    相关资源
    最近更新 更多