Developed by Hashicorp, Terraform is an open-source tool that is used to provision and manage resources across both public and private clouds in a safe and efficient manner. Terraform is considered as Infrastructure as a Code (IaaC) and is used to manage infrastructure on popular cloud platforms such as AWS, GCP, and Open Shift. In this guide, we demonstrate how to deploy AWS EC2 instance using Terraform.
Step 1: Install Terraform
To start off, we are going to install Terraform. Terraform is distribution-agnostic and can be installed in the same way across various Linux flavors. In this guide, we will install it on CentOS 8.
First, download the terraform zipped folder as shown:
$ wget https://releases.hashicorp.com/terraform/0.14.8/terraform_0.14.8_linux_amd64.zip
Next, unzip the directory to the /usr/local/bin directory.
$ sudo unzip terraform_0.14.8_linux_amd64.zip -d /usr/local/bin
And that’s it. To check the version of Terraform installed, run the command:
$ terraform --version
Step 2: Deploy AWS EC2 instance using Terraform
With Terraform in place, now we are going to deploy an ec2 instance on AWS. An ec2 instance is AWS’s cloud server with compute resources such as CPU, RAM and hard drive.
First, create a directory from which you will place your configuration file.
$ mkdir aws_dir && cd aws_dir
Next, create a Terraform file with a .tf file extension as shown.
$ sudo vim terraform_config.tf
Inside the file, we will define the following:
1) Name of the cloud provider – In this case , AWS
2) Access and secret keys – You can get this information by heading over to the IAM section of your AWS account. Click on ‘My Access key’.
3) Region – This is the region where the ec2 instance will be deployed. For our case, we have defined us-east-2.
4) ami – This is the Amazon Machine Image ID. This is the Unique ID for the e2-instance.
This is how our configuration file will look.
Specify the access & secret keys and region provider "aws" { access_key = "Your-own-access-key" secret_key = "Your-own-secret-key" region = "us-east-2" } Specify details of the ec2 instance resource "aws_instance" "instance1" { ami = "ami-0dd9f0e7df0f0a138" instance_type = "t2.micro" tags = { Name = "instance name" } }
Save and exit the configuration file.
To start using Terraform, run the command below. This initializes Terraform on your system.
$ terraform init
To simulate how the file will be executed, run the command below. Note that this is simply a dry run and no action will be taken
$ terraform plan
Lastly, to deploy the AWS EC2 instance using Terraform, execute the command:
$ terraform plan
When prompted, type ‘yes’ to proceed. the instance creation will begin shortly as seen below.
Now, head over to your AWS account and observe that the ec2 is up. and running.
This concludes our guide today. We hope you found this useful.