DevOps Classroom Series – 03/Jun/2020

Using Terraform with Azure

  • Add Extension to visual studio code Preview
  • To Configure Azure provider in terraform
    • Open azure cloud shell / use azure cli Preview
    • Execute az ad sp create-for-rbac --query "{ client_id: appId, client_secret: password, tenant_id: tenant }" in cloud shell/cli
  • Lets write template to create resource group, vnet with subnets and public ip

provider "azurerm" {
    features {}
}

resource "azurerm_resource_group" "tfgroup" {
    name                    = "terraform"
    location                = var.location
    tags                    = local.common_tags
}

resource "azurerm_virtual_network" "ntier" {
    name                    = var.network_name
    
    address_space           = [var.networkcidr]
    resource_group_name     = local.groupname
    location                = var.location

    tags                    = local.common_tags
    depends_on              = [azurerm_resource_group.tfgroup]
}

resource "azurerm_subnet" "subnets" {
    count                   = length(var.subnetnames)
    name                    = var.subnetnames[count.index]
    resource_group_name     = local.groupname
    virtual_network_name    = var.network_name
    address_prefixes        = [cidrsubnet(var.networkcidr,8,count.index)]      
    depends_on              = [azurerm_resource_group.tfgroup, azurerm_virtual_network.ntier]
  
}


resource "azurerm_public_ip" "myip" {
    resource_group_name     = local.groupname
    location                = var.location
    name                    = var.ipname
    allocation_method       = "Dynamic"
    tags                    = local.common_tags
    depends_on              = [azurerm_resource_group.tfgroup]


  
}


  • Now to get the state of the resources in terraform use terraform refresh
terraform refresh
  • Now if we want to recreate publicip during next terraform apply, we taint the resource
terraform taint azurerm_public_ip.myip

Preview

  • After taint, lets try to do apply
terraform apply .

Preview

  • You can undo this taint using untaint before apply command
  • While using terraform apply or destroy a particular resource can be targeted using -target command option Preview
  • Now lets try to delete only ip resource using terraform destroy
terraform destroy -target='azurerm_public_ip.myip' .

Preview

  • Exercise: What should be done to delete more that one resource using terraform destroy

Leave a Reply

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

About learningthoughtsadmin