Generating and using AWS Key Pairs with Terraform or OpenTofu

SSH Access to EC2 instances requieres a Key Pair

This howto 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.

How to create SSH Private Keys for AWS and Terraform

  1. Prerequisites

    Check that ssh-keygen is available.

  2. Generate a Key Pair

    Use ssh-keygen command line to generate a Key Pair and set the right file security.

  3. Upload the Key to AWS using Terraform

    Use the aws_key_pair Terraform resource to upload the Key Pair to AWS

  4. Next Steps

    Create an instance with Terraform and assign the Key Pair.

Prerequisites

The ssh-keygen command is part of OpenSSH authentication key utility and is readily available on most Linux distributions:

$ 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 paraphrase (secret used to protect an encryption key).
  • -C "Demo IT Wonderl Lab SSH User" is a text description of the Key Pair.
  • -m pem uses PEM (Privacy-Enhanced Mail) format for key generation and storage.
  • -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" -m pem -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.

Make sure to store the files in a secure location and make a backup.

Set the right permission to the file

The private key file should have read-only mode by the 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 1

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 don't have caducity.

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Cloud Tutorials

Securing your Infrastructure: Encrypting Terraform State Files with OpenTofu
Using the Terraform aws_route53_delegation_set, aws_route53_zone, and aws_route53_record resource blocks to configure DNS in AWS.
Using the Terraform aws_db_instance resource block to configure, launch, and secure RDS instances.
How to use the Terraform aws_instance resource block to configure, launch, and secure EC2 instances.
How to configure and use the Terraform aws_ami data source block to find and use AWS AMIs as templates (root volume snapshot with operating system and applications) for EC2 instances.
Javier Ruiz Cloud and SaaS Expert

Javier Ruiz

IT Wonder Lab tutorials are based on the diverse experience of Javier Ruiz, who founded and bootstrapped a SaaS company in the energy sector. His company, later acquired by a NASDAQ traded company, managed over €2 billion per year of electricity for prominent energy producers across Europe and America. Javier has over 25 years of experience in building and managing IT companies, developing cloud infrastructure, leading cross-functional teams, and transitioning his own company from on-premises, consulting, and custom software development to a successful SaaS model that scaled globally.

Are you looking for cloud automation best practices tailored to your company?

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram