简体   繁体   中英

Powershell - Read an environment Variable value and set the value in a Yaml file

In a Powershell session, I'm trying to read the value of the VAULT_TOKEN environment variable to set the value for a key (X-Vault-Token), and then save the output to a yaml file.The VAULT_TOKEN environment variable has a valid value, but I'm not able to get that value set for X-Vault-Token: $(env:VAULT_TOKEN) .

 # Create a YAML Document 
$RawYaml = @'
integration_name: com.monitor.sql
variables:
  Content:
    vault:
      http:
        url: https://vault.service.consul/v1/xyz/mssqlnr
        headers:
          X-Vault-Token: $(env:VAULT_TOKEN)
 '@

$RawYaml | out-File C:\Users\Public\Downloads\config.yaml  

I did refer to the link ( https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cpowershell&viewFallbackFrom=vsts#set-in-script ), and tried different options without any success. Please advice.

The issue is not with the way you invoke the variable but with the type of here-string you used, in PS when you use '' to define text, it does not expand any variable, example:

PS> $test =@'
>> $(5+5)
>> '@
PS> $test
$(5+5)

you need to use double quotes ", example:

PS> $test2 =@"
>> $(5+5)
>> "@
PS> $test2
10

so in you case it'll be like this:

# Create a YAML Document 
$RawYaml = @"
integration_name: com.monitor.sql
variables:
  Content:
    vault:
      http:
        url: https://vault.service.consul/v1/xyz/mssqlnr
        headers:
          X-Vault-Token: $env:VAULT_TOKEN
 "@

$RawYaml | out-File C:\Users\Public\Downloads\config.yaml  

That should fix it, good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM