Open In App

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 Of SSH Key with Terraform

Steps To Create SSH Key Using Terraform

Step 1: Set Up Terraform

Step 2: Set Up AWS CLI

Step 3: Configure AWS CLI

aws configure



Step 4: Create Terraform Code

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.37.0"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-east-1"
}
resource "aws_iam_user_ssh_key" "user1_ssh" {
username = <YOUR USERNAME>
encoding = "SSH"
public_key = <YOUR SSH PUBLIC KEY>
}
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.37.0"
}
}
required_version = ">= 1.2.0"
}

provider "aws" {
region = "us-east-1"
}

resource "aws_iam_user_ssh_key" "user1_ssh" {
username = <YOUR USERNAME>
encoding = "SSH"
public_key = <YOUR PUBLIC SSH KEY>
}

Step 5: Apply The Terraform Code

terraform init



terrraform apply

Conclusion

We have successfully ssh key for iam user with the help of terraform in this article. The configuration described can be further modified to make changes to create other keys in aws. This is how terraform allows reusable and modifiable configuration of infrastructure.

How to create an SSH key in Terraform? – FAQ’s

Q. Why do I need an SSH key pair in AWS?

An SSH key pair is required to securely access and authenticate with AWS EC2 instances. The public key is added to the EC2 instance, while the private key is used for authentication when connecting to the instance.

Q. How can I create an SSH key pair in AWS using Terraform?

You can use Terraform’s aws_key_pair resource to create an SSH key pair in AWS. This resource generates the key pair and allows you to specify the key name.

Q. What are the required parameters for creating an SSH key pair in Terraform?

When creating an SSH key pair with Terraform, you typically need to specify the key_name parameter, which is the name of the key pair. Optionally, you can also specify the public_key parameter if you want to use a specific public key.

Q. Can I delete an SSH key pair created with Terraform?

Yes, you can delete an SSH key pair using Terraform by removing the corresponding aws_key_pair resource from your Terraform configuration and applying the changes.

Q. Can I automate the creation of SSH key pairs for multiple environments with Terraform?

Yes, Terraform allows you to automate the creation of SSH key pairs for multiple environments by defining the necessary resources in your Terraform configuration files and using variables to customize the key names.


Article Tags :