Terraform Introduction and Basics with AWS

Today’s world is completely data-driven. Each encounter is a data point. The emails you send are managed by Google’s servers as data. Every interaction is a piece of data. However, as you may have noted, they are linked to the internet and not physically joined.  All of a company’s needs in terms of software as a service, platform as a service, and infrastructure as a service may be met by Cloud Computing. Nowadays, no one enjoys making software for each of their use cases, building platforms, or managing their own data center.

Steve Jobs said, and I quote, “I don’t need a hard disk in my computer, if I can get a server faster.” Carrying around those non-connected computers is byzantine by comparison. In this age of the cloud, Steve’s brilliance is obvious.

There are many software as a service (SaaS) providers nowadays, and many of them use cloud providers like Amazon Web Services, Microsoft Azure, Google Cloud Platform and others. However, the costs associated with maintaining such softwares will continue to rise indefinitely as their usage increases. The many services are each assumed to have their own infrastructure, including networks, virtual machines, databases, load balancers, and more. Not going to explain every nuance, but hopefully you get the gist. A large group of people would be needed to handle this. 

Following terraform, an entrant emerged. Terraform is an open-source infrastructure-as-code software solution that enables you to build, modify, and enhance your infrastructure in a reliable and consistent manner. Cloud LaaS resource provisioning, management, and modification became as easy as writing a single line of code.

What is Infrastructure as Code with Terraform?

Infrastructure as Code (IaC) tools let you control infrastructure with configuration files, optimal JSON (GUI). IaC allows you to develop, alter, and manage your infrastructure in a safe, consistent, and repeatable way.

HashiCorp makes Terraform, an infrastructure-as-code technology. It maintains your infrastructure’s lifespan and allows you to define resources and infrastructure in human-readable configuration files. Terraform is better than hand-managing infrastructure in various aspects.

  • Terraform supports multiple cloud platforms
  • Easy-to-read configuration language speeds up infrastructure coding
  • Terraform’s state lets you track resource changes during deployment
  • Allows safe collaboration on infrastructure by versioning configurations
  • It’s open-source

Terraform Basics

Getting Started with Terraform

What would you need? 

->Terraform CLI

-> AWS CLI

-> An Editor, preferably VS Code

-> Terraform VS Code Editor IDE

Installation on MacOS

Terraform Installation

Download Terraform MAC
Install CLI

Unzip the package

# Copy binary zip file to a folder

mkdir /Users/<YOUR-USER>/Documents/terraform-install

COPY Package to “terraform-install” folder

# Unzip

unzip <PACKAGE-NAME>

unzip terraform_0.14.3_darwin_amd64.zip

# Copy terraform binary to /usr/local/bin

echo $PATH

mv terraform /usr/local/bin

# Verify Version

terraform version

VS Code and Terraform Plugin Installation

Microsoft Visual Studio Code Editor
Hashicorp Terraform Plugin for VS Code

AWS CLI Installation 

# Install AWS CLI V2

curl “https://awscli.amazonaws.com/AWSCLIV2.pkg” -o “AWSCLIV2.pkg”

sudo installer -pkg AWSCLIV2.pkg -target /

which aws

aws –version

Configure AWS Credentials

aws configure

AWS Access Key ID [None]: AKIASUF7DEFKSIAWMZ7K

AWS Secret Access Key [None]: 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

Default region name [None]: us-east-1

Default output format [None]: json

# Verify if we are able list S3 buckets

aws sts get-caller-identity

Installation on Linux

Terraform Installation

Download Terraform MAC
Install CLI

VS Code and Terraform Plugin Installation

Microsoft Visual Studio Code Editor
Hashicorp Terraform Plugin for VS Code

AWS CLI Installation  and AWS Credentials

AWS CLI

Follow similar steps from macOS to configure AWS-CLI

Installation on Windows

Terraform Installation

Download Terraform
Install CLI

Unzip the package

Create new folder terraform-bins

Copy the terraform.exe to a terraform-bins

Set PATH in windows

VS Code and Terraform Plugin Installation

Microsoft Visual Studio Code Editor
Hashicorp Terraform Plugin for VS Code

AWS CLI Installation  and AWS Credentials

AWS CLI

Follow similar steps to configure AWS-CLI

Terraform Workflow and Commands

Terraform blocks can be very confusing. To make it simple to understand, we will cover terraform workflow and move right into some command basics. 

Command: terraform init

With this, the config directory, which stores all of the setup files, may be initialized. Basically, this is executed anytime a piece of code is added or removed from the configurations. The providers are downloaded at your command (basically AWS plugin in our case).

Command: terraform validate

Performs a syntax check and an integrity check on the configuration files to ensure they are valid. The term “internally consistent” refers to the fact that all resource changes have been checked. Attempting to delete an empty resource, for instance, should fail validation.

Command: terraform plan

This command creates an execution plan and notifies what all changes are likely to be made. 

Command: terraform apply

Apply is used to apply the configuration as the name suggests.

Command: terraform destroy

Used to destroy a configuration, and applies the change post user confirmation.

Demo Project to Create an EC2 machine using Terraform

With an understanding of what these commands perform, now write some code to build a VM in AWS, often known as EC2 or Elastic Cloud Compute. However, you must first meet the following requirements:

  1. There is an active VPC in the region
  2. AWs Credentials is working 

Let’s create our first terraform-manifests. You can use this sample code below.

# Terraform Settings Block

terraform {

  required_providers {

    aws = {

      source  = “hashicorp/aws”

      #version = “~> 3.21” # Optional but recommended in production

    }

  }

}

# Provider Block

provider “aws” {

  profile = “default” # AWS Credentials Profile configured on your local desktop terminal  $HOME/.aws/credentials

  region  = “us-east-1”

}

# Resource Block

resource “aws_instance” “ec2demo” {

  ami           = “ami-04d29b6f966df1537” # Amazon Linux in us-east-1, update as per your region

  instance_type = “t2.micro”

}

As you would see, Terraform employs three different blocks: the Settings block, the Provider block, and the Resource block. For the time being, we may ignore this and concentrate on the terraform init/validate/plan/apply/destroy command. In our subsequent blog, we’ll go into greater depth on this topic. 

The following is provided solely for your education: 

The cloud provider’s Terraform plug-in and the Terraform version are both specified in the settings block. It’s AWS for us. After declaring the resource in the resource block, we specify the cloud provider’s area in which the resource will be created in the provider’s block.

Command Execution

Step 1: Go to the location where you saved the manifest. The current working directory should be the same as the location of your Terraform manifests. Now let’s run terraform init. This would start the terraform and load the AWS HashiCorp plug-in. Along with it, a terraform.lock.hcl file is generated. It saves the version we’re using so that if there are any changes in the future, it can refer to it.

Step 2: At this point, we can run terraform validation. It will notify you if there is a problem with the file. Otherwise, a configuration valid message will be displayed on the screen.

Step 3: Now execute the terraform plan. This will print all of the resources that terraform will be producing as part of this project. The ‘+’ symbol indicates that it will create it, while the ‘-‘ sign indicates that it will modify it.

 

Step 4: Finally, run and apply terraform. This time, construct a plan and ask for yes or no confirmation. Choose yes – this will launch an ec2 instance.

Conclusion

A fundamental understanding of Terraform is now at your disposal. Declarative language makes it simple to define the exact system architecture you need to build. You can test your modifications and find bugs before releasing them with the plan command. You can maintain DRY and effective code with the help of variables, references and dependencies, which will be covered in subsequent blogs.

Remember, we have barely begun to scratch the surface. For how to manage Terraform state demonstrates, how Terraform remembers the infrastructure it has already built, and how it has far-reaching implications for the way you organize your Terraform code – stay tuned for the next Terraform series. 

 

 

Terraform developer toolkit: In-demand skills, learning resources, online courses, interview prep, books & more

Terraform is an infrastructure as a code tool that developers use to define the project resources both on the cloud or on-premise in human-readable configuration files. It makes it easy to reuse and share any code in a native cloud environment. More and more companies are using Terraform to manage the infrastructure and application lifecycle via a consistent workflow. As a DevOps engineer, learning Terraform gives you the skills to handle even the most low-level components of hosted applications like CPU, storage, and networking resources.

Here is a complete Terraform developer toolkit with a list of resources that help you learn, upskill, and prepare for the interviews.

1. Terraform’s Language (HCL): Also called Hashicorp Configuration Language, you must be familiar with the syntax to use Terraform. Here’s an example syntax: 

Terraform_command “provider_resource_name” “resource_name” {

“option_1”: “option_1”,

  “option_1”: “option_1”

}

When you understand the Terraform code’s basic structure, it becomes much easier to use Terraform. Any Terraform code block has four critical elements: Command, Provider Resource Name, and Options.

2. State: One of the most important concepts of Terraform is the State. As a client-based application, Terraform must be able to keep track of the resources that it creates. For this functionality, it uses the concept of state. You must know how to make a State JSON file and use it for resource optimization.

3. Dependency resolution: Creating a cloud infrastructure requires many resources that are created simultaneously. There is an overlapping dependency between these resources that need management. With Terraform, you can quickly identify which resources depend on each other to prepare a well-planned execution strategy. As a Terraform developer, you must know the concept of dependency resolution, which is extremely important to deploy resource updates in the correct order.

4. Infrastructure as Code: Any DevOps engineer will have to ensure that the systems they design are built in a repeatable manner using Infrastructure as Code. It is an essential skill because it is how you can document cloud objects as version-controlled code. You must learn the concepts of IaC to get better opportunities as a Terraform developer.

Top 35+ most asked Terraform interview questions and answers

28 real-time Terraform interview questions and answers

Top 40 Terraform interview questions and answers for 2022

11 most asked Terraform interview questions & answers [for freshers]

Top 100 Terraform interview questions with answers

4 great tips to stand out in a coding interview

Difficult interview questions & how to answer them

10 common questions to expect during your remote job interview

7 Common full-stack developer interview questions

7 Dos & don’ts for passing your technical interview

Official resources 

Terraform website

Terraform registry

Terraform tutorials

Terraform docs 

Terraform community

Online courses and tutorials for Terraform developers 

Hashicorp Certified — Terraform Associate

A course designed to make you a Terraform Associate, it is offered by Udemy. We recommend this online course for DevOps engineers who plan to implement Terraform in their organization. It covers all the Terraform modules and best practices in detail. This is the best course if you plan to learn the Infrastructure as Code approach.

Terraform for absolute beginners

For experienced developers, this 1-hour Coursera Terraform course is ideal. It is aimed at developers unfamiliar with Infrastructure as Code or who have not used Terraform before. This course covers Infrastructure as code concepts and ideas, Terraform basics and its execution flow, HCL language (Harshicorp Configuration Language System) syntax, and how to create Infrastructure using Terraform. Following the examples in the course, you will develop critical skills like DevOps, IT Automation, and Infrastructure as Code.

Terraform: From Beginner to Master with Examples in AWS

If you are an AWS developer planning to use Terraform for infrastructure deployment, this is the course for you. One distinctive quality of this course is its text-based interactive course. Implying you can practice right in the browser while learning Terraform. It is another excellent course to learn Terraform if you are a beginner. It elaborates on what challenges can be solved with Terraform in real-world applications. It covers all the critical features of Terraform, and as you don’t have to set up any local environment for practice, it’s much more user-friendly.

Books for Terraform developers 

Pipeline as Code: Continuous Delivery with Jenkins, Kubernetes, and Terraform

A book that teaches you how to automate your development pipeline in a cloud-native, service-driven world, Pipeline as Code is excellent for learning Terraform. It covers all essential concepts like CI/CD pipelines, best practices, and how to build reliable CI/CD pipelines for cloud-native applications using Terraform, and other modern tools.

Terraform: Up & Running

This hands-on book teaches you how to get up and running with Terraform fast. You will learn how to write production-grade Terraform modules and perform manual and automated testing for your code. This book also compares Terraform to Chef, CloudFormation, Puppet, Ansible, and SaltStack, so you better understand its features.

Patterns and Practices for Infrastructure as Code

This is a quick-start guide to getting started with Terraform in a cloud environment. The book begins with beginner’s concepts and moves on to features to manage Infrastructure at scale. It details advanced topics like state management, modules, and team collaboration on Terraform. As the book uses Python for Terraform, it is excellent for Python developers.

Online communities for Terraform developers 

Terraform on GitHub

Google Terraform YouTube Channel

Podcasts for Terraform developers

All About Terraform

Getting Started with Terraform on AWS with Cobus Bernard

Teamwork: DevOps teams work with both developers and operations teams. As part of a DevOps team, you should have a teamwork spirit. Learn to work well with other stakeholders and accommodate their ideas and requirements. Most successful teams are the ones that enable collaboration among members.

Patience: When working as a DevOps engineer, you must have patience. Not everyone will get your idea or the reason behind your decisions immediately. Other developers in your team might need more time to understand things. For this reason, you have to be patient. The operations team might be unable to understand how complex programming is or how long product update releases might take; for such reasons, you should anticipate the need for patience.

Open-mindedness: When you keep your mind open to new ideas, whether yours or someone else’s, you are more approachable and innovative. It would help if you took your time to understand the ideas presented to you before dismissing them. Exploring ideas is how you progress and find new ways to solve a challenge.

More resources on soft skill development:

5 Necessary soft skills for DevOps engineers

How soft skills transitioned to become the new power skills

4 key characteristics of a great software development team

Tips for good communication within a software development team

Conclusion 

Terraform is a vital tool in the native cloud software application environment. Adding Terraform to your skillset, you will be eligible to explore more challenging and better-paying DevOps engineer opportunities.

Talent500 is the platform for DevOps engineers in India to explore opportunities at global tech companies. Sign up here to join our elite pool of talent.