Skip to content

Instantly share code, notes, and snippets.

@fideloper
Created November 4, 2016 13:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fideloper/a6296b750e8a73d0da1d54b09dd5749e to your computer and use it in GitHub Desktop.
Save fideloper/a6296b750e8a73d0da1d54b09dd5749e to your computer and use it in GitHub Desktop.
Change many aws instances tags (boto3)
import boto3
import sys
ec2 = boto3.client('ec2')
# Grab where backup retention is 14 days so we can reduce it to 7
instances = ec2.describe_instances(Filters=[{'Name': 'tag:Retention', 'Values': ['14']}])
ids = []
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
ids.append(instance['InstanceId'])
print "Changing tags for %d instances" % len(ids)
ec2.create_tags(
Resources=ids,
Tags=[
{
'Key': 'Retention',
'Value': '7'
}
]
)
@fideloper
Copy link
Author

This assumes you have ~/.aws/credentials setup.

I ran this like so:

export AWS_DEFAULT_PROFILE="a-specific-profile"
export AWS_DEFAULT_REGION="us-east-1"
python tags.py

@dad2jrn
Copy link

dad2jrn commented Mar 14, 2018

What would this look like if I wanted to edit specific tags on a specific set of instance IDs passed either from a text file or passed as an argument?

@shadycuz
Copy link

shadycuz commented Mar 28, 2018

@dad2jrn If passing them as input on the CLI lookup pythons arg parser. If passing them via file it depends on the format. JSON, YAML, CSV? Basically, you would read the file into python using...

with open('data.txt', 'r') as myfile:
  data = myfile.read()

You could then take that data file and turn it into json. (if it's json format)

import json
data = json.load(data)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment