Synchronize tag values between EC2 instances and EBS volumes

Synchronize tag values between EC2 instances
and EBS volumes for the following tags

Name
Owner
Environment
CostCentre

The code also makes use of existing IAM roles with assume role and MFA tokens

# ------------------------------------------
# synchtags.py
# synchronize tag values between EC2 instances
# and EBS volumes for the following tags
#
# Name
# Owner
# Environment
# CostCentre
#
# ------------------------------------------
import boto3
import sys
from datetime import datetime, timedelta

# Account Switch
print(sys.argv[1])
if sys.argv[1] == "Production":
sRoleSessionName="Production"
sRoleArn="arn:aws:iam::xxxxxxxxxxxx:role/production-fulladmin"
sSerialNumber="arn:aws:iam::xxxxxxxxxxxx:mfa/username"

if sys.argv[1] == "Development":
sRoleSessionName="Development"
sRoleArn="arn:aws:iam::xxxxxxxxxxxx:role/development-fulladmin"
sSerialNumber="arn:aws:iam::xxxxxxxxxxxx:mfa/username"

mfa_token = input("Enter the MFA code: ")

sts_client = boto3.client('sts')

print("Accessing Account:", sRoleSessionName)

assumedRoleObject = sts_client.assume_role(
    RoleArn=sRoleArn,
    RoleSessionName=sRoleSessionName,
    SerialNumber=sSerialNumber,
    TokenCode=mfa_token,
)

credentials = assumedRoleObject['Credentials']

ec2client = boto3.resource(
    'ec2',
    aws_access_key_id = credentials['AccessKeyId'],
    aws_secret_access_key = credentials['SecretAccessKey'],
    aws_session_token = credentials['SessionToken'],
region_name='us-east-1',
)

instances =   ec2client.instances.all()
for instance in instances:
print('---- Processing Instance ID: ', instance.id)
for tag in instance.tags:
if tag['Key'] == 'CostCentre':
costcentretag=tag['Value']
for vol in instance.volumes.all():
vol.create_tags(Tags=[{"Key" : "CostCentre", "Value" : costcentretag}])
if tag['Key'] == 'Name':
nametag=tag['Value']
for vol in instance.volumes.all():
vol.create_tags(Tags=[{"Key" : "Name", "Value" : nametag}])
if tag['Key'] == 'Environment':
environmenttag=tag['Value']
for vol in instance.volumes.all():
vol.create_tags(Tags=[{"Key" : "Environment", "Value" : environmenttag}])
if tag['Key'] == 'Owner':
ownertag=tag['Value']
for vol in instance.volumes.all():
vol.create_tags(Tags=[{"Key" : "Owner", "Value" : ownertag}])

Comments

Post a Comment

Popular posts from this blog

Basic Send Message to MQ with Java and IBM MQ JMS

Basic Receive Message to MQ with Java and IBM MQ JMS

Creating a simple Alert / Success Message with ASP.NET/VB using Bootstrap