Search code examples
windowsamazon-web-servicespowershellpowershell-3.0

How to set private key as environment variable in powershell


I have assigned output of aws command to a variable:

$SECRET_KEY = (aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:12345:secret:non-prod/testing/private-key-8PPof --query 'SecretString' --output text)

Now i want to export the output of this to environment variable.

if i use below

$env:SECRET_KEY=$SECRET_KEY >> output formatting is messed up and everything is coming in one line with spaces for the key instead of newline

Can anyone help with how to export the output of the aws command as environment variable to the powershell cli


Solution

    • Environment variables are invariably strings.

    • In PowerShell, if you assign a value other than a string, that value is automatically stringified (converted to a string)

      • PowerShell reports stdout output from external programs such as aws as a stream of lines, which when captured, become an array of strings (lines).

      • PowerShell stringifies arrays by joining their elements with a single space as the separator,[1] which explains what you saw; a simple example:

        $arr = 1, 2; "$arr" # -> '1 2'
        
    • In order to assign a multiline string to an environment variable based on output from an external program, you'll have to join the lines explicitly with a newline as the separator.

    Therefore:

    $env:SECRET_KEY = 
     (
       aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:12345:secret:non-prod/testing/private-key-8PPof --query 'SecretString' --output text
     ) -join "`n"
    

    Note: The above uses Unix-format LF-only newlines ("`n"); to use Windows-format CRLF newlines, use "`r`n"


    [1] The - rarely used - $OFS preference variable can normally be used to change the default separator. Curiously, however, it has no effect on the implicit stringification that happens on assigning to an environment variable.