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.
AWS uses JMESPath, as the spec for their --query option. When passing jmespath filter expression as a string: You can use double quotes (") instead and wrap the variable in single quotes ('). This will not prevent the variable from being replaced.
Output format json – The output is formatted as a JSON string. yaml – The output is formatted as a YAML string. yaml-stream – The output is streamed and formatted as a YAML string. Streaming allows for faster handling of large data types.
AWS_PROFILE. Specifies the name of the AWS CLI profile with the credentials and options to use. This can be the name of a profile stored in a credentials or config file, or the value default to use the default profile.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With