Learn Terraform - get started...

After reading Chapter 1 of the book it was time to get my machine ready for using Terraform to script the deployments in Azure. So I search the Microsoft Docs for a short guide and found this short description.

First Step - Install Terraform on my machine

I decided to install Terraform in the Windows Subsystem for Linux (WSL) on my Windows10 machine. I’m on the fast-ring in the Windows10 insider program - so I’m already able to use WSL2. If you want to learn more about WSL2 visit the Microsoft page https://aka.ms/wsl2. To install Terraform in my WSL2 I opened the bash and entered the following command (use sudo of needed to have privileged rights):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# First - install unzip

apt-get install unzip

# Download the installation for Terraform (check for newest version before...)

wget https://releases.hashicorp.com/terraform/0.12.6/terraform\_0.12.6\_linux\_amd64.zip

# Unzip the Terraform folder

unzip terraform\_0.12.6\_linux\_amd64.zip terraform

# Move the folder to an accessible path for the system

mv terraform /usr/local/bin/

# test the Terraform version on your WSL machine

terraform --version

If everything worked fine, you will now have Terraform on your WSL to start using it.

Second Step - get Terraform connected

As soon as you want Terraform to apply your script in your Azure Tenant the best way is to deploy a service principal in your Azure Active Directory with the needed contributor rights. You can find these guide in the Microsoft Docs.

The last action is to define the environment variables for Terraform to use the just created credentials.

Last Step - deploy your first resource

Now that the environment is set up properly - we can deploy our first Azure resource. At what is the best first resource - yes, a resource group!

We need our first Terraform script. I made a new folder in the WSL and started my Visual Studio Code (VSCode) in this folder by just typing code . to start the UI in that folder and created my first script named main.tf and entered the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# main.tf

provider "azurerm" {
version = "~>2.0.0"
features {}
}

resource "azurerm\_resource\_group" "rg" {
name = "myFirstTerraform-RG"
location = "westeurope"
tags = {
source = "Terraform"
}
}

After saving the script I opened the terminal in VSCode and run my first Terraform command:

1
terraform init

If all environment variables are set correctly and we made no other typing error Terraform will interpret the provider statement and will download the needed Azure provider. This done we can apply our script to Azure by typing

1
terraform apply

We only have to type one final “yes” into the console and our first resource group is deployed in Azure. So let’s open the Azure portal and check:

Terraform sample resource group

That’s it - our first Terraform script was successfully been deploy to Azure!