Table of contents
No headings in the article.
Infrastructure as Code is a way of defining and managing your infrastructure using code, rather than manual processes like clicking through a UI or using the command line. This means that you can manage your infrastructure in the same way that you manage your application code - with version control, automation, and collaboration. In other words, infrastructure as code is a way of making your infrastructure more like software.
Benefits of IaC
Provisioning infrastructure has historically been a time-consuming and costly manual process. As virtualization, containers, and cloud computing have become the norm, infrastructure management has moved away from physical hardware in data centers—providing many benefits, but also creating some new challenges.
IaC can help your organization manage IT infrastructure needs while also improving consistency and reducing errors and manual configuration.
Benefits:
Cost reduction
Increase in speed of deployments
Reduce errors
Improve infrastructure consistency
Eliminate configuration drift
Why Terraform?
Terraform provides Cloud Development Kits(CDKs), and Pulumi is also a popular option for provisioning infrastructure with traditional software tools.
Terraform is a tool for provisioning, managing, and deploying infrastructure resources. It is an open-source tool written in Golang and created by the HashiCorp company. With Terraform, you can manage infrastructure for your applications across multiple cloud providers - AWS, Azure, GCP, etc. - using a single tool.
Terraform Cloud enables teams to work together with role-based access controls and policy enforcement. Terraform Cloud provides remote state management, which securely stores and manages the state of your infrastructure, enabling collaboration and preventing conflicts.
Terraform's capabilities and benefits
Platform independence
Terraform creates and manages resources on various platforms and services via their application programming interfaces (APIs).
State management
Terraform Cloud provides remote state management, which securely stores and manages the state of your infrastructure, enabling collaboration and preventing conflicts. The Terraform state files are encrypted at rest and you can enable certain teams and individuals to read these state files. Terraform state files may contain sensitive information and therefore need to be properly secured.
Version Control Integration
You can integrate with version control systems, allowing teams to manage infrastructure code alongside application code and track changes over time. Your version control system becomes your source of truth.
How to Install Terraform on Windows
If you are installing Terraform on Windows, you will need to download the appropriate Terraform package from the Terraform download page, unpack it, and execute it using the CLI. Follow the steps below to make sure you install it correctly:
Download the installation file
1. Navigate to the Terraform download page (https://www.terraform.io/downloads.html). It should list out Terraform downloads for various platforms. Navigate to the Windows section and download the respective version. For this example I am downloading V1.1.0.
2. It will download a zip file. Create a folder on the C drive as C:/terraform. Download the zip file in this folder. Unzip the file to extract the .exe file.
Update Path Environment Variable
1. Next open the Start menu and search for Environment variables. Open the Environment variables settings page.
2. On the Environment variables edit page, open the Path variable as shown below:
3. On the opened Path pop up, click New and add the Terraform download folder. This is the folder where the zip file was downloaded and unzipped (C:/terraform).
4. Click OK on the above window to save the Path variable addition. If needed, restart your system to apply the variable changes.
5. Open a Command prompt and run this command to verify Terraform is installed successfully:
Terraform
Terraform script to provision a simple cloud resource
Let us begin by importing a simple resource – EC2 instance in AWS. I am assuming the Terraform installation and configuration of AWS credentials in AWS CLI is already done locally. We will not go into the details of that in this tutorial. To import a simple resource into Terraform, follow the step-by-step guide below.
Prepare the EC2 Instance
Assuming the Terraform installation and configuration of AWS credentials in AWS CLI is already done locally, begin by importing a simple resource—EC2 instance in AWS. For this tutorial's sake, we will manually create an EC2 resource to be imported. This could be an optional step if you already have a target resource to be imported.
Terraform: Create EC2 Instance in Existing VPC
Go ahead and provision an EC2 instance in your AWS account. Here are the example details of the EC2 instance thus created:
Name: MyVM
Instance ID: i-0b9be609418aa0609
Type: t2.micro
VPC ID: vpc-1827ff72
…
Terraform Commands
• Introduction to basic Terraform commands
init:
The terraform init command is the first command you should use to initialize the working directory.
To prepare the working directory for use with Terraform, the Terraform init command performs the following steps:
Backend Initialization
Child Module Installation
Plugin Installation
terraform init — Initialize the working directory.
plan:
The Terraform plan command creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure. By default, when Terraform creates a plan it: Reads the current state of any already-existing remote objects to make sure that the Terraform state is up-to-date.
Terraform plan is a Terraform CLI command that previews the changes that will be made to the infrastructure based on the current code configuration. It generates and displays an execution plan, detailing which actions will be taken on which resources, allowing for a review before actual application.
The terraform plan command does three things:
Ensures the state is up to date by reading the current state of any already-existing remote infrastructure.
Determines the deltas between the current configuration and the prior state data.
Proposes a series of changes that will make the remote infrastructure match the current configuration.
Apply:
The terraform apply command executes the actions proposed in a terraform plan. It is used to deploy your infrastructure. Typically apply should be run after terraform init and terraform plan.
f the apply command is run without any options it will run a terraform plan first, ask the user to confirm the planned actions, and then execute those changes once confirmed.
The apply command can also be used with a previously generated planfile, from the terraform plan -out=<path to file>.
terraform apply
Creates or updates infrastructure depending on the configuration files. By default, a plan will be generated first and will need to be approved before it is applied
Destroy:
The Terraform destroy command is a command that terminates resources managed by your current Terraform project by deleting infrastructure resources present in the state file. When the destroy command is executed, Terraform first validates the information contained in the state file by cross-checking with cloud provider APIs. Internally it builds a dependency graph to identify the sequence in which the resources are to be destroyed.
Terraform destroy is a more common way to destroy resources managed by Terraform. The destroy command can be used to destroy a complete set of cloud infrastructure or a targeted resource.
To destroy a specific EC2 instance (demo_vm_1), the --target argument can be supplied to the destroy command with the resource path to identify the correct resource as below.
Terraform: Destroy Target
• Tips for managing and organizing Terraform code, including version control integration.
Start every module with a main.tf file, where resources are located by default.
In every module, include a README.md file in Markdown format. In the README.md file, include basic documentation about the module.
Place examples in an examples/ folder, with a separate subdirectory for each example. For each example, include a detailed README.md file.
Create logical groupings of resources with their own files and descriptive names, such as network.tf, instances.tf, or loadbalancer.tf
Avoid giving every resource its own file. Group resources by their shared purpose. For example, combine google_dns_managed_zone and google_dns_record_set in dns.tf.
In the module's root directory, include only Terraform (*.tf) and repository metadata files (such as README.md and CHANGELOG.md).
Place any additional documentation in a docs/ subdirectory.
Name all configuration objects using underscores to delimit multiple words.
Declare all variables in variables.tf.
Give variables defined types.
Organize all outputs in an outputs.tf file.
Provide meaningful descriptions for all outputs.
Organize helper scripts that aren't called by Terraform in a helpers/ directory.
Connect to Version Control: Create a new repository in your version control system and link your Terraform project directory to this repository. Create Terraform Configuration Files: Write your Terraform configuration files () to define your desired infrastructure.