Infrastructure as Code Terraform

Steven Audy
sera-engineering
Published in
3 min readOct 15, 2020

# How to use Terraform on Azure

This is explanation how to setup Terraform in Microsoft Azure environment using Azure-CLI in Windows 10 Command Prompt.

PREREQUISITES

HOW TO USE

  1. Once you have azure-cli in your command prompt (if you using windows OS), type az login and login
  2. Go to subscription you want to create resources in resource group you want to create (az account set –subscription “subscription name”
  3. Then create Azure AD service principal for terraform to perform resource creation instead using your admin account : az ad sp create-for-rbac — name ServicePrincipalName
  4. It will produce something like this :

5. Create file.tf for terraform to perform and put this inside file :

provider “azurerm” {

features {}

subscription_id = “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx” #put subscription id from cmd : az account list — output table

client_id = “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx” #put appid from SP

client_secret = “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx” #put password from SP

tenant_id = “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx” #put tenant

}

6. You can begin to create resources (basically starting with RG creation) :

resource “azurerm_resource_group” “rg” {

name = “rg_name”

location = “Southeast Asia”

}

Other resources you can find it in https://www.terraform.io/docs/providers/azurerm/index.html

7. After done configure file.tf, open command prompt and go to the folder where file.tf exist with command cd [folder_path]

8. Apply command terraform init to initialize plugin terraform in that folder ( this only running once if the folder already have terraform plugins.

9. Then terraform plan — out [namefile].out -> this step will give you insight which resource will be created, deleted. Once you clarify the plan, you can execute it using command terraform apply [namefile].out

Note : in plan step, terraform will verify existing resources in azure. If the resource is not there, terraform will perform to create. If it exist, you need to import the resources first into terraform plan (https://faultbucket.ca/2018/03/terraform-import-azure-resources/). After import is successful, run terraform plan again and then apply if there’s no error.

--

--

Steven Audy
sera-engineering

Hi i’m Steven. Right now i’m a Cloud Architecture & DevOps Engineer at PT. Serasi Autoraya. Interested in Infrastructure, Architecture and Automation :)