
This command would generate a public and private key
$ ssh-keygen -f terraform_ec2_key
This resources would import aws key pair
### Option 1 - Terraform can generate SSL/SSH private keys using the tls_private_key resource | |
variable "key_name" {} | |
resource "tls_private_key" "example" { | |
algorithm = "RSA" | |
rsa_bits = 4096 | |
} | |
resource "aws_key_pair" "generated_key" { | |
key_name = "var.key_name" | |
public_key = "${tls_private_key.example.public_key_openssh}" | |
} | |
resource "aws_instance" "web" { | |
ami = "ami-5b673c34" | |
instance_type = "t2.micro" | |
key_name = "${aws_key_pair.generated_key.key_name}" | |
tags = { | |
Name = "HelloWorld" | |
} | |
} | |
### Option 2 - Retrieving the Public Key for Your Key Pair on Linux and use with aws_key_pair using | |
chmod 400 my-key-pair.pem | |
ssh-keygen -y -f /path_to_key_pair/my-key-pair.pem >> terraform_ec2_key.pub | |
provider "aws" { | |
region = "ap-south-1" | |
access_key = "" | |
secret_key = "" | |
} | |
resource "aws_key_pair" "terraform-demo" { | |
key_name = "terraform-demo" | |
public_key = "file(terraform_ec2_key.pub)" | |
} |










I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND