Infrastructure as Code Terraform
# 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
- Download azure-cli (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest)
- Download terraform https://www.terraform.io/downloads.html and follow the instructions
- Set up Terraform access to Azure : create an Azure AD service principal (https://docs.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest)
HOW TO USE
- Once you have azure-cli in your command prompt (if you using windows OS), type az login and login
- Go to subscription you want to create resources in resource group you want to create (az account set –subscription “subscription name”
- 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
- 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.