AWS CLI EC2 Describe Tags

Here’s how to get a list of EC2 tags.

aws ec2 describe-tags \
--filters "Name=resource-id,Values=i-xxxxxxxxxxxxx" \
--query 'Tags[][Key,Value]'  \
--profile default \
--region us-east-1 \
--output text

Terraform Launch EC2 Instance

Here’s the template for launching an EC2 instance via Terraform.

provider "aws" {
  region                  = "us-east-1"
  shared_credentials_file = "/home/username/.aws/credentials"
  profile                 = "default"
}
resource "aws_security_group" "hostname-sg" {
	name = "allow ssh"
	vpc_id = ""
	ingress {
		cidr_blocks = [ "10.0.0.0/8" ]
		from_port = 22
		to_port = 22
		protocol = "tcp"
	}
	egress {
		from_port = 0
		to_port = 0
		protocol = "-1"
		cidr_blocks = [ "0.0.0.0/0" ]
	}
}
resource "aws_instance" "hostname" {
	ami = "ami-xxxxxxxxxx"
	key_name = "your-key"
	instance_type = "t2.large"
	subnet_id = "subnet-xxxxxxxx"
	security_groups	= ["${aws_security_group.hostname-sg.id}"]
	tags {
		Name = "hostname"
		Environment = "development"
	}
}

AWS CLI Add Tags to IAM User

How to add tags to an existing IAM user via AWS CLI.

aws iam tag-user \
--user-name john.doe \
--tags '{"Key": "Department", "Value": "Accounting"}'

Multiple tags.

aws iam tag-user \
--user-name john.doe \
--tags '[{"Key": "Department", "Value": "Accounting"},{"Key": "Manager", "Value": "jane.doe"}]'

AWS CLI: Describe Instances

If you have a ton of EC2 instances, one way to get results quickly is to run to use AWS CLI such as “describe-instances.” Here’s an example on how to get a list of instances with a tag name equal to some value. In addition, you limit the display only results you want displayed.

$ aws ec2 describe-instances \
--query 'Reservations[].Instances[].Tags[?Key==`Name`].Value' \
--filter Name=tag:Project,Values=web \
--region us-east-1 \
--profile default \
--output text

This returns values of the “Name” tag name in instances where they occur.