Terraform 101 - Inception to Mastering Terraform - Part 1
A guide to terraform.

Terraform 101 - Inception to Mastering Terraform - Part 1


Introduction to Terraform

Terraform stands tall as an open-source IaC tool, serving as the architect of modern infrastructure management. Its essence lies in crafting deployable resources for cloud environments with utmost clarity and efficiency, transcending the constraints of a single cloud provider.

Back in the mists of 2011, with the advent of AWS CloudFormation, the seed of Terraform was sown. Recognizing the need for a cloud-agnostic solution, the creators embarked on a journey to birth Terraform. The initial lines of Golang code were etched in July 2014, paving the way for version 0.1, initially supporting AWS and DigitalOcean.


Decoding Terraform's Language

Central to Terraform's prowess is the HashiCorp Configuration Language (HCL). Crafted with finesse, it seamlessly balances human readability with machine intelligence. Its native syntax beckons developers into a world of clarity and simplicity, while its JSON variant ensures interoperability and automation.

read more about it here

Unraveling the Terraform Workflow

The core of Terraform's modus operandi unfurls in three distinct steps:

  1. Write: Herein lies the genesis of your infrastructure blueprint.
  2. Plan: A pivotal phase where Terraform previews changes, allowing for meticulous refinement and iteration.
  3. Apply: The moment of truth, where Terraform materializes your vision into tangible infrastructure, updating the state file for future reference.

One other command that you will need to know is: "terraform destroy", which looks at recorded, stored state file created during deployment and destroys all resources created, it is a non-reversible command so it should be used with caution.

Terraform Init

Initiating a Terraform project is akin to laying the cornerstone of a digital edifice. A simple command, "terraform init", ignites the journey, fetching modules, configuring the backend, and setting the stage for transformative creations. Remember, every action in Terraform hinges on this foundational step, ensuring a robust and reliable deployment process.

When initializing the working directory two files appear alongside the Terraform configuration files :

  • .terraform: a hidden directory, used to manage cached provider plugins and modules, a record of active workspace, and a record of backend configuration
  • State data file, if the configuration uses the default local backend. This is managed by Terraform in a terraform.tfstate file (if the directory only uses the default workspace) or a terraform.tfstate.d directory (if the directory uses multiple workspaces).


Terraform Configuration

At the heart of every Terraform endeavor lies the configuration. A snippet akin to a masterstroke, defining providers and their configurations, orchestrates the symphony of infrastructure deployment. Whether it's provisioning resources on AWS or orchestrating cloud-native marvels, Terraform's configuration unfurls a canvas for innovation.

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

in the above configuration, the word provider is a reserved keyword that fetches whatever provider is following the keyword which in this case is aws, and between braces, we have the config parameters that help to define the arguments of the AWS provider. The configuration parameters will vary depending on the used provider.

Terraform's Terrain - Resource

The hallmark of Terraform's prowess is its ability to sculpt resources with finesse. Whether it's the humble EC2 instance or the intricate web of networking components, Terraform empowers you to craft with precision. Dive into the code, sculpt your dreams, and let Terraform weave them into reality.

Resources are a component of your infrastructure. It might be some low-level component such as a physical server, virtual machine, or container. Or it can be a higher-level component such as an email provider, DNS record, or database provider. Let’s look at the example below which deploys an AWS ec2 instance:

resource "aws_instance" "example" {
ami = "ami-0123456789abcdef0" # Change the AMI   
instance_type = "t2.micro" 
}        

resource is a reserved keyword that tells Terraform to consider the blocks as a resource block "aws_instance" is a resource provider by AWS, managed by HashiCorp.


When Terraform runs, it will first install the AWS provider. Then, it will use the aws provider to create the virtual machine.

Here are some other examples of providers:

azurerm - for Azure

google - for Google Cloud Platform

kubernetes - for Kubernetes

openstack - for OpenStack

vsphere - for VMware vSphere


There are many other providers available, and new ones are being added all the time. Providers are an essential part of Terraform. They allow Terraform to interact with a wide variety of cloud providers and other APIs. This makes Terraform a very versatile tool that can be used to manage a wide variety of infrastructure.

Terraform's Terrain - Data

Another block you need to know about in Terraform is the data source block, The main difference between a data source block and a resource block is that a data source block fetches and tracks details of an already existing resource, whereas a resource block creates a resource from scratch, look at the following example which stores id information about an already deployed VM:

data "aws_instance" "apache-server" {
instance_id = "some-random-id"
}        

Resource Addressing

Let’s imagine a scenario where you need to call the deployed ec2 instance, you can do that by specifying the resource type which is aws_instance then separated by a dot with the user's arbitrary given name. So in the scenario above, we can reference the resource with aws_instance.web . The same process goes for data source blocks.

It’s recommended that if you want to reference a property of a resource inside of the same resource use self attribute.

resource "aws_instance" "webserver" { 
  ami = data.aws_ssm_parameter.webserver-ami.value 
  instance_type = "t3.micro" 
  key_name = aws_key_pair.webserver-key.key_name 
  associate_public_ip_address = true 
  vpc_security_group_ids = [aws_security_group.sg.id]                                                          subnet_id = aws_subnet.subnet.id 

provisioner "remote-exec" { 
  inline = [ 
"sudo yum -y install httpd && sudo systemctl start httpd", "echo '<h1><center>My Website via Terraform Version 1</center></h1>' > index.html", 
"sudo mv index.html /var/www/html/" 
] 

  connection { 
    type = "ssh" 
    user = "ec2-user" 
    private_key = file("~/.ssh/id_rsa") 
    host = self.public_ip 
     } 
   } 
  tags = { 
   Name = "webserver" 
   }
}        


As we journey through the realms of Terraform, remember, that it's not just about provisioning resources; it's about sculpting the future of infrastructure. With Terraform as our guide, let's embark on a voyage of innovation, embracing the ethos of Infrastructure as Code with fervor and finesse.


Thanks for the read.

Follow for upcoming part of the Terraform learning journey.


要查看或添加评论,请登录

Maharshi Dutta的更多文章

社区洞察

其他会员也浏览了