I'm trying to tag ec2 instances using boto3. My plan is to take input from a text file, from which I'd like to create a dictionary and then loops through this tagging the instances.
Text file is in the format of:
'ec2-id'#[{'Key': 'firstKey', 'Value': 'firstValue'}, {'Key': 'secondKey', 'Value': 'secondValue'}, {'Key': 'thirdKey', 'Value': 'thirdValue'}]
My code is:
import boto3
import json
region = 'eu-west-1'
client = boto3.client('ec2',region)
ec2Instances = client.describe_instances()['Reservations']
num_of_instances = (len(ec2Instances))
print('Number of instance to tag is: ', num_of_instances)
tagsDict = {}
input = open(".\input.txt")
delim = '#'
for line in input:
key, value = line.split(delim)
tagsDict.update({key: value})
print(tagsDict)
input.close()
for i in list(tagsDict.keys()):
client.create_tags(
Resources = [i],
Tags = tagsDict[i]
)
print(i)
print(tagsDict[i])
returned error:
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Tags, value: [{'Key': 'firstKey', 'Value': 'firstValue'}, {'Key': 'secondKey', 'Value': 'secondValue'}, {'Key': 'thirdKey', 'Value': 'thirdValue'}], type: <class 'str'>, valid types: <class 'list'>, <class 'tuple'>
I'm a beginner to python and boto3 but it seems to me the issue is that the way i'm constructing the dictionary the value is a string but if I create it manually and the value is a list of dictionaries it works ie:
tagsDict['ec2-id'] = [{'Key': 'firstKey', 'Value': 'firstValue'}, {'Key': 'secondKey', 'Value': 'secondValue'}, {'Key': 'thirdKey', 'Value': 'thirdValue'}]
Any help would be massively appreciated! Thanks.