Create and Remove AWS EC2 key pair by using command line

When we launch a new EC2 instance in AWS Cloud , to access the server we need the ssh keys. In EC2 instances password are not set , we have to use ssh key to get access whereas keys are based on public–key cryptography.

Here, we are quickly going through with creating/removing/listing the ssh keys by using command line. We will do this practice by using AWS cli with AWS Access key set on your system .
(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)

Create AWS ssh key by using aws command line

Generally we use the below command so that the .pem file will be created directly to your working directory.

Replace the below given values in command –
1. us-east-1 ## with region where you want to create keys
2. my-aws-key ## Give your desired key name

aws --region us-east-1 ec2 create-key-pair --key-name my-aws-key --query 'KeyMaterial' --output text > my-aws-key.pem

When we use above command , the .pem file will be get created.

Now, give 400 permission to aws key file (.pem file)

chmod 400 my-aws-key.pem

List AWS ssh keys by using aws command line

To list the AWS ssh keys are very simple.
Replace us-east-1 with region name you want .

aws --region us-east-1 ec2 describe-key-pairs

Remove the AWS ssh key by using aws command line

First list the AWS ssh key available as we have described in above section. To remove the ssh key, use below given command.
Replace us-east-1 with your given region name and my-aws-key with your aws ssh key (Listed from above given command).

aws --region us-east-1 ec2 delete-key-pair --key-name my-aws-key