Terraweek Day 1: Introduction to Terraform and Terraform Basics
What is Terraform and how can it help you manage infrastructure as code?
Terraform is an open-source infrastructure as code (IaC) tool developed by HashiCorp. It enables you to define and provision infrastructure resources across various cloud providers and other infrastructure platforms using a declarative configuration language.
With Terraform, you can describe your desired infrastructure state in a Terraform configuration file, which is typically written in HashiCorp Configuration Language (HCL) or JSON. This configuration file specifies the resources you want to create, their properties, dependencies, and any other necessary configurations.
Here's how Terraform helps you manage infrastructure as code:
Declarative Syntax: Terraform uses a declarative syntax, meaning you describe the desired end-state of your infrastructure rather than scripting out the individual steps to achieve that state. This approach allows Terraform to determine the actions required to reach the desired state.
Infrastructure Provisioning: Terraform can provision infrastructure resources such as virtual machines, networks, storage, load balancers, and DNS records across various cloud providers like AWS, Azure, Google Cloud, and more. It abstracts away the provider-specific APIs and handles the complexity of resource creation.
Dependency Management: Terraform automatically manages dependencies between resources. It understands the relationships between resources defined in the configuration file and provisions them in the correct order. For example, if you create a virtual machine that depends on a specific network, Terraform ensures that the network is created first.
State Management: Terraform maintains a state file that tracks the current state of your infrastructure. It keeps track of the resources it has created, their properties, and any metadata associated with them. This state file allows Terraform to determine the changes needed to transition from the current state to the desired state and helps in ensuring idempotent executions.
Infrastructure as Code (IaC): By using Terraform, you treat your infrastructure as code. This means that infrastructure provisioning becomes reproducible, version-controlled, and auditable. You can share and collaborate on the infrastructure code, apply software engineering practices, and leverage the benefits of source code management systems.
Extensibility: Terraform has a large and active community that contributes to a vast ecosystem of providers and modules. You can extend Terraform's functionality by using community-contributed modules or developing custom providers for your unique requirements.
Automation and CI/CD Integration: Terraform can be integrated into your CI/CD pipelines, allowing for automated infrastructure deployments. This ensures that your infrastructure evolves alongside your application code, making deployments consistent and reliable.
Immutable Infrastructure: Terraform encourages the concept of immutable infrastructure, where infrastructure resources are created and replaced rather than modified in place. This promotes consistency, reliability, and easier rollbacks by ensuring that infrastructure changes are always applied through the creation of new resources rather than modifying existing ones.
Plan and Apply: The "terraform plan" command generates an execution plan that shows the changes Terraform will make to reach the desired state. It displays the creation, modification, or deletion of resources. The "terraform apply" command applies the changes and provisions or updates the infrastructure accordingly. This separation of planning and applying allows for the review and validation of changes before they are executed.
Why do we need Terraform and how does it simplify infrastructure provisioning?
Managing infrastructure manually is prone to human errors, is time-consuming, and lacks consistency. This is where Terraform comes to the rescue! Here’s why we need Terraform and how it simplifies infrastructure provisioning:
Declarative Configuration: Terraform uses simple and readable language to describe your infrastructure requirements. Instead of worrying about the specific steps to create each resource, you can focus on what you want your infrastructure to look like. It’s like telling
Terraform your wish, and it grants it to you!Automation Made Easy: With Terraform, you can automate the provisioning and management of your infrastructure. That means you can sit back and relax while Terraform does the heavy lifting for you. It’s like having a robot friend who follows your instructions flawlessly.
Multi-Cloud Magic: Want to use multiple cloud providers like AWS, Azure, or Google Cloud?
No problem! Terraform supports various cloud platforms, making it a breeze to manage resources across different providers. It’s like having a universal remote control for your infrastructure.Infrastructure as Code: With Terraform, you can treat your infrastructure as code, just like you would with a cool video game.
You write your infrastructure specifications in code, which brings a bunch of benefits. You can version control your code, collaborate
with others, and reuse code snippets.Provider Abstraction: Terraform provides a consistent interface to interact with various cloud providers and infrastructure platforms. It abstracts away the provider-specific APIs and details, allowing you to use a unified configuration language for provisioning resources across different environments. This simplifies the learning curve and reduces the effort required to work with multiple providers.
Dependency Management: Terraform automatically manages dependencies between resources. It analyzes the resource graph defined in your configuration and determines the correct order in which resources should be provisioned. This eliminates the need for manual tracking and ensures that resources are created or modified in a way that satisfies their dependencies.
How can you install Terraform and set up the environment for AWS, Azure, or GCP?
To start with, firstly we need to download, install and setup Terraform by following the link 📌 Terraform Install
Once setup is done, you can simply check the Terraform version as
terraform --version
By default Terraform stores state in a local file named “terraform.tfstate”, but it can also be stored remotely, which works better in a team environment.
Configure Google Cloud Platform (GCP) :
Log in to the Google Cloud Platform and create a new project https://console.cloud.google.com
Create an IAM Service Account for Terraform to use and select IAM & Admin > Service Accounts > Create Service Account
Enter a name for the service account Set the role as Service Account Admin
Create a JSON key Check the key has been downloaded to your computer Copy the JSON file to the CentOS Server, for ease of use save it “below” your project folder
Now we can write the connections.tf file to “connect” to GCP.
Configure Azure:
Create an Azure account if you do not have one already.
Create a service principal with the necessary permissions to access and manipulate your Azure resources.
Note down the Azure subscription ID, client ID (also known as application ID), client secret (also known as password), and tenant ID.
Export the Azure subscription ID, client ID, client secret, and tenant ID as environment variables. For Linux and macOS, you can do this by adding the following lines to your .bashrc or .bash_profile file, replacing the values with your own subscription ID, client ID, client secret, and tenant ID:
export ARM_SUBSCRIPTION_ID="your_subscription_id" export ARM_CLIENT_ID="your_client_id" export ARM_CLIENT_SECRET="your_client_secret" export ARM_TENANT_ID="your_tenant_id"
Configure AWS :
Create an AWS account, log in to AWS CLI AWS LINK
Configure the AWS CLI with your AWS access key and secret access key credentials that allow you to create resources.
To use your IAM credentials to authenticate the Terraform AWS provider, set the
AWS_ACCESS_KEY_ID
environment variable and set secret_key
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
- Now make a directory for terraform "mkdir terraform_practice" and create a file name "vi aws_provider.tf" inside it
# inform terraform to fetch the aws plugin with version greater than 5
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
create another file named "vi main.tf" and paste the below code
#intializing aws provider
provider "aws" {
# below mentioned region is N-virgina
region = "us-east-1"
}
- Initializing terraform using
terraform init
command
# install the plugins and modules
terraform init
# to see what terraform will do
terraform plan
After configuration, run terraform apply
to create or modify your cloud resources based on your code.
Cleanup:
When you're done, use
terraform destroy
the resources created by Terraform.Explain the important terminologies of Terraform with the example at least (5 crucial terminologies).
Providers:
A provider in Terraform is a plugin that enables interaction with an API. This includes Cloud providers and Software-as-a-service providers. The providers are specified in the Terraform configuration code. They tell Terraform which services it needs to interact with. There are hundreds of available providers that can be used with Terraform, making it a hugely versatile tool.
Providers maintained by Hashicorp and providers are released independently from Terraform itself with each version providing additional features and bug fixes.
Once a provider is specified, each provider makes a list of
resources
anddata
types available for use in the Terraform code.provider "aws" { region = "us-east-1" }
Resources:
A container for other content in Terraform's configuration language. Blocks represent the configuration of objects like resources. For example, the
resource
block is used to define an AWS VPC resource in Terraform:resource "aws_vpc" "main" { cidr_block = var.base_cidr_block }
Data Source:
A configuration object in Terraform that returns information about an external object. Data sources do not create or manage infrastructure but provide readable attributes. For example, the
aws_vpc
data source can be used to retrieve information about an existing AWS VPC:data "aws_vpc" "existing" { id = "vpc-1234567890" }
Variable:
Variables allow you to parameterize your Terraform configurations and make them more flexible. They enable you to pass values dynamically during runtime. Example:
variable "region" { ... }
variable "instance_type" { description = "The EC2 instance type" default = "t2.micro" } resource "aws_instance" "web_server" { ami = "ami-0c94855ba95c71c99" instance_type = var.instance_type }
Output:
Outputs are values that are computed and made available for reference after Terraform applies changes. They can be used to display useful information or share values between different Terraform configurations. Example:
output "public_ip" { ... }.
State:
The Terraform state is like a record book that keeps track of what resources Terraform created and their current status. It helps Terraform understand what changes need to be made to achieve the desired configuration.
terraform { backend "s3" { bucket = "my-terraform-state" key = "terraform.tfstate" region = "us-west-2" } }
Stay tuned for my next blog on "Day2 of Terraweek Challenge". I will keep sharing my learnings and knowledge here with you.
Let's learn together! I appreciate any comments or suggestions you may have to improve my learning and blog content.
Thank you,
Subscribe to my newsletter
Read articles from Siri Chandana directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by