How To Create Key Pair In AWS Using Terraform ?
Last Updated :
02 Apr, 2024
In cloud infrastructure management, secure admittance to instances is central. While working with Amazon Web Services (AWS) utilizing Terraform, creating key pairs is fundamental for secure access to EC2 instances. Key pairs comprise of a public key and a private key, where the public key is utilized to encrypt data, and the private key is utilized to decrypt it.
This guide gives a step-by-step instructional exercise on the most proficient method to create key pairs in AWS utilizing Terraform. Terraform, infrastructure as a code tool, considers the declarative configuration of resources, making it ideal for managing cloud infrastructure in a reliable, scalable, and repeatable manner.
Primary Terminologies:
- Key Pair: A set of cryptographic keys containing a public key and a private key. Utilized for secure correspondence and verification. Key pairs are secure login information for your instances/virtual machines. To connect to the instances we use key pairs that contain a public key and a private key
- Private Key: A secret key that is safely put away and utilized for decoding information encoded with the comparing public key. It ought to never be imparted to any other individual.
- Public Key: A key that is openly dispersed and utilized for encrypting information. It is imparted to different gatherings to speak with the proprietor of the key pair safely.
- Amazon Web Services (AWS): AWS stands for Amazon Web Services. AWS is a platform that provides on-demand resources for hosting web services, storage, networking, databases, and other resources over the internet with a pay-as-you-go pricing. A far-reaching cloud computing platform given by Amazon, offering a great many services including computing power, storage, databases, and so on.
- EC2 (Elastic Compute Cloud): A web service given by AWS that permits clients to lease virtual PCs (instances) on which they can run their own applications.
- Terraform: Terraform is an open-source infrastructure as a code tool created by HashiCorp, utilized for building, changing, and forming infrastructure proficiently. It empowers users to define infrastructure in declarative configuration files.
What is meant by Key Pair?
A key pair is a set of cryptographic keys utilized for secure communication between systems. It normally comprises two parts: a public key and a private key.
- Public Key: The public key is shared freely and is utilized for encrypting data. Dispersed to different groups need to discuss safely with the proprietor of the key pair.
- Private Key: The private key is kept secret and safely put away by the owner. It is utilized for decrypting data that has been encrypted with the comparing public key. The private key should to never be imparted to any other individual.
Key pairs are normally utilized in different security protocols, like SSH (Secure Shell), SSL/TLS (Secure Socket Layer/Transport Layer Security), and digital signatures. With regards to AWS, key pairs are utilized for safely getting to EC2 instances, where the public key is utilized to encrypt login credentials, and the private key is utilized to decrypt them.
Step-by-step process to create key pair in AWS using Terraform
Step 1: Launch an Instance
Launch EC2 instance with Amazon Linux2 Kernel 5.10(AMI) along with port numbers set SSH – 22, HTTP 8o, select storage t2.micro and select existing security group.

Now connect with git bash or any terminal like Putty, PowerShell, visual studio code, and so on.

Step 2: Install Terraform
Now install terraform to our local machine by using following commands or go to official page of terraform and copy commands
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install terraform

Step 3: Create a file to create key pair
Create a file with " .tf " extension like <filename.tf>. Inside this file we are configuring our infrastructure with script
Provider section
In this provider section we are defining which region to mention
# Specify provider
provider "aws" {
region = "eu-west-1" # Change this to your desired region
}
Keypair Resource
In this Keypair resource section we defining keypair name and key pair path to store our key
# Define key pair resource
resource "aws_key_pair" "my_key_pair" {
key_name = "my-key-pair" # Name for your key pair
public_key = file("~/.ssh/id_rsa.pub") # Path to your public key file
}

Step 4: Generate Keys
In this step we are generating keys generation because our terraform infrastructure keypair need a path to store key ID
Default default path of public key is /home/ec2-user/.ssh/id_rsa.pub
Generate key_generation by using following command
ssh-keygen

with out this step we cannot create a key pair while executing terraform validate we face a error. Like shown in below figure

Step 5: Execute Terraform Commands
Now initialize terraform by using following command. When we execute this it automatically install some packages required to terraform
terraform init

Now execute terraform execution flow commands when we execute this commands terraform build a our infrastructure
terraform fmt
terraform validate
terraform plan

Now execute terraform apply command
terraform apply --auto-approve

Resources created after successfully terraform apply completed

Conclusion
By understanding how to create key pairs in AWS using Terraform is crucial for keeping up with secure access to cloud resources. By following the steps framed in this guide, users can successfully oversee cryptographic keys and ensure secure correspondence between systems inside their AWS infrastructure.
Key Pairs assume an imperative part in securing down access to EC2 instances, and Terraform gives a convenient method for automate the creation and the management of these key pairs. By utilizing Terraforms infrastructure as code capacities, users can define key pair resources in a declarative way, ensuring consistency and unwavering quality across their infrastructure deployments.
Besides, by integrating key pair creation into their Terraform work processes, clients can smooth out their infrastructure management processes and authorize security best practices reliably across their AWS environments.
Similar Reads
How To Create SQS In AWS Using Terraform ?
Amazon Simple Queue Service (SQS) is a completely managed message queuing service provided by AWS, offering scalable and reliable message conveyance between distributed parts of an application. It fills in as a fundamental building block for building event driven, microservice-based models, empoweri
8 min read
How To Create ECR Repository In AWS Using Terraform ?
In a cloud computing and microservice world, we must concentrate on the involvement of the infrastructure resources properly. With Terraform, an open source IaC (infrastructure as code) tool that is widely used for provisioning and managing cloud resources across many cloud service providers such as
9 min read
How To Create AWS IAM Roles Using Terraform?
Terraform is an IAAC tool which is used provision infrastructure . Here in this guide i will first discuss what is terraform . Then i will discuss what is IAM Role and in which scenarios we should use IAM Role . Then i will walk you through the different steps to create an IAM Role for an EC2 servic
5 min read
How To Create Elastic IP In AWS Using Terraform ?
Using Terraform, creating an Elastic IP (EIP) on AWS entails specifying the resources required in a Terraform configuration file in order to create the EIP. A static IPv4 address intended for dynamic cloud computing is called an elastic IP. It is helpful in situations when you require a public IP ad
4 min read
How To Create SNS Topic In AWS In Using Terraform
Amazon Simple Notification Service (SNS) is a fully managed messaging service given by Amazon Web Services (AWS), offering a versatile and reliable solution for sending notices and messages to different endpoints or subscribers. SNS points act as correspondence channels to which messages can be dist
6 min read
How To Create An SSH key In Terraform ?
AWS SSH keys are private secret keys used for various access related things in AWS. These can be used for resources such as EC2 instances, IAM accounts. etc. Terraform can be used for easy and direct creation of SSH key in AWS. Let's see how we can create SSH Key using Terraform. Primary Components
4 min read
How To Create AWS VPC Using Terraform ?
Terraform is an IAAC tool used to automate programmatic infrastructure provisioning. Here in this guide, I will first discuss what is AWS VPC. Then I will discuss terraform. After this, I will walk you through the different steps to write a code using Terraform to create a custom AWS VPC using subne
6 min read
How to Create AWS EC2 using Terraform?
AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, cl
13 min read
How To Create AWS Route 53 Using Terraform ?
DNS In the present cloud-based infrastructure conditions, managing DNS (Domain Name System) configurations is vital for coordinating traffic effectively across different services and resources. AWS Route 53 stands apart as a highly versatile and dependable DNS web service given by Amazon Web Service
7 min read
How To Create AWS VPN Using Terraform?
As associations embrace cloud computing for their Infrastructure needs, the secure and effective association between on-premises organizations and cloud assets becomes pivotal. In the domain of cloud-based DevOps, a Virtual Private Network (VPN) fills in as a fundamental component for laying out sec
6 min read