Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Forked from pjaudiomv/update-ssm-tags.sh
Last active October 1, 2020 23:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitrocode/401fb59fd7318fc91db045164d6f09da to your computer and use it in GitHub Desktop.
Save nitrocode/401fb59fd7318fc91db045164d6f09da to your computer and use it in GitHub Desktop.
Tags instances with detected platform_version
#!/usr/bin/env python
# Original: https://gist.github.com/pjaudiomv/ff5efca41cdb7244ef4416c6097f6a7a
import boto3
import pdb
TAG_PLATFORM_VERSION = 'platform_version'
def get_ssm_by_platform_versions(ssm_res):
versions = {}
for instance in ssm_res['InstanceInformationList']:
if not instance['PlatformVersion'] in versions:
versions[instance['PlatformVersion']] = []
versions[instance['PlatformVersion']] += [instance]
return versions
def main():
ssm = boto3.client('ssm')
ec2 = boto3.client('ec2')
ssm_params = {
'MaxResults': 50
}
while True:
ssm_res = ssm.describe_instance_information(**ssm_params)
print(f"Retrieved {len(ssm_res['InstanceInformationList'])} instances from SSM")
# sort by platform version so there are few ec2 create tags requests
platform_versions = get_ssm_by_platform_versions(ssm_res)
for version in platform_versions:
resources = [
instance['InstanceId']
for instance in platform_versions[version]
]
# ec2 create_tags max has a limitation of 1000 resources but we're
# limited by ssm's max of 50 so no need to paginate
ec2_res = ec2.create_tags(
Resources=resources,
Tags=[{
'Key': TAG_PLATFORM_VERSION,
'Value': version,
}]
)
print(f'Tagged {len(resources)} instances with {TAG_PLATFORM_VERSION}={version}')
if 'NextToken' in ssm_res:
ssm_params['NextToken'] = ssm_res['NextToken']
else:
break
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment