Terraform with Visual Studio Code for Azure

What is Terraform?

Terraform is a managing tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage Microsoft Azure.

Configuration files describe to Terraform the components needed to run a single application or an entire infrastructure on Azure. Terraform generates an execution plan describing what it will do to reach the desired state, and then executes it to build the described infrastructure. As the configuration changes, Terraform is able to determine what changed and create incremental execution plans which can be applied.

The infrastructure Terraform can manage includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features, etc.

The key features of Terraform are:

  • infrastructure as Code
  • execution plans
  • resource graph
  • change automation

Installation Terraform?

This is a quick start guide to use Terraform in Visual Studio Code and Azure.

Installation Terraform extensions in Visual Studio.

Install following extension into your Visual Studio Code:

  • Azure Account (Current version at publishing is 0.4.3)
  • Azure Terraform (Current version at publishing is 0.2.2)

terraform0011

Installation Terraform on Windows 10

We need the Terraform executable, on the local machine. Terraform current version can be downloaded as from this page by selecting the operating system. In this chase it will be Windows 32-bit / 64-bit.
terraform002

After the download has been completed, extract the ZIP file and copy the executable to c:\Users\<UserName>\Tools\Terraform and copy the file in the newly created directory.

terraform0061

Search in the start menu for “Edit the system environment variables” and click [Environment Variables…]. This will bring you to change the path variables under the system environment.

terraform003

 

 

 

Add in the path variable a new line by clicking [New] and a the line c:\Users\<UserName>\Tools\Terraform\

Click «OK», «OK», «OK»

This will save the new settings towards the machine, sometimes a reboot is needed to activate the settings.

To check is you can execute Terraform, just open a command prompt and type «terraform». This will generated the following output.

OUTPUT

C:\Users\<username>>terraform
Usage: terraform [-version] [-help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management

C:\Users\frederik>

Installation Terraform add-on nodejs

Download the software from the following page and download current version.

terraform007

After download start the installation:

This slideshow requires JavaScript.

 Installation Terraform add-on Graphviz

Download the software from the following page and download current version for windows.

Check if the environment variables has been added, see screenshot below:

terraform018
Local setup has been completed.

Create in Visual Studio Code a project for Terraform.
terraform019
We are ready to prepare Azure in the following configuration steps.

Configuration steps in Azure

Connect to your tenant and open cloud shell in Bash or go to cloud SHELL and select your directory.
terraform020
Connected
terraform021
In this next step will prepare the Azure environment for Terraform and give the application access via a Azure Service Principal (more information about Azure Service Principal with Azure CLI)

First we will check the subscription ID and tenant ID.
terraform022
Set account to the correct subscription

az account set --subscription="«subscriptionId»"

Enter the subscription id out of previous step. In the next step we will create the Service Principal in Azure AD.

az ad sp create-for-rbac --rol="Contributor" --scope="/subscriptions/«subscriptionId»"

This will generate and output as shown in picture below, make note of the appId and password that has been generated for the Azure SP.
terraform024
In the Azure Portal, above result looks like this: Go to Azure Active Directory >> Select App registrations.
terraform025

Upload your first main configuration file to Azure.

Open Visual Studio Code and create a “main.tf” file and enter the Azure provider information.

provider "azurerm" {
  subscription_id = "«subscriptionId»"
  client_id       = "«ClientId»"
  client_secret   = "«ClientSecret»"
  tenant_id       = "«TenantId»"
}

>> Information that has been collected in previous steps
Example:
provider "azurerm" {
  subscription_id = "4fdb43bc-cccc-43bc-gggg-fa7f36bed0df"
  client_id       = "dsfd4tst-ef49-4390-92ab-5a15cc80f95b"
  client_secret   = "02a01a9d-3a59-4092-a1b0-f5e03e7a2a50"
  tenant_id       = "32f54d8f-b485-45ce-86e8-g5d38f3a7d23="
}

>> Create resource group in your tenant
>> location can be found by entering the follozing command in your bash shell
prompt az account list-location --output table
DisplayName          Latitude    Longitude    Name
-------------------  ----------  -----------  ------------------
East Asia            22.267      114.188      eastasia
Southeast Asia       1.283       103.833      southeastasia
Central US           41.5908     -93.6208     centralus
East US              37.3719     -79.8164     eastus
East US 2            36.6681     -78.3889     eastus2
West US              37.783      -122.417     westus
North Central US     41.8819     -87.6278     northcentralus
South Central US     29.4167     -98.5        southcentralus
North Europe         53.3478     -6.2597      northeurope
West Europe          52.3667     4.9          westeurope
Japan West           34.6939     135.5022     japanwest
Japan East           35.68       139.77       japaneast
Brazil South         -23.55      -46.633      brazilsouth
Australia East       -33.86      151.2094     australiaeast
Australia Southeast  -37.8136    144.9631     australiasoutheast
South India          12.9822     80.1636      southindia
Central India        18.5822     73.9197      centralindia
West India           19.088      72.868       westindia
Canada Central       43.653      -79.383      canadacentral
Canada East          46.817      -71.217      canadaeast
UK South             50.941      -0.799       uksouth
UK West              53.427      -3.084       ukwest
West Central US      40.890      -110.234     westcentralus
West US 2            47.233      -119.852     westus2
Korea Central        37.5665     126.9780     koreacentral
Korea South          35.1796     129.0756     koreasouth
France Central       46.3772     2.3730       francecentral
France South         43.8345     2.1972       francesouth
Australia Central    -35.3075    149.1244     australiacentral
Australia Central 2  -35.3075    149.1244     australiacentral2

resource "azurerm_resource_group" "RG-PROnICT" {
        name = "RG-PROnICT"
        location = "WestEurope"
        tags {
          Environment = "Production"
          Departement = "IT"
        }
}

Connect to your Azure tenant by pressing «CTRL» + «Shift» + «P» and type «Azure: Sign In»
terraform027
In the bottom right corner, following pop-up will guide you to the web portal of Azure to authenticate via a device login code.

terraform028
Following steps displaying how we will authenticate.

This slideshow requires JavaScript.

When authenticated, Visual Studio Code will display in left corner “Azure: «username»”.

Next step we will test the connection and upload the first main file.
Pressing «CTRL» + «Shift» + «P» and type «Azure Terraform: init»
terraform034
During initialization the Terraform executable will be downloaded. Before doing this we need to push the configuration file to the Cloud Shell location or upload to Cloud Shell.

terraform038
terraform039
Everything is set to apply the configuration and let Azure RM do the rest.
Pressing «CTRL» + «Shift» + «P» and type «Azure Terraform: Plan»
terraform040
Pressing «CTRL» + «Shift» + «P» and type «Azure Terraform: Apply» and type «Yes» to apply the configuration.

This slideshow requires JavaScript.

Check if the resource group has been created.
terraform046
There we have it, now we can start building are project with Terraform and Visual Studio Code.

 


One thought on “Terraform with Visual Studio Code for Azure

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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