Terraform

Using Terraform with Azure

This is a tutorial on using Terraform with Azure for beginners.

1. Overview

Terraform was created on May 21st, 2014 by Mitchell Hashimoto. Hashimoto was Hashicorp’s founder. Terraform is used for building code and handling infrastructure security. Terraform is a popular DevOps tool in the software world.

2. Terraform with Azure Tutorial

2.1 Prerequisites

Terraform is necessary on the operating system in which you want to execute the code.

2.2 Download

You can download Terraform from this website.

2.3 Setup

2.3.1 Terraform Setup

You can set up the Terraform by using the command below on macOS:

Terraform Setup

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

You can run this command to check if it is working:

Terraform Execution

 terraform -v

The output of the above command executed is shown below:

Terraform Execution Output

apples-MacBook-Air:~ bhagvan.kommadi$  terraform -v
Terraform v1.1.5
on darwin_amd64
apples-MacBook-Air:~ bhagvan.kommadi$

The terraform execution command has other options which are shown below:

Terraform Execution Options

$ terraform Usage: terraform [-version] [-help]  [args] ... help content omitted

2.4 Start a New Terraform Project

You can create a Terraform Project using resource definitions. Resource definitions are the files with the suffix .tf. You can use Terraform’s language for configuring the resources like EC2 instance, an Azure MariaDB, or a DNS entry. You can create a sample Terraform project with the commands shown below:

Terraform Project Creation Commands

$ cd $HOME
$ mkdir sample-terraform
$ cd sample-terraform
$ cat > main.tf <<EOF
provider "local" {
  version = "~> 1.4"
 }
resource "local_file" "sample" {
content = "sample, Terraform"
filename = "sample.txt"
}
EOF

The above main.tf file has resource and provider definitions. Local provider version 1.4 or other compatible version is used. sample of type local_file has the resource definition. You can run the terraform project by using the command below:

Terraform Project Execution

terraform init

The output of the above command when executed is shown below:

Terraform Project Execution Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 1.4"...
- Installing hashicorp/local v1.4.0...
- Installed hashicorp/local v1.4.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Above, terraform reads the project files and downloads the required providers from public registries. The next step is to execute the plan command as shown below:

Terraform Project Execution – Plan

 terraform plan

The output of the above command when executed is shown below:

Terraform Project Execution – Plan Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform plan

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.sample will be created
  + resource "local_file" "sample" {
      + content              = "sample, Terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "sample.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

───────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.
apples-MacBook-Air:sample-terraform bhagvan.kommadi$

The above terraform plan command helps in verifying the actions for resource creation. Terraform assumes that default values will be used where ever you have not shared them in the resource definition. You can now execute the apply command for resource creation.

Terraform Project Execution – Apply

 terraform apply

The output of the above command when executed is shown below:

Terraform Project Execution – Apply Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform apply

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.sample will be created
  + resource "local_file" "sample" {
      + content              = "sample, Terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "sample.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

local_file.sample: Creating...
local_file.sample: Creation complete after 0s [id=37d2f5fd67a0734d5d8d1626a47ae46f5b4dee17]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
apples-MacBook-Air:sample-terraform bhagvan.kommadi$

In the above command, the execution plan is generated. You can see the sample.txt. It will have the expected content Sample, Terraform.

Terraform Project Execution – Sample.txt

sample, Terraform

You can run the apply-auto-approve command next.

Terraform Project Execution – Apply Auto Approve

terraform apply -auto-approve

The output of the above command when executed is shown below:

Terraform Project Execution – Apply Auto Approve Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform apply -auto-approve
local_file.sample: Refreshing state... [id=37d2f5fd67a0734d5d8d1626a47ae46f5b4dee17]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and
found no differences, so no changes are needed.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Apply complete! Resources: 0 added, 0 changed, 0 destroyed

You can have modules in Terraform which can have resources defined across different projects.

2.5 Azure Setup

You can access the Azure cloud shell first. Select the bash shell for the tutorial. You can check the subscription using the command az account show. You will see the output as shown below:

Azure Subscription check output

Requesting a Cloud Shell.Succeeded. 
Connecting terminal...

Welcome to Azure Cloud Shell

Type "az" to use Azure CLI
Type "help" to learn about Cloud Shell

bhagvan@Azure:~$ az account show
{
  "environmentName": "AzureCloud",
  "homeTenantId": "776ab42f-9b4d-4e96-ba20-f464a7f4b53a",
  "id": "458ed9b2-c552-42b5-954e-f3c8210ddc73",
  "isDefault": true,
  "managedByTenants": [],
  "name": "Pay-As-You-Go",
  "state": "Enabled",
  "tenantId": "776ab42f-9b4d-4e96-ba20-f464a7f4b53a",
  "user": {
    "cloudShellID": true,
    "name": "live.com#bhagvanarch@gmail.com",
    "type": "user"
  }
}

If the verification goes wrong, you can set the right subscription using the command below.

Azure Subscription setting

az account set -s "my subscription name"

Now let us look at using terraform on Azure.

2.6 Terraform on Azure

On Azure cloud shell, you can create a new folder terraform. You can write the terraform configuration file as shown below:

Azure Terraform Configuration

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=2.97.0"
    }
  }
}


provider "azurerm" {
  features {}
}


resource "azurerm_resource_group" "rg" {
    name     = "rg-AzureTerraform"
    location = "westus"
}

Now you can initialize the terraform configuration with upgrade using terraform init -upgrade. The output is as below:

Terraform Project – initialize

bhagvan@Azure:~/terraform$ terraform init -upgrade

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/azurerm versions matching "2.97.0"...
- Installing hashicorp/azurerm v2.97.0...
- Installed hashicorp/azurerm v2.97.0 (signed by HashiCorp)

Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
bhagvan@Azure:~/terraform$

You can execute the terraform plan by running the command terraform plan. You can see the output below:

Terraform Project – Plan

bhagvan@Azure:~/terraform$ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_resource_group.rg will be created
  + resource "azurerm_resource_group" "rg" {
      + id       = (known after apply)
      + location = "westus"
      + name     = "rg-AzureTerraform"
    }

Plan: 1 to add, 0 to change, 0 to destroy.

─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply"
now.

Now you can apply this plan using the command terraform apply. The output is as shown below:

Terraform Project – Apply

bhagvan@Azure:~/terraform$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_resource_group.rg will be created
  + resource "azurerm_resource_group" "rg" {
      + id       = (known after apply)
      + location = "westus"
      + name     = "rg-AzureTerraform"
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

azurerm_resource_group.rg: Creating...
azurerm_resource_group.rg: Creation complete after 4s [id=/subscriptions/458ed9b2-c552-42b5-954e-f3c8210ddc73/resourceGroups/rg-AzureTerraform]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
bhagvan@Azure:~/terraform$

You can check the created configuration by reviewing the contents of the file terraform.tfstate. The contents are shown below:

Terraform Project – State after apply

bhagvan@Azure:~/terraform$ cat terraform.tfstate 
{
  "version": 4,
  "terraform_version": "1.1.7",
  "serial": 1,
  "lineage": "3d30be68-b673-9327-2e79-4a87db56673c",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "azurerm_resource_group",
      "name": "rg",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "id": "/subscriptions/458ed9b2-c552-42b5-954e-f3c8210ddc73/resourceGroups/rg-AzureTerraform",
            "location": "westus",
            "name": "rg-AzureTerraform",
            "tags": null,
            "timeouts": null
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo1NDAwMDAwMDAwMDAwLCJkZWxldGUiOjU0MDAwMDAwMDAwMDAsInJlYWQiOjMwMDAwMDAwMDAwMCwidXBkYXRlIjo1NDAwMDAwMDAwMDAwfX0="
        }
      ]
    }
  ]
}
bhagvan@Azure:~/terraform$

3. Download the Source Code

Download
You can download the full source code of this example here: Using Terraform with Azure

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button