Python 使用boto将AMI从一个AWS帐户复制到另一个AWS帐户

Python 使用boto将AMI从一个AWS帐户复制到另一个AWS帐户,python,python-2.7,amazon-web-services,boto,amazon-ami,Python,Python 2.7,Amazon Web Services,Boto,Amazon Ami,我做了一些RnD,但没有找到关于这个话题的任何答案或提示。如果可以使用boto将AMI从一个AWS帐户复制到另一个AWS帐户,任何人都可以给出提示或回答。您可以将AMI从一个帐户共享到另一个帐户。试试这个: 这就是你想要它做的吗 在这里 共享完图像后,也许你可以复制它。不可能复制AMI,但你可以像@byumark所说的那样共享它。与Bot3共享非常容易。我不会像他那样使用客户,我会使用 现在,如果处理加密的AMI,它有点棘手。您需要允许访问用于加密的CMK,共享快照本身而不是ami。然后复制快

我做了一些RnD,但没有找到关于这个话题的任何答案或提示。如果可以使用boto将AMI从一个AWS帐户复制到另一个AWS帐户,任何人都可以给出提示或回答。

您可以将AMI从一个帐户共享到另一个帐户。试试这个:

这就是你想要它做的吗

在这里


共享完图像后,也许你可以复制它。

不可能复制AMI,但你可以像@byumark所说的那样共享它。与Bot3共享非常容易。我不会像他那样使用客户,我会使用


现在,如果处理加密的AMI,它有点棘手。您需要允许访问用于加密的CMK,共享快照本身而不是ami。然后复制快照,并在复制时再次设置加密,以确保使用目标帐户默认KMS密钥对其进行加密。

您不能直接将AMI从一个帐户复制到另一个帐户,但可以与其他帐户共享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
)
就是这样,很简单:)


阅读有关命令的内容

谢谢兄弟,你真的节省了我的时间!