Skip to main content

Explaining Terraform Code as Infrastructure (CAI)

 

Explaining Terraform Code as Infrastructure (CAI) by Ziggy Rafiq in his Blog Post


Explaining Terraform Code as Infrastructure (CAI)


What Is Terraform

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. It can manage popular service providers as well as custom in-house solutions. Terraform uses a declarative syntax to describe the desired state of infrastructure and automatically creates, updates, and deletes resources to reach the desired state.


Why use Terraform

Terraform is used because it offers several benefits over manual provisioning and other configuration management tools:

  • Infrastructure as Code: Terraform allows you to describe your infrastructure using code, making it easier to version control, automate deployment, and share configurations.
  • Cross-Provider Compatibility: Terraform can manage a diverse range of infrastructure resources across multiple cloud providers, on-premises data centres, and other infrastructure sources.
  • Improved Collaboration and Workflow: Terraform enables teams to work together more effectively by providing a unified language for expressing infrastructure.
  • Improved Visibility and Validation: Terraform allows you to preview changes before you apply them, which helps avoid unintended consequences and improves the quality of changes.
  • Increased Resource Management Efficiency: Terraform enables you to automate resource provisioning, making it easier to manage resources and enforce infrastructure standards.

Where is Terraform

Terraform is an open-source tool created by Hashicorp. It can be used on any platform that supports Go, including Windows, macOS, and Linux. Terraform is available for download from the Hashicorp website and can also be installed using package managers such as Homebrew, APT, and YUM. Additionally, Terraform is available as a pre-built binary for a variety of operating systems and architectures. The source code for Terraform is hosted on GitHub and is open for contribution from the community.


How to use Terraform

Terraform is used by writing Terraform configuration files that describe the desired state of the infrastructure. The basic steps to use Terraform are:

  • Write Terraform configuration files: These files define the infrastructure resources you want to create and manage, such as virtual machines, databases, and networking components.
  • Initialize Terraform: This step downloads the necessary plugins and verifies the configuration files for syntax and validity.
  • Plan Terraform: This step generates an execution plan, which outlines the changes that Terraform will make to reach the desired state.
  • Apply Terraform: This step implements the execution plan and makes the necessary changes to the infrastructure.
  • Monitor Terraform: This step monitors the infrastructure to ensure it remains in the desired state.

It is recommended to use Terraform in version control systems such as Git to keep track of changes to the configuration files over time. Additionally, Terraform has a number of advanced features such as modules, workspaces, and state management that can be used to improve the efficiency and scalability of infrastructure management.

Examples of using Terraform

Here are a few Examples of Terraform I have created for this blog post. I will be at some point adding YouTube Videos demonstrating how to use Terraform with a few examples.

Example One

This is a simple example of Terraform configuration that provisions on AWS (Amazon Web Services) EC2 Instance.

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

This Terraform configuration does the following:

  • Specifies the AWS provider and sets the region to us-west-2.
  • Creates an EC2 instance using the ami-0c55b159cbfafe1f0 Amazon Machine Image (AMI) and the t2.micro instance type.

You can save this code to a file with a .tf extension and run terraform init, terraform apply to create the EC2 instance on AWS.


Example Two

In this example of using Terraform to deploy an SQL Server instance on Azure (Microsoft Azure).

provider "azurerm" {

  version = "2.0"

}

 

resource "azurerm_resource_group" "example" {

  name     = "example-group"

  location = "westus"

}

 

resource "azurerm_sql_server" "example" {

  name                         = "example-server"

  location                     = azurerm_resource_group.example.location

  resource_group_name          = azurerm_resource_group.example.name

  version                      = "12.0"

  administrator_login          = "adminuser"

  administrator_login_password = "Password1234!"

}

 

output "sql_server_fqdn" {

  value = azurerm_sql_server.example.fully_qualified_domain_name

}

This Terraform configuration creates a resource group named example-group in the westus region, and a SQL Server instance named example-server within that group. It also sets the administrator username and password. The output of the Terraform run will display the fully qualified domain name of the SQL Server instance, which can be used to connect to it.

Example Three

In this Example of code, I will be using Terraform to deploy a web server on AWS (Amazon Web Services) EC2 instance.

provider "aws" {

  region = "us-west-2"

}

 resource "aws_instance" "example" {

  ami           = "ami-0c55b159cbfafe1f0"

  instance_type = "t2.micro"

   tags = {

    Name = "example-web-server"

  }

}

 output "public_ip" {

  value = aws_instance.example.public_ip

}

This Terraform script creates an EC2 instance in the us-west-2 region using the Amazon Linux AMI, with a t2.micro instance type. It also tags the instance with the name "example-web-server". The output at the end of the script displays the public IP address of the EC2 instance, which you can use to access your web server.

Example Four

 In this example, I am showing you how to deploy an IIS (Microsoft Internet Information Server) on a Windows Server 2019 EC2 instance on AWS (Amazon Web Services) using Terraform.

provider "aws" {

  region = "us-west-2"

}

 

resource "aws_instance" "example" {

  ami           = "ami-0e55e25ba95c71c99"

  instance_type = "t2.micro"

 

  tags = {

    Name = "example-iis-server"

  }

 

  connection {

    type     = "winrm"

    user     = "Administrator"

    password = "Password123"

  }

 

  provisioner "remote-exec" {

    inline = [

      "powershell.exe -command Add-WindowsFeature Web-Server;",

      "powershell.exe -command Add-WindowsFeature Web-ASP;",

      "powershell.exe -command Add-WindowsFeature Web-ISAPI-Ext;",

      "powershell.exe -command Add-WindowsFeature Web-ISAPI-Filter;",

      "powershell.exe -command Add-WindowsFeature Web-Net-Ext45;"

    ]

  }

}

 output "public_ip" {

  value = aws_instance.example.public_ip

}

This Terraform script creates a Windows EC2 instance in the us-west-2 region using the Windows Server 2019 Base AMI, with a t2.micro instance type. It also tags the instance with the name "example-iis-server". The connection block is used to specify the connection information for the Windows EC2 instance, including the username and password. The provisioner block is used to install IIS on the Windows EC2 instance by running a series of PowerShell commands that add the necessary Windows features. The output at the end of the script displays the public IP address of the EC2 instance, which you can use to access your IIS server.

Example Five

This is one of my favorite examples I enjoyed writing as I personally use this one a lot within my SDLC (Software Development Lifecycle ) outside my work. Here I am using Terraform to deploy an ASP.net Core Web Application on a Windows Server 2019 EC2 instance on AWS (Amazon Web Services).

provider "aws" {

  region = "us-west-2"

}

 

resource "aws_instance" "example" {

  ami           = "ami-0e55e25ba95c71c99"

  instance_type = "t2.micro"

 

  tags = {

    Name = "example-aspnet-app"

  }

 

  connection {

    type     = "winrm"

    user     = "Administrator"

    password = "Password123"

  }

 

  provisioner "file" {

    source      = "path/to/aspnetapp.zip"

    destination = "C:\\aspnetapp.zip"

  }

 

  provisioner "remote-exec" {

    inline = [

      "powershell.exe -command Add-WindowsFeature Web-Server;",

      "powershell.exe -command Add-WindowsFeature Web-ASP;",

      "powershell.exe -command Add-WindowsFeature Web-ISAPI-Ext;",

      "powershell.exe -command Add-WindowsFeature Web-ISAPI-Filter;",

      "powershell.exe -command Add-WindowsFeature Web-Net-Ext45;",

      "powershell.exe -command Expand-Archive -Path C:\\aspnetapp.zip -DestinationPath C:\\aspnetapp;",

      "powershell.exe -command cd C:\\aspnetapp;",

      "powershell.exe -command .\\Setup.ps1;"

    ]

  }

}

 

output "public_ip" {

  value = aws_instance.example.public_ip

}

This Terraform script creates a Windows EC2 instance in the us-west-2 region using the Windows Server 2019 Base AMI, with a t2.micro instance type. It also tags the instance with the name "example-aspnet-app". The connection block is used to specify the connection information for the Windows EC2 instance, including the username and password. The first provisioner block copies the ASP.NET Core application (compressed as a zip file) to the EC2 instance. The second provisioner block installs IIS on the Windows EC2 instance and sets up the ASP.NET Core application by running a series of PowerShell commands. The output at the end of the script displays the public IP address of the EC2 instance, which you can use to access your ASP.NET Core application.

Final Thoughts 

In this blog post, I have explained Terraform and I have given 5 examples of where to use Terraform as it helps us speed up setting up Infrastructures by using code as infrastructure not only that but it is well-documented code in formats such as JSON. 

Comments

Most Viewed Ziggy Rafiq Blog Posts

A Complete Guide to Using GUIDs in C# with Code Examples

  Overview In this post, we are looking at GUIDs (Globally Unique Identifiers), which are widely used in C# for generating unique identifiers for objects, entities, and resources in a system. In this post, we'll explore the basics of GUIDs in C#, their advantages, and how to convert strings to GUIDs. In this post, we have used Guid Generator to create the GUID from the following URL Address https://guidgenerator.com/ What is GUID GUID (Globally Unique Identifier) in C# is a 128-bit value that is used to identify objects, entities, or resources in a unique manner across different systems and applications. It is also known as UUID (Universally Unique Identifier) in some other programming languages.   GUIDs are generated using a combination of unique factors such as the MAC address of the network adapter, the current time and date, and a random number. The resulting GUID is a string of 32 hexadecimal digits separated by hyphens, such as "b86f2096-237a-4059-8329-1bbcea72769b...

Primitives Data Types and None-Primitives Data Types in C# with Code Examples

  Overview I wrote this post to provide an explanation of primitive and non-primitive data types in C#. C# is a strongly typed programming language, where each variable and expression must have a specific data type. C# data types are categorized into two primary groups: primitive data types and non-primitive data types. Primitive data types are the simplest data types available in programming languages. They are typically pre-defined data types and can represent a single value, such as a boolean value, character, or integer. Examples of primitive data types include int, char, float, double, and boolean, which are common in programming languages like C++, C, and Java. Non-primitive data types are also referred to as composite data types or reference data types. They are constructed from primitive data types and are more complex than primitive data types. Non-primitive data types can hold multiple values and allow for the creation of more intricate data structures like tables, li...

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6 Overview An Enum (Enumeration) is a group of constants that are read-only value types. By default, the first value of the Enum variable is 0 i.e. Here we will create an Enum of Priorities type with read-only values of Highest, Normal and Low. We will set the read-only values using an integer assigning a number next to the value. By default, the integer value will start with 0. Here we will be assigning the integer value next to the Enum value such as in the below example and we will use a comma (,) to separate the item in the list of Enum(Enumeration).  We create Enum by using the Enum keyword and then using class, interface, and abstract. The reason we use an Enum is to ensure we improve our application performance and improve application readability, and maintainability, and reduces the complexity of the application hence why if you take a look at the example below of Status (NotStarted, Started, Comp...