17

I am trying to create an instance in ec2 using CLI. Is there anyway to specify tags to the instance when using CLI to create instances?

aws ec2 run-instances --image-id $ami_id --key-name $deployment_key_name \
--region $region --security-groups default --instance-type m4.large \
--user-data file://./yaml/master.yaml

3 Answers 3

33

As of 28 March 2017, you can specify tags for instances (and attached volumes) as part of the run-instances command.

Example:

aws ec2 run-instances --image-id ami-abc12345 --count 1 \
--instance-type t2.micro --key-name MyKeyPair \
--subnet-id subnet-6e7f829e \
--tag-specifications 'ResourceType=instance,Tags=[{Key=webserver,Value=production}]' 'ResourceType=volume,Tags=[{Key=cost-center,Value=cc123}]' 

Announcement blog post: https://aws.amazon.com/blogs/aws/new-tag-ec2-instances-ebs-volumes-on-creation/

Additional documentation (see example 4): http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI

1
  • 1
    just a small add - you need to upgrade or reinstall your AWS EC2 Cli
    – Up_One
    Commented Nov 11, 2017 at 0:38
2

Use the aws ec2 create-tags command afterwards to add tags by instance ID.

2
  • I need to add tags when creating instances, like from GUI Commented Sep 24, 2015 at 9:37
  • There's no way to do it in a single command. You must use this second command after the instance is launched. The GUI does the same thing but it hides it. Commented Sep 25, 2015 at 13:28
0

Here is my suggestion and a way to verify it:

I am using SSO with the profile name ATeam. You will need to update this accordingly in your config and credentials files.

Create the instance:

aws ec2 run-instances \
 --image-id ami-0578f2b35d0328762 \
 --instance-type t2.micro \
 --security-group-ids sg-065d064965244f9a0 \
 --subnet-id subnet-00d93c6b00c0a6ccb \
 --key-name devass \
 --user-data file://ec2-user-data-web-app.md \
 --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=pub_1},{Key=Group,Value=devass},{Key=LifeCycle,Value=development}]' \
 --count 1 \
 --profile ATeam

Verify the important instance information, Sorry, the query needs to be placed on one line as I have not discovered a way to break it down to multiple lines.

  aws ec2 describe-instances  --query "Reservations[*].Instances[*].{Instance:InstanceId,PublicIP:PublicIpAddress,Name:Tags[?Key=='Name']|[0].Value,Group:Tags[?Key=='Group']|[0].Value,LifeCycle:Tags[?Key=='LifeCycle']|[0].Value,Status:State.Name}" \
  --profile ATeam \
  --output table

Result: Console Output for describe-instances

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .