Using tags with CLI

Overview

In this step, you’ll familiarize yourself with performing tagging operations from the AWS CLI.

To do this step, you need to have AWS CLI installed on your machine. Please refer to this link for installation instructions.

Create an access keys

Access keys are long-term credentials for an IAM user or the AWS account root user. You can use access keys to sign programmatic requests to the AWS CLI or AWS API (directly or using the AWS SDK). To use AWS CLI, you must create an Access key.

  1. In the search bar, find and select IAM access_key

  2. In the Quick Links section, choose My security credentials access_key

  3. Scroll down to Access keys, choose Create access key access_key

  4. Tick the box to agree: “I understand creating a root access key is not a best practice, but I still want to create one.” Then, choose Create access key access_key

  5. Your access key created successfully. Choose Done to finish the process of creating an access key. access_key

Adding tags to an existing EC2 resource

  1. From the CLI, run aws configure to enter your Access key, Secret access key, and the region where you want to create tags for EC2 Instances. access_key

  2. From the CLI, invoke ec2 create-tags with flags –resources and –tags

aws ec2 create-tags --resources <InstanceID> --tags Key=<Key>,value=<Value>

For example, if you wanted to create a tag of “Key=Project,Value=AWS” for an EC2 instance resource, your parameters will be:

aws ec2 create-tags --resources i-0e3175bb924387083 --tags Key=Project,Value=AWS

access_key access_key

  1. If you want to add multiple tags at once, separate them with spaces: ⚠️ Warning: If you cannot run the command below, change your region to us-east-1 or look up the AMI-ID for your region.
aws ec2 create-tags --resources i-0e3175bb924387083 --tags Key=Env,Value=Test Key=Project,Value=AWS

Adding a tag to a new resource

Add tag to new virtual machines

From the CLI, invoke ec2 run-instances to create a new virtual machine and use the flag –tag-specifications to declare tag information:

aws ec2 run-instances `
    --image-id ami-0f3caa1cf4417e51b `
    --count 1 `
    --instance-type t3.micro `
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=ec2-instance-3},{Key=Environment,Value=Test}]" `

Note: You will have to replace the appropriate parameters for your account. The image below illustrates sample output: access_key access_key access_key

Description of tagged resources

From the CLI, invoke ec2 derscibe-instances with the flag –filters. This command is used to list and display detailed information about EC2 Instances based on a specific tag that you have assigned to them.

aws ec2 describe-instances --filters Name=<tag:key>,Values=<SampleTagKey>

For example:

aws ec2 describe-instances --filters Name=tag:Environment,Values=Test

The picture below illustrates sample output: access_key access_key