Skip to content

Instantly share code, notes, and snippets.

@Esl1h
Created September 21, 2020 19:51
Show Gist options
  • Save Esl1h/5085683eef6e08552002fdd51376eab5 to your computer and use it in GitHub Desktop.
Save Esl1h/5085683eef6e08552002fdd51376eab5 to your computer and use it in GitHub Desktop.
AWS. Adiciona no volume EBS as mesmas tags da EC2. Adds the same EC2 tags to the EBS volume.
import boto3
ec2 = boto3.client('ec2')
tags = None
def getVolumesId(filters):
global tags
instances = getInstances(filters)
volumes = []
for instance in instances['Reservations']:
# recupera as tags adicionadas na EC2
tags = instance['Instances'][0]['Tags']
# cria um array com o id dos volumes
volumes.append(instance['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['VolumeId'])
return volumes
def getInstances(filters):
# recupera as EC2 com base nos filtros
return ec2.describe_instances(Filters=filters)
def addTags(volumesId, tags):
for tag in tags:
# remove chave usada pela AWS
if tag['Key'] == 'aws:autoscaling:groupName':
tags.remove(tag)
break
# adiciona tags nos recursos solicitados
response = ec2.create_tags(Resources=volumesId, Tags=tags)
print(response)
# Filtro dos recursos, neste caso busca EC2
filters = [{'Name': 'tag:Name', 'Values': ['MyApp-ec2']}]
# Adiciona Tags
addTags(getVolumesId(filters), tags)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment