Today I learned how to copy aws EC2 amis between regions usin aws CLI.
aws ec2 copy-image --name "{}" --source-image-id "{}" --source-region "{}" --region "{}"
--name
is for the name of the ami in the new region, and --region
is for the destination region.
I used it to migrate a bunch of amis from a region to another
from subprocess import Popen, PIPE
import json
import mysql.connector
def kebab(name):
return name.lower().replace('_', '-').replace(' ', '-')
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="database"
)
c = mydb.cursor()
c2 = mydb.cursor()
c.execute("SELECT * FROM aws_images")
results = c.fetchall()
for i, result in enumerate(results):
name = kebab(result[2]) if result[2] else "unnamed-{}".format(i)
ami = result[8]
try:
cmd = 'aws ec2 copy-image --name "{}" --source-image-id "{}" --source-region "us-east-2" --region "eu-west-1"'.format(name, ami)
stream = json.loads(Popen(cmd, shell=True, stdout=PIPE).stdout.read())
new_img = stream['ImageId']
cmd = 'UPDATE aws_images SET ami_id="{}" WHERE id={}'.format(new_img, result[0])
c2.execute(cmd)
print("changed {} with {}\n{}".format(ami, new_img,'-'*15))
except Exception as e:
print(e)
continue
mydb.commit()