amazon-web-servicesamazon-ec2terraformprivate-keykey-pair

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


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


Solution

  • 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
    ubuntu@35.72.30.251: Permission denied (publickey).