Use Terraform With Microsoft Azure

In this blog post, I will show you how to use Terraform on Microsoft Azure and create a resource group.

About Terraform

Terraform is an Infrastructure As Code open-source tool that allows us to create, manage and delete infrastructure resources as code.

With Terraform, we use .TFS files to describe our infrastructure and use Terraform to create it.

Cloud Shell

In this post, I will use Azure Cloud Shell because Terraform is pre-loaded into Cloud Shell, and we don’t need to pass any authentication credentials.

The first step here will be login on to Cloud Shell using shell.azure.com.

Create Directory

Next, let’s create a folder called terraform in Cloud Shell using the following PowerShell cmdlet.

New-Item terraform -Type directory

After creating the folder, I will access it using;

cd terraform

In the terraform folder, I will create a file called azure.tf, as shown below.

New-Item azure.tf

Code

The terraform code below will create a resource group called DSC in Sout East Asia.

In Cloud, Shell use can use the editor to copy-paste the code.

Type the following command to open the file the editor.

code azure.tf

provider "azurerm" {
version = "~>2.0"
features {}
}
resource "azurerm_resource_group" "rg" {
name = "dsc"
location = "southeastasia"
}

Set Subscription

Before running the code, we need to set the Azure subscription in Cloud Shell to the resource group is created in the right place.

Use the command below to get all your subscriptions in azure.

Get-AzSubscription

From the output, note the subscription name and set the subscription using the following command.

Select-AzSubscription pay-as-you-go

Commands

The final step will be running terraform and deploy the code.

Let’s start with initializing Terraform from using the following command which Azure will go ahead and download the latest module.

terraform init

To test the code before the deployment, Let’s run the following command, if the command comes without an error, we can deploy the code.

terraform plan

The final step will be deploying the code using the apply command and checking that the RG was created.

terraform apply

As you can see, terraform has created the resource group successfully.

Clean up

To clean the deployment and delete the resource use

terraform destroy

Processing…
Success! You're on the list.

Posted

in

by