Yaroslav Bulatov
Yaroslav Bulatov

Reputation: 57973

Copy AMI to another region using boto3

I'm trying to automate "Copy AMI" functionality I have on my AWS EC2 console, can anyone point me to some Python code that does this through boto3?

Upvotes: 4

Views: 4321

Answers (3)

barryku
barryku

Reputation: 2584

I use high-level resources like EC2.ServiceResource most of time, so the following is the code I use to use both EC2 resource and low-level client,

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'])

Upvotes: 2

RaghuCK
RaghuCK

Reputation: 125

To be more precise.

Let's say the AMI you want to copy is in us-east-1 (Source region). Your requirement is to copy this into us-west-2 (Destination region)

Get the boto3 EC2 client session to us-west-2 region and then pass the us-east-1 in the SourceRegion.

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'
)

Upvotes: 7

John Rotenstein
John Rotenstein

Reputation: 270224

From EC2 — Boto 3 documentation:

response = client.copy_image(
    ClientToken='string',
    Description='string',
    Encrypted=True|False,
    KmsKeyId='string',
    Name='string',
    SourceImageId='string',
    SourceRegion='string',
    DryRun=True|False
)

Make sure you send the request to the destination region, passing in a reference to the SourceRegion.

Upvotes: 6

Related Questions