joshft91
joshft91

Reputation: 1885

Search AWS CLI output and save to variable

I'm very new to batch files, but I'm trying to use one to automate some AWS CLI instance-creation.

What I have is pretty simple so far -- I have a command in my .bat file that will run the run-instances command:

aws ec2 run-instances --dry-run --image-id %ami_id% --key-name %keypair% --security-group-ids %security_group% --instance-type "r3.large" --subnet-id %az1b_subnet%

This command takes a little bit to run, but will eventually (without the --dry-run) return json about the created instance(s). I'd like to search that json output and save the instance-id to a variable so that I can use it to tag my newly created instance with the ec2 create-tags command.

Any thoughts on how I could do that? My first attempt was to add > test.txt to the end of the above command and then search through the json and set the variable. However, the test.txt is created instantly before the CLI command has finished and returned its output.

Thanks.

Upvotes: 17

Views: 30428

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269340

The AWS Command-Line Interface (CLI) has a --query parameter that can be used to specify the output fields. Combined with --output text, it can provide a list of Instance IDs.

Here's a script, assuming that only one instance is started per run-instances call (otherwise a loop would be required):

ID=`aws ec2 run-instances --image-id ami-xxxxxxxx --instance-type t1.micro --query 'Instances[0].InstanceId' --output text`

aws ec2 create-tags --resources $ID --tags Key=Name,Value=WebServer

Upvotes: 35

Related Questions