Generating and using AWS Key Pairs with Terraform or OpenTofu

· Updated · 3 min read · Terraform & OpenTofu Tutorials

SSH access to EC2 instances requires a key pair #

This how-to shows how to create a key pair using ssh-keygen and how to upload it to AWS using Terraform / OpenTofu.

Documentation:

Intended usage:

  • Connect using SSH protocol to EC2 Linux Instances.
  • Configure EC2 Linux instances using Ansible.

Prerequisites #

The ssh-keygen command is part of the OpenSSH authentication key utility and is available on most Linux distributions (see also Public Key Authentication):

$ ssh-keygen

Generate a Key Pair #

There are multiple ways to generate SSH Key Pairs depending on the needs.

Command line quick generation without a passphrase

  • -t ed25519 indicates using the Edwards-curve Digital Signature Algorithm for key generation.
  • -N "" avoids setting a passphrase (a secret used to protect the private key).
  • -C "Demo IT Wonder Lab SSH User" is a text description of the Key Pair.
  • -f ~/keys/ditwl-kp-config-user-ecdsa specifies where to store the private and public key files.

Generate the Key Pair:

$ ssh-keygen -t ed25519 -N "" -C "Demo IT Wonder Lab SSH User" -f ~/keys/ditwl-kp-config-user-ecdsa
Generating public/private ed25519 key pair.
Your identification has been saved in /home/jruiz/keys/ditwl-kp-config-user-ecdsa
Your public key has been saved in /home/jruiz/keys/ditwl-kp-config-user-ecdsa.pub
The key fingerprint is:
SHA256:w3ErTHem1Iz3JVvhmL7rx5uVE0b4idJauyTh6mGqirQ Demo IT Wonder Lab SSH User
The key's randomart image is:
+--[ED25519 256]--+
|               . |
|           +  + o|
|        o = *..=o|
|       + = * .== |
|        S.o  oo+ |
|     .  .oo . . +|
|    . .  B =   +.|
|     E  = B o   *|
|   .o... o o  .Bo|
+----[SHA256]-----+

Two files are generated in the ~/keys/ directory (~ is the user home directory):

  • ditwl-kp-config-user-ecdsa: private key, to use by SSH and Ansible.
  • ditwl-kp-config-user-ecdsa.pub: a public key to be distributed to EC2 instances using AWS Console or Terraform.

Set the right permission to the file #

The private key file should be readable only by its owner. Set the right permission:

$ chmod 600 $HOME/keys/ditwl_kp_infradmin.pem

Upload the Key to AWS using Terraform #

Terraform provides a resource for the creation of Key Pairs. The following example creates a key pair with the name ditwl-kp-config-user using the previously created public key.

# Copyright (C) 2018 - 2023 IT Wonder Lab (https://www.itwonderlab.com)
#
# This software may be modified and distributed under the terms
# of the MIT license.  See the LICENSE file for details.
# -------------------------------- WARNING --------------------------------
# IT Wonder Lab's best practices for infrastructure include modularizing 
# Terraform/OpenTofu configuration. 
# In this example, we define everything in a single file. 
# See other tutorials for best practices at itwonderlab.com
# -------------------------------- WARNING --------------------------------

#Define Terrraform Providers and Backend
terraform {
  required_version = "> 1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

#-----------------------------------------
# Default provider: AWS
#-----------------------------------------
provider "aws" {
  shared_credentials_files = ["~/.aws/credentials"]
  profile                  = "ditwl_infradmin"
  region                   = "us-east-1" //See BUG https://github.com/hashicorp/terraform-provider-aws/issues/30488
}

resource "aws_key_pair" "ditwl-kp-config-user" {
  key_name   = "ditwl-kp-config-user"
  public_key = file("~/keys/ditwl-kp-config-user-ecdsa.pub")
}

Create the Key Pair using Terraform #

Init, Plan and Apply the Terraform plan:

$ tofu apply

OpenTofu used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

OpenTofu will perform the following actions:

  # aws_key_pair.ditwl-kp-config-user will be created
  + resource "aws_key_pair" "ditwl-kp-config-user" {
      + arn             = (known after apply)
      + fingerprint     = (known after apply)
      + id              = (known after apply)
      + key_name        = "ditwl-kp-config-user"
      + key_name_prefix = (known after apply)
      + key_pair_id     = (known after apply)
      + key_type        = (known after apply)
      + public_key      = "ssh-ed25519 AAAAC3NzaC1lZYUA1NTE5AAASIA1CQW/T/mJrP+YWKg+l100+JYlPLNIHBFYRNy3uyZUh Demo IT Wonder Lab SSH User"
      + tags_all        = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  OpenTofu will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_key_pair.ditwl-kp-config-user: Creating...
aws_key_pair.ditwl-kp-config-user: Creation complete after 1s [id=ditwl-kp-config-user]

Check at the AWS Console #

Check that the Key Pair has been created in the AWS Console

Visit EC2 → Key Pairs (under Network & Security)

Key pairs EC2 us east

Next Steps #

Create an EC2 instance with Terraform, assign the Private Key, and configure with Ansible.

About Edwards-curve Digital Signature Algorithm (Ed25519) #

Ed25519 is a digital signature algorithm that uses elliptic curve cryptography (ECC) to provide secure authentication and data integrity. It is a popular choice for applications that require high performance and small key sizes, such as:

  • SSH authentication: Securely logging into remote servers.
  • TLS/SSL certificates: Protecting website traffic.
  • Code signing: Ensuring the authenticity of software.
  • Blockchain transactions: Verifying the legitimacy of transactions on a blockchain.

Key features of Ed25519:

  • High performance: Ed25519 is significantly faster than other commonly used digital signature algorithms, such as RSA and ECDSA. This makes it ideal for applications that require fast signing and verification of messages.
  • Small key sizes: Ed25519 uses small public and private keys (32 bytes each), which makes them easier to store and transmit than larger keys used by other algorithms.
  • High security: Ed25519 is considered to be a very secure algorithm. It has been carefully designed to resist attacks, and it is based on the well-studied mathematics of elliptic curves.
  • Open-source: Ed25519 has an open-source license.

Notes:

  • Ed25519 Key Pairs can not currently be used with AWS Windows machines.
  • Key pairs do not expire.
  • Instead of opening SSH, consider AWS Systems Manager Session Manager, which does not need key pairs or inbound ports.

#AWS EC2 #OpenTofu #Public-Key #SSH #Terraform