Skip to content

Instantly share code, notes, and snippets.

@brianredbeard
Created November 5, 2020 04:22
Show Gist options
  • Save brianredbeard/689ee4e8efc72c739b22ac525d756c50 to your computer and use it in GitHub Desktop.
Save brianredbeard/689ee4e8efc72c739b22ac525d756c50 to your computer and use it in GitHub Desktop.
CopyOCPAMI.py - A utility to copy a RHEL CoreOS AMI Image to a different region/account.
#!/usr/bin/env python
"""CopyOCPAMI.py - A utility to copy OpenShift Amazon Machine Images
Copyright (C) 2020 Brian 'redbeard' Harrington
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import sys
import uuid
import boto3
import requests
RHCOS_BUILDS = "https://raw.githubusercontent.com/openshift/installer/master/data/data/rhcos.json"
try:
DEST_REGION = sys.argv[1]
except IndexError:
print("ERROR: You must supply the destination ",
"region in which you wish to operate")
sys.exit(1)
CLIENT = boto3.client('ec2', region_name=DEST_REGION)
def get_ocp_info(region="us-east-1"):
"""Retrieve OpenShift metadata from GitHub
Args:
region (str, optional): Region of the AMI ID to return. Defaults to "us-east-1".
Returns:
ami: AMI ID
"""
builds = requests.get(RHCOS_BUILDS).json()
return builds["amis"][region]
def copy_ami(ami, sregion="us-east-1"):
"""Copy an AMI to a different region
Args:
ami (str): Amazon Machine Image (AMI) Id that you wish to copy
sregion (str, optional): Source Region. Defaults to "us-east-1".
"""
# Get metadata on the AMI hosted in sregion
image = boto3.resource('ec2', region_name=sregion).Image(ami)
# Generate a token to ensure the operation is idempotent
client_token = str(uuid.uuid4())
# Use copy_image - https://boto3.amazonaws.com/
# https://bit.ly/3jZy4JN
print("Copying image {} from region {}".format(ami, sregion))
response = ""
try:
response = CLIENT.copy_image(
ClientToken=client_token,
Name=image.name,
SourceImageId=ami,
SourceRegion=sregion
)
except Exception as err:
print("ERROR: Unable to copy image - {}".format(err))
print("Image copy executed")
print("New AMI: {}\nRequestId: {}".format(
response["ImageId"], response["ResponseMetadata"]["RequestId"]
))
def main():
"""Copy an AMI ID across Amazon accounts/regions
"""
ami_id = get_ocp_info()["hvm"]
copy_ami(ami=ami_id)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment