AWS SSH Key Pair Creation

Viewed 223

I came across the following command to create AWS SSH key-pair but failed to understand what "--query" parameter is doing here.

aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem

Can someone please explain me the significance of --query parameter?

2 Answers

The --query parameter is a feature of the AWS CLI tool that allows you to filter the response that is displayed when the command has executed successfully. All the --query KeyMaterial parameter is doing is restricting the output of the command to the actual contents of the SSH key, without any other data like the key's ID or anything. This is necessary because the output is being saved to a file via > MyKeyPair.pem.

By using the --query parameter you are able to modify the response you will receive back from the AWS API.

This feature can be very useful in scenarios where you want to programmatically use the AWS CLI to extract parts of a response, in your example this is extracting the KeyMaterial attribute from the response but it could also be used to filter and extract attributes based on their values.

For you usecase it means you will be able to get the plain text of the key and pump it straight into a text file rather than manually performing copy and paste (although this is benefited by the --output flag).

For more information take a look at the Controlling command output from the AWS CLI documentation.

Related