How to Create EC2 Instance using Terraform with Key Pair on AWS

How to Create EC2 Instance using Terraform with Key Pair on AWS

How to Create EC2 Instance using Terraform with Key Pair on AWS

In my previous articles, you have seen how to launch an EC2 instance in AWS using different ways. Such as-

In this post, you’ll learn how to create EC2 instance using terraform with key pair on AWS. So are you ready?

Don’t want to miss any posts from us? join us on our Facebook group, and follow us on Facebook, Twitter, LinkedIn, and Instagram. You can also subscribe to our newsletter below to not miss any updates from us.

What is EC2 and Why Create it using Terraform?

Amazon EC2 or Elastic Compute Cloud is a service that provides scalable compute capacity in the cloud. In simple words, it’s a virtual machine similar to an actual server and you can use it to deploy your application.

You can literally get started with EC2 in minutes using AWS Management Console. However, it’s far from the ideal scenario. Creating one server manually is okay, but imagine if you need to create hundreds of servers with the same configuration. Do you think you can do it correctly without any mistakes?

Seems tough 🙁

That’s where IaC tools come into the picture. Tools like Terraform helps you create an infrastructure in an automated way that can be repeated you create the same infrastructure as many time as you want.

Read: Ways in Which You can Create and Manage AWS Resources

Why Create an EC2 Instance with Key Pair?

First of all, you might be thinking what is a key pair?

Key Pair = Public Key + Private Key

The public key is used to encrypt and the private key to decrypt the data.

When you create an EC2 instance and you know you will be doing SSH into your instance using an SSH client. You provide a keypair so that you can use it later to connect to your instance. A key pair is a security credential that you use while connecting to your EC2 instance.

So if you will be connecting to your EC2 instance from your local machine, consider using a key pair. Otherwise, there are other ways to connect your system and it’s absolutely okay for you to skip adding a key pair to your instance.

Alright !!!

Let’s go ahead and see how to create EC2 instance using terraform with key pair on AWS.

Prerequisite

Assumption: Before you use this tutorial to create a key pair using terraform, you should know how to create a resource on AWS using terraform. If you are a beginner I highly recommend you to read my previous post on Getting Started With Terraform on AWS In Right Way. Once you have read the post, you are ready to move ahead with this post further.

Steps to Create EC2 Instance using Terraform with Key Pair on AWS

  1. Declare the Provider
  2. Create a Key Pair
  3. Create an EC2 instance using Key Pair

Step 1: Declare the Provider

Before you use terraform to provision your resource, you need to tell it which cloud provider you will be working with. Additionally, you tell terraform how you will be authenticating with the said cloud provider.

As we’ll be working with AWS, here is our provider declaration section and authentication section-

#Provider Declaration
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

#Authentication Information 
provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

As you can see, we’ll be working with the AWS provider. We have provided authentication details as AWS CLI default profile. Also, we have specified the region in which we would like terraform to create my resources.

We are ready with the boilerplate code. Let’s see how to create a key pair.

Step 2: Create a Key Pair

Before you can create an EC2 instance with key pair, you will need a key pair. This section talks about how to create EC2 key pair using terraform.

In the previous post on creating EC2 key pair using terraform, I covered extensively how you can create a key pair. I will sum it up for reference here. You can create an SSH key and use the public key part to create a key pair on AWS as shown below.

Create an SSH key using the command-

ssh-keygen -t rsa -b 4096

ssh-keygen is the command that will generate an SSH key for you. We are using the -t option to specify the algorithm that we want it to use. -b option says the size of the key. We have chosen 4096 as it is considered strong enough.

Once done, you will have a private and public key file with you, Copy the content of the public key file and use that to create your key pair in AWS as shown below.

#Resource to Create Key Pair
resource "aws_key_pair" "demo_key_pair" {
  key_name   = var.key_pair_name
  public_key = var.public_key
}

You might be thinking it’s a manual step to create an SSH key outside terraform and you can instead do it using tls_private_key resource. Well, you are 100% right. But it’s not recommended at all as your private key will lie in your state file unencrypted.

Step 3: Create an EC2 Instance using Key Pair

Once done, you can create an EC2 instance using the key pair.

#Example Instance Creation using Key Pair
resource "aws_instance" "demo-instance" {
  ami           = "ami-06489866022e12a14"
  instance_type = "t2.micro"
  key_name      = aws_key_pair.demo_key_pair.key_name
}

As you can see, you can use aws_instance resource to create an EC2 instance. I have specified the minimum set of parameters to create an instance above. Which are ami and instance_type. You can see all the other attributes you can specify in the official documentation.

Also, we have specified key_name to specify the name of the key pair to attach to the instance. We are retrieving the name from the aws_key_pair resource we just created.

Final Configuration File to Create an EC2 instance with Key Pair on AWS using Terraform:

Here is what the final configuration file looks like.

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

#Variable Declaration
variable "key_pair_name" {
  type    = string
  default = "demokeypair"
}
#Variable Declaration
variable "public_key" {
  type    = string
  default = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQD3BVBp88VgmeWU0ERBBP0C0wIvC9iaFuvOrwwU01EF13e2wjT7XQ8aIvj3CvvVXvoFK5rbms+i2Ky6F0okAS/M+il2PJgKfSUZuKiLUgr652NTADyBTxmDiMCVg/ytT/oBWxW8EF0Iu8cHkjxr1a+gIxQAZV3AgAsCVhs7gYdT5n28gZncYdCfuUp2+dAe9QvJ6RkBSy/ObaC7WrnXI/ld6BsZNJeLVpOzPjbgbRgmMOXKX87vERdi0vQ64QW7DnE/AjhR4SZ8GWxsty8sJvcuvzX2QOA5TUFtteuFE0rqFjXXCwzuysveXYwHqphs0d6LneHkRDj23ChGKaha8pLvharjq8DUtlVZ3UCBRbsT4/joeM/S71LANkhnatqTsIISP+Sg8MCt21oABvQLAcTV0j/OuDH3h+iPavkm5/Ehjkhkgkg+z/niiEOTAfYfB0X9jqmx9r1a+iOoiPc4NBOVBWxBzq718G6xt1rEXwfmOQol0LI+mVGRBmMLgPGBvniXQv04rQqhQmRvkXHDj8nlXhNoaoXMR0pzvFuxRq/AZnCbaDRRWbEbmUREWLNFB+ZPa0qSMIBH1u8+3p3TxOumnQWw3TxRtSVfTwIPuxjFNyjCe4SyEh90aEK5P/IAPhe9x+O435Z+Es9331Q== preeti@ExampleMachine"
}

#Resource to Create Key Pair
resource "aws_key_pair" "demo_key_pair" {
  key_name   = var.key_pair_name
  public_key = var.public_key
}

resource "aws_instance" "demo-instance" {
  ami           = "ami-06489866022e12a14"
  instance_type = "t2.micro"
  key_name      = aws_key_pair.demo_key_pair.key_name
}

Once we have the final configuration file, create a terraform file main.tf and paste the content of it. Make sure to generate your own SSH key and replace the value of the public key with your own. The one mentioned over here is a dummy one. Also depending on your region, you need to provide the AMI Id that will be used to create an instance.

You can get the AMI Id from the console. Try creating an instance, choose an AMI and see the Id of the AMI and use it. Once you have replaced all variables and you are ready to create an instance-

Then run the below set of commands.

terraform init - To initialize project directory with AWS specific plugins
terraform plan- To see what is being created
terraform apply- To actually create resource to AWS
terraform destroy- To delete/detroy the created resource

Once you run terraform apply, your key pair and EC2 instance get created.

Ec2 creation

How to Create an EC2 Instance using Existing Key Pair using Terraform

If you have already created a key pair on AWS, then all you need to do is specify the key pair name while creating an EC2 instance. And you should be good to go.

Make sure that you have the private key of the key pair you are specifying handy with you. Otherwise, you won’t be able to connect to your instance from your local system.

Using an existing key pair looks as simple as-

#Variable Declaration
variable "already_created_key_pair_name" {
  type    = string
  default = "demokeypair"
}

resource "aws_instance" "demo-instance" {
  ami           = "ami-06489866022e12a14"
  instance_type = "t2.micro"
  key_name      = var.already_created_key_pair_name
}

Step 5: Clean up

If you are creating this Key Pair for learning purposes, you can go ahead and delete your key pair

Simply run terraform destroy and it will delete all that you created using main.tf.

Happy Learning !!!

Note: Use terraform destroy with caution. As it deletes whatever you created. So make sure intend to do so.

Conclusion

In this post, you learnt how to create EC2 instance using Terraform with key pair on AWS

  • We saw how to create an EC2 key pair using terraform
  • Created an EC2 instance using the created key pair
  • We also saw how to use an existing key pair while creating an EC2 instance

I hope you found this post helpful. Please let me know in the comment section.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on
  • Subscribe to our newsletter to get notified each time we post new content
  • Share this post with your friends

Leave a Reply

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