I want to make a script that checks for an EC2 instance if it has an existing association with the SSM document AWS-GatherSoftwareInventory, If not, create it. The aim is to have an association per instance so that we can gather information about installed apps and running services. So Here is the python script I made for this: To run the script I pass the instance ID as an argument:
import boto3
import argparse
session = boto3.session.Session(profile_name='production')
ssm = session.client('ssm')
argparser = argparse.ArgumentParser()
argparser.add_argument("--instance_id", help="instance ID to create the association for", dest='instance_id')
args = argparser.parse_args()
#First, make sure there is no old association to this instance
filter = [{'key' :'Name','value': 'AWS-GatherSoftwareInventory'}]
list_instances = []
response = ssm.list_associations(AssociationFilterList=filter).get('Associations')
for association in response:
for target in association['Targets']:
list_instances.append(target['Values'][0])
if args.instance_id not in list_instances:
# Create association for this instance
response = ssm.create_association(Name='AWS-GatherSoftwareInventory',
Targets=[{'Key':'InstanceIds','Values':[args.instance_id]}],
ScheduleExpression="cron(0 0 * * ? *)",
SyncCompliance='AUTO')
print("Association for instance ID: "+args.instance_id+" is created with the association ID: "+response.get('AssociationDescription')['AssociationId'])
else:
response = ssm.list_associations(AssociationFilterList=filter).get('Associations')
print("this instance "+args.instance_id+" has already an association.")
So what I do here, I list all associations and keep all the target instances IDs in a list, and check if my instance is in that list, if not, create the association for it. My problem is, even if the association exists already, the script goes ahead and recreate a new one which turns into failure because one instance can only have one single association. Where is the issue? SSM API issue ? or programatical one?