How to apply tags on EC2 instances using Python

This post explains how to apply, retrieve or delete tags from an EC2 instance using Python.To manage your EC2 instances you can assign tags on each EC2 instance. Tags enables you to categorize the instances in different ways.

Prerequisite

To run the python script from your local machine you need to have Boto3 credential set up, refer Setting up boto3 credentials for configuring Boto3 credentials.

Python code to apply tags on EC2 instance

AWS Boto3 provides create_tags api to add or overwrite the specified tags on specified EC2 resources. Each resource can have a maximum of 50 tags.

   
  import boto3

  client = boto3.client("ec2")

  tags = [
      {"Key": "Name", "Value": "foo"},
      {"Key": "Owner", "Value": "bar"},
      {"Key": "Department", "Value": "baz"},
  ]

  instance_ids = ["insatnce_id_1", "insatnce_id_2"]

  response = client.create_tags(DryRun=False, Resources=instance_ids, Tags=tags)

  print(response)
    
   

Python code to retrieve tags from EC2 instance

AWS Boto3 provides describe_tags api to fetch tags from an specified EC2 instance.

   
  import boto3

  client = boto3.client("ec2")

  instance_id = "instance_id_1"

  response = client.describe_tags(
      DryRun=False, Filters=[{"Name": "resource-id", "Values": [instance_id]}]
  )

  print(response)
   

Python code to delete tags from EC2 instance

AWS Boto3 provides delete_tags api to delete specified tags from the specified set of resources from an specified EC2 instance.

   
  import boto3

  client = boto3.client("ec2")
  
  tags_to_delete = {"Key": "Department"}

  instance_ids = ["instance_id_1"]
  
  response = client.delete_tags(
      DryRun=False, Resources=instance_ids, Tags=[tags_to_delete]
  )

  print(response)
   

Category: AWS