1
votes

I have saved azure storage key in key vault and i want to retrieve the key using Azure cli and set it as env. variable in window cmd before i run terraform script.

Below listed command doesn't work, can anyone tell me what needs to be changed ?

set ARM_ACCESS_KEY=$(az keyvault secret show --name terraform-backend-key --vault-name myKeyVault)

Error on initializing

enter image description here

Main.tf

variable "count" {}
variable "prefix" {
default="RG"
 }
terraform {
backend "azurerm" {
container_name       = "new"
storage_account_name  = "mfarg"
key                  = "terraform.tfstate"
}}
resource "azurerm_resource_group" "test" {
count ="${var.count}"
name     = "${var.prefix}-${count.index}"
location = "West US 2"
}

Command prompt output

enter image description here

2
If you don't get enough answers here, you might also wish to ask a similar question on ServerFault or SuperUser.cssyphus
you are assigning a multi-line JSON document to a variable which probably fails. use "--query path --output tsv" to get just the property you need.victor m

2 Answers

3
votes

To set the environment variable in Windows, I suggest you use the PowerShell command to achieve it. In PowerShell, you can just do it like this:

$env:ACCESS_KEY=$(az keyvault secret show -n terraform-backend-key --vault-name myKeyVault --query value -o tsv)

Also, in your CLI command, you could not show the secret directly, it outputs the whole secret not just the access key as you want. See the difference between the two commands.

enter image description here

2
votes

A late answer, but perhaps useful to those who still have the same problem. This method will work in windows Command prompt, cmd.

For /f %%i in ('az keyvault secret show --vault-name "Your-KeyVault-Name" --name "Your-Secret-Name" --query "value"') do set "password=%%i"

Now if you just run "echo %password%" you will see your secret value. Remember that az command has to be between ' ', like 'az keyvault secret etc'.