Reputation: 109
With minimal experience in python, I am looking for ideas in building a lambda that tags AWS resources, especially ec2-instances and their volumes, by using prefix in the instance name tag.
Examples:
I would like to setup auto tagging for predefined set of tags by using the prefix "dev-cassandra" which should apply to any new instances created with this prefix.
Similarly different set of tags to different application instances.
This can be applied by provisioning tool for the regular instances, but not to the existing ASG instances.
Upvotes: 1
Views: 976
Reputation: 1
HERE is a little script I created in Python that I think would accomplish what you're looking for.
You need to tell the script the following information:
The AWS CLI profile to use The AWS region where to run The AWS resources to process (Currently I have added 10 options) The tag key and the tag values along with the "hint" words that could help the script to identify the possible value for that missing tag. You would get a list of your resources, along with the missing tag suggestion based on the existing resource key, description, and resources ID. Once your happy with the tag value suggestion, you can select to apply in bulk or one by one the missing tags to your AWS resources.
Upvotes: 0
Reputation: 329
You can insert tags upon instance creation by using resource-method create_instances in the 'TagSpecifications' attribute.
Or you can also edit specific instance tags with the client-method create_tags for this method you need to get the instance id first. The prefix logic can be added to the python script as desired.
Here are 2 examples of these methods:
create_instances:
# Getting resource object with aws credentials
s = boto3.Session(
region_name=<region_name>,
aws_access_key_id=<aws_access_key>,
aws_secret_access_key=<aws_secret_access_key>,
)
ec2 = s.resource('ec2')
# Some of these options are optional
instance = ec2.create_instances(
ImageId=<ami_id>,
MinCount=1,
MaxCount=1,
InstanceType=<instance_type>,
KeyName=<instance_key_pair>,
IamInstanceProfile={
'Name': <instance_profile>
},
SecurityGroupIds=[
<instance_security_group>,
],
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': <key_name>,
'Value': <value_data>,
},
]
},
],
)
create_tags:
# Next line is for getting client object from resource object
ec2_client = ec2.meta.client
ec2_client.create_tags(
Resources=[
<instance_id>,
],
Tags=[
{
'Key': 'Name',
'Value': <dev-cassandra><_your_name>
},
{
'Key': <key_name>,
'Value': <value_data>,
},
]
)
worth mentioning that the "instance name" is also a tag. For example:
{
'Key': 'Name',
'Value': <dev-cassandra><_your_name>
}
Upvotes: 1