Terraform for AWS

Prakriti Mandal
8 min readSep 22, 2023

An innovative tool to optimize the utilization of several services on various platforms like azure, aws, gcp, has enriched the power of automation to create a cost-effective, high-performance and resilient infrastructure for the production of servers in industry-level architecture.

In this blog, we are going to focus only on AWS-related✨ infra. So, without a further a do let’s get started.

To begin with, AWS (Amazon Web Services) is a ☁️ cloud public provider that provides innumerable services to deploy a webserver or more on demand. But in order to do that people have to go to the AWS console and engage themselves in handling the virtual machines, networks, storage, and more. In order to reduce the effort and time, terraform as an IaC (infrastructure as a code) tool helps in defining and provisioning the infra resources and destroying it as well by writing it in the code editor and deploying them in simple commands like

— ⚡— →>> terraform init, terraform apply and terraform destroy <<← —⚡ —

Terraform is an Opensource infrastructure as a code tool developed by HashiCorp. This allows us to describe the desired infrastructure configuration in HCL (HashiCorp Configuration Language). Several other providers are supported by terraform like GCP, Azure, Kubernetes etc. A user only needs to know the extended functions in order to create a server. He has to specify the desired state for the services to run, not the step-by-step procedure to provision. Therefore, terraform provides a declarative configuration to manage services in providers.

N.B.- The terraform code is saved in the file that ends with .tf extension.

In order to create the entire infrastructure, the aws cli needs to be configured with proper aws credentials. The credentials include the aws access key and aws secret access key. Please go through the resource below to learn more about the aws cli and configure it in your machine.

Terraform Init⚡

With this terraform init command, we initialize the code written after the desired infra has been coded. This usually downloads the plugins and modules related to the providers to be used while creating the aws resources. The plugins help in interacting with the providers. It creates a blank statefile to preserve the execution plan.

This results in an error, when the code written has any typos in the resources declared, any connection problem with aws, or credentials present to connect to aws is wrong. Whenever any new code is added, terraform init has to run.

Terraform Apply⚡

Whenever the terraform init finishes initializing the infra code, we are safe to run the holy terraform apply command. It creates the whole infrastructure in a few seconds, seamlessly. It enriches the statefile for the entire infrastructure. The file contents are preserved in json(javascript object notation) format and are present in terraform.tfstate.

It contains all the essential information that is created during the terraform apply command. It's related to all the services that have been created for deploying the desired system. After the terraform apply have been commenced, it asks for another last approval, where we need to give a yes. Though, we can directly command terraform apply -auto-approve, to eliminate the step. I prefer to use the command even without executing the terraform plan.

Terraform Plan⚡

terraform plan is a command used to preview the changes that Terraform intends to make to your infrastructure before actually applying those changes. It performs a dry run of your Terraform configuration and displays a summary of what actions Terraform will take, such as creating, updating, or destroying resources. This creates the execution plan which needs to be established after the terraform apply has been executed.

How to write a aws terraform structure code

To begin with, we need to declare the provider first. The provider to be named after the platform we are going to use to create the infra resources.

We are allowed to declare other stuff like region, access key, secret access key. But Terraform authority warns not to include hard-coded credentials in its configurations, which may lead to leakage and security vulnerability.

The resource block in the configuration depicts the services to be used to meet the desired state.

The resources may be an ec2-instance, subnets, vpc, elastic ips, internet gateway and many more. First we declare the resource name in double quotes and then we put the name in the same format.

We are allowed to configure the entire infra in the same file, but it may create a mess afterwards, so to avoid such confusion we compose them in separate directories and files. Terraform will recognize the files present in the respected directory and will create the state file.

We create variables in a separate file with variable.tf and declare the variables in a file known as terraform.tfvars.

If we take the example of ec2-instance, we specify the ami, region, instance type in the resource, we initialize the values in variable.tf and declare them in terraform.tfvars.

Demo

Let's create an ec2-instance with a security group,

At first we, move to provider

Since we are using aws, we select the same one and depict the region where we are going to create the instance. We initiate the region in variable.tf file.

Now about the instance, we declare the resource i.e., aws_instance for an ec2-instance. Then the type, here we use t2.micro, depending on the use case people can define other types like t2.large, t2.xlarge etc. Here the objects to be written in string formats.

We can write the access key and secret access key to access the aws cli.

Then we go for the private key pair i.e., to be named after an existing key or we can generate rsa keys by the command ssh-keygen -t rsa. Here we keep a line reserve for security groups in format [“${security-group-resource.security-group-name.name}”] . This part fetch security group name from terraform.tfstate file (mentioned above).

Now we get into, security group. It contains an ingress named object which allows traffic to get to server to access the specific protocol. We can write any port depending on the protocol.

Now in the variable section(variable.tf), we initialize the ami to be used to create the instance and the region where the instance is going to be established.

Now, we declare the ami and region in terraform.tfvars.

The file structure may be the same as given below until you add any backend to store the state of the present code after the apply command. Anyway, we are going to cover this in its sequel.

We are going to write another line of code in output format to get the IP address after the instance has successfully run.

After that, we commence with terraform init command. Once the init has been successfully initiated we will move forward to terraform apply.

We need to approve the resources to be created after the confirmation. As you can see it only accepts yes, if you want to stop either at the instant I would refer Ctrl + c command.

It forwards you the below line with 2 resources that have been created i.e., a security group and ec2-instance. If you are worrying about other related resources like subnets, vpc, internet gateway, these are set to default. It also gives you the IP address that I missed somehow.

The file structure will be restructured as per the one given below. You will get the terraform.tfstate, the Hashicorp Configuration Language(hcl) related items and other materials.

Now we login into the instance. Let's move to the directory where our public key is present, in my case, it is present in the Downloads folder. We use ssh protocol to log into the instance which is why we declared port 22 in the security group of the instance but we referred to it as TCP protocol, its okay in any case.

The command to get the instance in the cmd is ssh -i “your-keypair-name.pem” ec2-user@ip_address, for ubuntu, we use ubuntu in place of ec2-user as a user.

We have created an instance and it’s a click away in your command line to be used. We have reached the end of the blog, we can destroy both of the resources by entering the terraform destroy and approve it like before when apply command has been executed. It is so easy and handy that you don’t even have to go to the AWS console and seek all the resources when you have a plenty of them to terminate.

I hope you have learned to build a basic automated infra. If the blog helps persuade you up to learn more about terraform stuffs, follow me here for more and give a clap. Thanks for coming to this end, let's recap in its sequel.

Keep learning, keep growing, have a beautiful day🙏🏻.

--

--

Prakriti Mandal

DevOps enthusiast believe in learning by contributing.