Post

Create RSA Key Pair with Terraform

Generate RSA key pair and save private key locally using Terraform

Create RSA Key Pair with Terraform

Terraform: Create RSA Key Pair

Generate an RSA key pair and save the private key to a file using Terraform.

The Code

Create main.tf:

1
2
3
4
5
6
7
8
9
10
11
12
# Generate RSA private key
resource "tls_private_key" "devops_kp" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

# Save private key to file
resource "local_file" "devops_private_key" {
  content  = tls_private_key.devops_kp.private_key_pem
  filename = "/home/bob/devops-kp.pem"
  file_permission = "0600"
}

Verify the Key Pair

Run these commands to confirm the key was created successfully:

1
2
3
4
5
# Check file exists
ls -la /home/bob/devops-kp.pem

# Verify RSA key type
openssl rsa -in /home/bob/devops-kp.pem -check -noout
This post is licensed under CC BY 4.0 by the author.