Create a key pair and download the .pem file with Terraform (AWS)

17.3k Views Asked by At

I could create the key pair myKey to AWS with Terraform.

resource "tls_private_key" "pk" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "kp" {
  key_name   = "myKey"       # Create a "myKey" to AWS!!
  public_key = tls_private_key.pk.public_key_openssh
}

AWS:

enter image description here

But I couldn't download the myKey.pem file. Is it possible to download the myKey.pem file with Terraform like below?

enter image description here

2

There are 2 best solutions below

0
On BEST ANSWER

Feb, 2022 Update:

No, it's not possible to download the myKey.pem file with Terraform. Instead, we can create the myKey.pem file which has the same private key as the key pair myKey on AWS. So the created myKey and myKey.pem file by Terraform are the same as those which we manually create and download on AWS. This is the code below. (I used Terraform v0.15.4)

resource "tls_private_key" "pk" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "kp" {
  key_name   = "myKey"       # Create a "myKey" to AWS!!
  public_key = tls_private_key.pk.public_key_openssh

  provisioner "local-exec" { # Create a "myKey.pem" to your computer!!
    command = "echo '${tls_private_key.pk.private_key_pem}' > ./myKey.pem"
  }
}

Don't forget to make myKey.pem file only readable by you running the code below before ssh to your ec2 instance.

chmod 400 myKey.pem

Otherwise the error below occurs.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0664 for 'myKey.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "myKey.pem": bad permissions
[email protected]: Permission denied (publickey).
4
On

Terraform resource tls_private_key has attributes that can be exported. This is the list.

The way you would download myKey.pem using Terraform would be by exporting the attribute private_key_pem to a local file.

So in your case, it would be:

resource "tls_private_key" "pk" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "kp" {
  key_name   = "myKey"       # Create a "myKey" to AWS!!
  public_key = tls_private_key.pk.public_key_openssh
}

resource "local_file" "ssh_key" {
  filename = "${aws_key_pair.kp.key_name}.pem"
  content = tls_private_key.pk.private_key_pem
}

Note:

  1. You can't export the content of attribute private_key_pem using either of resources tls_private_key and local_file. If you really wan't to, here's how.

  2. The file myKey.pem is generated by Terraform with permissions 755. You would need to change this to 400