Problem statement -> Most of the organizations prefer to use Terraform to provision/update/destroy resources in cloud platforms such as Azure, AWS, GCP. Sometime its required to use local-exec to perform certain operations from terraform in case the TF provider/resources are not available.

In my case , i was using Terraform with github workflow (on push) to create resources in appropriate cloud platform and i was using Linux github runner to run the terraform. i wanted to execute az cli in local-exec but also wanted to add some condition based on terraform variables before running AZ cli.

Solution-> if we want to use terraform variable in local-exec then just use “${var.VariableName}” inside the local-exec provisioner.

Example code ->

resource "null_resource" "azcli" {
  provisioner "local-exec" {
    command = <<EOT
      declare -a location=("australiaeast" "australiasouthEast" "brazilsouth" "canadacentral" "centralus" "eastus" "eastus2")
      for i in "$${location[@]}"
      do
        if [ "${var.mssql_server_location}" = "$${location[i]}" ]
        then
          echo "you reached if block"
          az sql db update --resource-group "${data.azurerm_resource_group.rg.name}" --server "${var.mssql_server_name}" --name "${var.resource_name}" --maint-config-id "${var.maintenancewindowconfig}"
        fi
      done
    EOT
  }
  depends_on = [
    azurerm_mssql_database.primary
  ]
}


(Visited 13 times, 1 visits today)

By Arun Sabale

Arun is a Solution Architect on enterprise client management with more than 14 years of experience in IT. Arun Sabale is Blogger and tech enthusiast. His main focus is on Azure cloud infra, Cloud automation with powershell, python, ARM terraform and all cloud infra services like compute, storage, network, automation, function api etc... LinkedIN - https://www.linkedin.com/in/arun-sabale/

Leave a Reply

Your email address will not be published. Required fields are marked *