How to configure and use the Terraform aws_key_pair
resource block to create and manage AWS Key Pairs for performing SSH Public Key Authentication into EC2 instances.
Welcome to our tutorial series where we dive into cloud infrastructure deployment using Terraform or OpenTofu on AWS. In this series, the fundamentals are shown, guiding you through the process of minimizing resource usage and simplifying the deployment complexities associated with cloud infrastructure. This tutorial series is a work in progress.
This comprehensive OpenTofu and Terraform tutorial guides you step-by-step through creating infrastructure in AWS using Terraform.
Infrastructure as Code (IaC) helps maintain consistency, enables version control, enhances collaboration among teams, allows for easier replication of environments, streamlines the deployment and management of infrastructure boosting efficiency, and reducing errors in managing complex systems.
How to start building AWS infrastructure with Terraform: Key Pairs
Read previous sections of the tutorial: AWS with Terraform Tutorial
An AWS Key Pair is a set of security credentials that consists of a public key and a private key. It is used to securely connect to Amazon EC2 instances.
How to create an AWS Key Pair with Terraform
Generate a Key Pair that will allow SSH Authentication into the instance and upload the Key Pair Public Key to AWS using Terraform (to be used in Cloud-init scripts).
Plan, and apply the Terraform plan to create the Key Pair in AWS.
There is no cost for creating or having Key Pairs in AWS.
Common Questions About AWS Key Pairs
Can a lost AWS Key Pair be regenerated? Where should the AWS Key Pair be stored? ...
Other tutorials for creating infrastructure in AWS using Terraform
Read previous sections of the tutorial:
An AWS Key Pair is a set of security credentials that consists of a public key and a private key. It is used to securely connect to Amazon EC2 instances and authenticate access using Public key authentication for SSH.
The AWS Key Pair can be generated using the AWS Console or using external tools like ssh-keygen. AWS only stores the Public Key and AWS generated Private Keys are deleted after being generated and downloaded. See
In this tutorial the Key Pair is generated outside AWS, using the command line tool ssh-keygen
.
During instance launch, Cloud-init scripts appends the AWS stored Public Key to the instance authorized_keys file inside the ~/.ssh/ directory.
Previous sections of this AWS with Terraform guide have covered basic information about Terraform and AWS and have configured and used the AWS Terraform provider to create a VPC, four subnets, one Internet Gateway, two NAT Gateways, three Routing Tables, and Security Groups.
It is time to:
The ssh-keygen command is part of OpenSSH authentication key utility and is readily available on most Linux distributions:
$ ssh-keygen
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.
The private key file should have read-only mode by the owner, set the right permission:
$ chmod 600 $HOME/keys/ditwl_kp_infradmin.pem
Key Pair creation in AWS (uploading, as it has already been created localy using ssh-keygen) is done with the aws_key_pair
Terraform Block.
Add the following block to the terraform-aws-tutorial.tf
created in previous sections.
For Security Group ditwl-sg-base-ec2
:
# Upload a Private Key Pair for SSH Instance Authentication resource "aws_key_pair" "ditwl-kp-config-user" { key_name = "ditwl-kp-config-user" public_key = file("~/keys/ditwl-kp-config-user-ecdsa.pub") }
Open a command line shell at the same location where the terraform-aws-tutorial.tf file is located, and, run the Terraform or OpenTofu plan, and apply the commands.
Run tofu plan
to generate and review the execution plan. Check each line and value to make sure that it corresponds to the desired change.
Terraform will refresh the state comparing it with the Cloud resources and produce a plan for the resources that need to be created, updated, or destroyed.
In the past section of the tutorial, some resources were commented out to reduce the infrastructure cost during development, as the Public Key don't have any dependency yet with the commented code, there is no need to uncomment.
Run the Terraform plan:
$ tofu plan aws_vpc.ditlw-vpc: Refreshing state... [id=vpc-0d9d5a25ebe999037] ... 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 = { + "cost_center" = "marketing-department" + "environment" = "pro" + "owner" = "IT Wonder Lab" } } Plan: 1 to add, 0 to change, 0 to destroy. ...
Run tofu apply
to generate and apply the execution plan. OpenTofu will generate a new plan and ask for confirmation before applying the changes. Review again the changes and answer yes or no to apply the changes in AWS.
$ tofu apply aws_vpc.ditlw-vpc: Refreshing state... [id=vpc-0d9d5a25ebe999037] ... 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 AAAAC3NzaC1lZDI1NTE5AAAAIA1CQW/T/mJrP+YWLg+l800+JYlPLNIHVFXRNy3zyZUh Demo IT Wonderl Lab SSH User" + tags_all = { + "cost_center" = "marketing-department" + "environment" = "pro" + "owner" = "IT Wonder Lab" } } 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 2s [id=ditwl-kp-config-user] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Review the result, it should be 1 (resource) added, 0 changed, 0 destroyed
.
Check that the Key Pair has been created in AWS Console.
Navigate to AWS Console: EC2 - Key Pairs.
There is no cost for creating or having Private Keys in AWS.
AWS doesn't allow regeneration of lost key pairs. If you lose the private key, you'll need to create a new key pair and update your instances accordingly. Authorized keys injection can be done by stoping the instance and mounting the EBS root volume in another instance to make changes in its file system.
Private key should be protected. Store it securely and avoid sharing it. It's crucial for accessing instances. AWS recommends using a password-protected, encrypted key store.
Yes, you can use the same key pair for multiple instances. It simplifies management, but be cautious about security implications and consider creating separate key pairs for different purposes and different environments ro reduce risk.
During the instance creation process, you can specify the key pair.
AWS Key Pairs and security groups serve different purposes. Key pairs are for instance access, while security groups control inbound and outbound traffic to instances. They complement each other for a secure setup.
This tutorial series is a work in progress and will have these sections:
AWS with Terraform: The Essential Guide: Sections
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?