使用 boto3 将 AMI 复制到另一个区域
Copy AMI to another region using boto3
我正在尝试自动化我在 AWS EC2 控制台上拥有的 "Copy AMI" 功能,谁能告诉我一些通过 boto3 执行此操作的 Python 代码?
response = client.copy_image(
ClientToken='string',
Description='string',
Encrypted=True|False,
KmsKeyId='string',
Name='string',
SourceImageId='string',
SourceRegion='string',
DryRun=True|False
)
确保将请求发送到 目标区域 ,并传递对 SourceRegion
.
的引用
更准确地说。
假设您要复制的 AMI 位于 us-east-1(源区域)。
您的要求是将其复制到 us-west-2(目标区域)
将 boto3 EC2 客户端会话获取到 us-west-2 区域,然后在 SourceRegion 中传递 us-east-1。
import boto3
session1 = boto3.client('ec2',region_name='us-west-2')
response = session1.copy_image(
Name='DevEnv_Linux',
Description='Copied this AMI from region us-east-1',
SourceImageId='ami-02a6ufwod1f27e11',
SourceRegion='us-east-1'
)
我大部分时间都使用EC2.ServiceResource这样的高级资源,所以下面是我用来同时使用EC2资源和低级客户端的代码,
source_image_id = '....'
profile = '...'
source_region = 'us-west-1'
source_session = boto3.Session(profile_name=profile, region_name=source_region)
ec2 = source_session.resource('ec2')
ami = ec2.Image(source_image_id)
target_region = 'us-east-1'
target_session = boto3.Session(profile_name=profile, region_name=target_region)
target_ec2 = target_session.resource('ec2')
target_client = target_session.client('ec2')
response = target_client.copy_image(
Name=ami.name,
Description = ami.description,
SourceImageId = ami.id,
SorceRegion = source_region
)
target_ami = target_ec2.Image(response['ImageId'])
我正在尝试自动化我在 AWS EC2 控制台上拥有的 "Copy AMI" 功能,谁能告诉我一些通过 boto3 执行此操作的 Python 代码?
response = client.copy_image(
ClientToken='string',
Description='string',
Encrypted=True|False,
KmsKeyId='string',
Name='string',
SourceImageId='string',
SourceRegion='string',
DryRun=True|False
)
确保将请求发送到 目标区域 ,并传递对 SourceRegion
.
更准确地说。
假设您要复制的 AMI 位于 us-east-1(源区域)。 您的要求是将其复制到 us-west-2(目标区域)
将 boto3 EC2 客户端会话获取到 us-west-2 区域,然后在 SourceRegion 中传递 us-east-1。
import boto3
session1 = boto3.client('ec2',region_name='us-west-2')
response = session1.copy_image(
Name='DevEnv_Linux',
Description='Copied this AMI from region us-east-1',
SourceImageId='ami-02a6ufwod1f27e11',
SourceRegion='us-east-1'
)
我大部分时间都使用EC2.ServiceResource这样的高级资源,所以下面是我用来同时使用EC2资源和低级客户端的代码,
source_image_id = '....'
profile = '...'
source_region = 'us-west-1'
source_session = boto3.Session(profile_name=profile, region_name=source_region)
ec2 = source_session.resource('ec2')
ami = ec2.Image(source_image_id)
target_region = 'us-east-1'
target_session = boto3.Session(profile_name=profile, region_name=target_region)
target_ec2 = target_session.resource('ec2')
target_client = target_session.client('ec2')
response = target_client.copy_image(
Name=ami.name,
Description = ami.description,
SourceImageId = ami.id,
SorceRegion = source_region
)
target_ami = target_ec2.Image(response['ImageId'])