|
#!/usr/bin/env python |
|
|
|
import boto3 |
|
import os |
|
import json |
|
|
|
script_dir = os.path.dirname(os.path.realpath(__file__)) |
|
|
|
owner_account = 'xxxxxxxxxxx' |
|
|
|
accounts = [ |
|
{'account_number': '111111111111', 'account_name': 'account1'}, |
|
{'account_number': '222222222222', 'account_name': 'account2'}, |
|
{'account_number': '333333333333', 'account_name': 'account3'}, |
|
{'account_number': '444444444444', 'account_name': 'account4'}, |
|
{'account_number': '555555555555', 'account_name': 'account5'} |
|
|
|
] |
|
|
|
# Read the manifest with the latest image created |
|
with open("{}/../packer/manifest.json".format(script_dir)) as f: |
|
data = json.load(f) |
|
# Get the latest packer uuid |
|
last_uuid = data['last_run_uuid'] |
|
# Get the information from last builds |
|
latest_builds = [x for x in data['builds'] if x['packer_run_uuid'] == last_uuid] |
|
|
|
# For each build, get tags and copy them over |
|
for build in latest_builds: |
|
region = build['artifact_id'].split(':')[0] |
|
ami_id = build['artifact_id'].split(':')[1] |
|
# Get access to the owner account, to get the tags just created |
|
client = boto3.client('sts') |
|
response = client.assume_role(RoleArn="arn:aws:iam::{}:role/your-role-to-assume".format(owner_account), RoleSessionName=ami_id) |
|
session = boto3.Session( |
|
aws_access_key_id=response['Credentials']['AccessKeyId'], |
|
aws_secret_access_key=response['Credentials']['SecretAccessKey'], |
|
aws_session_token=response['Credentials']['SessionToken'], |
|
region_name=region |
|
) |
|
ec2 = session.resource('ec2') |
|
# Get the image |
|
image = ec2.Image(ami_id) |
|
# Print tags found in shared account: |
|
print("Found tags in shared ami ({}):".format(ami_id)) |
|
for tag in image.tags: |
|
print("- {}: {}".format(tag['Key'], tag['Value'])) |
|
|
|
# Get access to each of the consumer accounts, to copy the tags |
|
for account in accounts: |
|
childClient = boto3.client('sts') |
|
childResponse = childClient.assume_role(RoleArn="arn:aws:iam::{}:role/your-role-to-assume".format(account['account_number']), RoleSessionName=ami_id) |
|
childSession = boto3.Session( |
|
aws_access_key_id=childResponse['Credentials']['AccessKeyId'], |
|
aws_secret_access_key=childResponse['Credentials']['SecretAccessKey'], |
|
aws_session_token=childResponse['Credentials']['SessionToken'], |
|
region_name=region |
|
) |
|
childEc2 = childSession.resource('ec2') |
|
childImage = childEc2.Image(ami_id) |
|
childImage.create_tags(Tags=image.tags) |
|
print("Copied tags in {}".format(account['account_name'])) |