Skip to content

Instantly share code, notes, and snippets.

@diomalta
Created July 1, 2021 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diomalta/e0a573156678b08cf3fc5f6dab321da0 to your computer and use it in GitHub Desktop.
Save diomalta/e0a573156678b08cf3fc5f6dab321da0 to your computer and use it in GitHub Desktop.
AWS - SSH key generated by terraform
variable "key_name" {
type = string
default = "manager_rsa"
}
# Creates a private key and saves it in Terraform state without encryption
# https://registry.terraform.io/providers/hashicorp/tls/latest/docs/resources/private_key
resource "tls_private_key" "rsa_key" {
algorithm = "RSA"
rsa_bits = 4096
}
# Generate key pair for access EC2 instance
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/key_pair
resource "aws_key_pair" "deployer" {
key_name = var.key_name
public_key = tls_private_key.rsa_key.public_key_openssh
}
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance
resource "aws_instance" "web" {
...
key_name = aws_key_pair.deployer.key_name
...
}
# In addition to having access by state, we can recover in other ways.
# Use output
output "private_ssh_key" {
description = "ssh key generated by terraform"
value = tls_private_key.rsa_key.private_key_pem
}
# Use "local-exec" and create 'manager_rsa.pem' in current directory
resource "aws_key_pair" "deployer" {
key_name = var.key_name
public_key = tls_private_key.rsa_key.public_key_openssh
provisioner "local-exec" {
command = "echo '${tls_private_key.rsa_key.private_key_pem}' > ./'${var.key_name}'.pem"
}
provisioner "local-exec" {
command = "chmod 400 ./'${var.key_name}'.pem"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment