Thursday, 21 August 2025

PART2 - Using Bash Instead of PowerShell for - Setting Up Azure Managed Redis with Terraform Using AzApi

 We have discussed "Setting Up Azure Managed Redis with Terraform Using AzApi" , since direct terraform resources are not yet available until the pull request here is released. We used a PowerShell script to extract access key and output it from terraform output. In this post let's look at how to get the same steps with bash script instead of PowerShell and get the Azure Managed Redis deployed as shown below.



The resource block to extract and create temp password file can use bash as shown below.

provisioner "local-exec" {
    command     = <<-SHELL
      set -euo pipefail

      az login --service-principal \
        -u "${var.azure_devops_service_connection_app_id}" \
        -p "${var.azure_devops_service_connection_password}" \
        --tenant "${var.tenant_id}"

      az account set --subscription "${var.subscription_id}"

      az extension add --name redisenterprise --upgrade --yes

      key=$(az redisenterprise database list-keys \
        --cluster-name "${azapi_resource.managed_redis.name}" \
        --resource-group "${azurerm_resource_group.rg.name}" \
        --query primaryKey -o tsv)

      echo "{\"primary_key\":\"$key\"}" > redis_key.json
    SHELL
    interpreter = ["/bin/bash", "-c"]
  }
}

The script can be created with name read-redis-key.sh with below content instead of read-redis-key.ps1 in "Setting Up Azure Managed Redis with Terraform Using AzApi".

#!/usr/bin/env bash
set -euo pipefail

path="redis_key.json"

if [[ -f "$path" ]]; then
    json=$(cat "$path")
    echo "$json"
    rm -f "$path"
else
    echo '{"primary_key":""}'
fi

To read the accesskey/password of redis using temp file  we can use below data block in terraform.

data "external" "redis_key" {
  program = ["/bin/bash", "./read-redis-key.sh"]

  depends_on = [null_resource.redis_key]
}

With this rest of  "Setting Up Azure Managed Redis with Terraform Using AzApi" implementation will work as expected.

No comments:

Popular Posts