Reputation: 43
I am using boto3 to tag EC2, and the script was working fine but out of blue somehow its no more tagging it. The peculiar thing is that its not returning any error. I mess the ARN up with dummy digits or no ARN at all just few digits, Still no error. Any Ideas what caused this?
# client = session.resource('ec2')
# This is the client that is passed into the function
def tag_ec2(client, cache, logger):
try:
resource_id = cache['ARN'].split(':')[-1]
response = client.Tag(
resource_id,
cache['key'],
cache['value']
)
print(response)
except Exception as e:
logger.error(f"Exception occurred while tagging {cache['resource']}: {e}.")
return str(e)
return None
This is the function that I use. No matter what ARN I give a real one or a fake one, It never throws any error or tag the instance with the real one either. I've tried it on other EC2 resources like subnet and it works fine with them.
Upvotes: 0
Views: 615
Reputation: 6635
The documentation says, client.Tag
represents a tag, you can think of it as accessing one of the tags in the instance as an object. It is not actually meant to 'create' tags. In that sense, it does make sense that it never returns an error b/c it may actually be your intention that you will first create the object and then do something with it (see resource's available actions here: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#networkinterface )
You can use instance resource's create_tags method as follows (see ref here):
# client = session.resource('ec2')
instance = client.Instance(resource_id)
response= instance.create_tags(Tags=[{'Key': cache['key'], 'Value': cache['Value']}])
and check results with
instance.tags
There are other ways you can use service resource. Actually, it is probably confusing for people to see you are referring to ec2 service resource as client, so let's use correct terminology as follows:
resource = session.resource('ec2')
tags = [{'Key': cache['key'], 'Value': cache['Value']}]
response = resource.create_tags(Resources=[resource_id], Tags=tags)
Note that when you directly use Service Resource, you need to specify both Tags and resource id(s) as explained here.
Upvotes: 2