can you use IF statement in inline Azure Powershell script in Azure Devops? - azure

I have a task in Azure Devops which builds a VM
Task 1 builds a VM
Task 2 adds datadisks if required
so in task 2 I have an inline powershell script but when i run it it gives an error
" The term 'n' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Not sure why it is giving the error?
"
###Azure Devops pipeline variable is $(datadisk1required) this has the value 'n'
$datadisk1required = $(datadisk1required)
if ($datadisk1required -eq "n")
{
write-host "datadisk1 not required"
write-host $datadisk1required
}

The substitution of AzDO variables in the script happens before PowerShell runs, and that means that if the inline script definition is:
$powerShellVariable = $(azVariable)
and the value of the azVariable variable in the task is "string", the resulting script passed to PowerShell will be:
$powerShellVariable = string
PowerShell will interpret the bare word string as a command name, hence the error.
Put quotation marks in place around the AzDO variable macro and it'll work:
$datadisk1required = '$(datadisk1required)'

Related

Assign Azure Powershell variable to DevOps Pipeline variable

How can I assigned the $NewIP variable precalculated in this step to a DevOps pipeline variable called $pipeline_ip?
You should use logging command if you want to assign powershell variable to Azure DevOps variable
echo "##vso[task.setvariable variable=pipeline_ip;]$NewIP"
Update after clarification:
If you use syntax like:
$NewIP = $(pipeline_ip)
Then $(pipeline_ip) would be replaced with the value before script will be executed.
And if you use syntax like
$NewIP = $env:PIPELINE_IP
then you will refer to environment variable and since all DevOps variables are mapped (except secret variables - here you need to express this excplicitly) it would also work.
However, these are two ways of doing that.
You can use two methods:
$NewIP = $(pipeline_ip) Macro syntax variables
$NewIP = $env:PIPELINE_IP Set variables in pipeline

How to set an environment variable with PowerShell in Azure Devops release pipeline?

I have a function which will return a result. I am setting that result as an environment value in a pipeline. When I am invoking environment variable it's not printing the next two lines.
Write-Host "Before env : $result"
write-host "##vso[task.setvariable variable=message]$result"
[![enter code here][1]][1]
In other stage I invoked message other variable but it's not printing the next two lines.
write-host "After env : $(message)"
[![enter code here][2]][2]
My only challenge was not getting the last two lines which is ASDB_REPORT / ASDB_REPORT_TEST
If you set an environment variable with PowerShell in release pipeline, please refer to this doc: Set variables in scripts.
$result = 'crushed tomatoes'
Write-Host "##vso[task.setvariable variable=sauce]$result"
# Write-Host "sauce: $(sauce)"
Please note that "Subsequent steps will also have the pipeline variable added to their environment. You cannot use the variable in the step that it is defined." Thus you could access to the new variable with macro syntax and in tasks as environment variables.
Write-Host "sauce: $(sauce)"
Write-Host "my environment variable is $env:SAUCE"
However, you can't pass a variable from one job to another job or from one stage to another stage of release pipeline, unless you use multi-stages YAML. Please refer to Set a multi-job output variable for details.

Azure DevOps Yaml: Gaining secret variable out of Azure KeyVault Task from Variable

I'm trying to obtain a secret out of my KeyVault.
The variable name is secretVar.
Obtaining the secret like this: $(secretVar) works fine however I would like to retrieve it from a variable like this:
I keep getting command not found and I've no idea why this shouldn't be working.
So the name of the secret I want to extract is inside a bash variable. For this question I've simplified the problem but in my real use case I have a bash for loop which loops through secret names and inside the for loop I want to extract the appropriate value from the KeyVault with the corresponding secret name like this:
for secretname in secrets; do
echo $($secretname) # This should contain the value of the secret but gives command not found
done
If anyone has an idea what could be happening, any help is very appreciated.
Thanks in Advance!
Look at the syntax you're using.
variable=secretVar
You are creating an environment variable with the literal value secretVar
Then you try to execute the value of the variable $variable with $($variable). So it tries to run the command secretVar, which obviously doesn't exist, and you get an error message.
The syntax you're looking for is
variable=$(secretVar)
just like you used in the first echo command in the script.
If you don't want to run the variable value as a command, the syntax would be $variable, not $($variable)
$variable is the syntax for a Bash environment variable.
$(variable) is the syntax for referencing Azure DevOps variables.
First of all, the script keyword is a shortcut for the command-line task. The task runs a script using cmd.exe on Windows and Bash on other platforms. You need to pay attention to the agent you are using.
If you want to set variables in scripts, you can use task.setvariable logging command. For example:
- script: |
echo $(secretvar)
echo "##vso[task.setvariable variable=variable]$(secretvar)"
- script: |
echo $(variable)
You can find more detailed information in this document.

How to unpack or fetch a value of a nested variable stored in Azure DevOps Build Piplines' Variables group?

Is it possible to use variable inside a variable in Powershell script with Azure Pipelines variables?
SCENARIO
Two variables are set in Azure Pipelines Variable group - DeploymentCredentials
a. DeployUATApiPassword = "123456"
b. DeployPRODApiPassword = "789654"
Another variable is set in the Variables section of the pipeline as DeploymentEnvironment
At runtime, the value of the DeploymentEnvironment variable is set as either UAT or PROD
Based on the enviornment, I want to fetch the password which is stored as a variable, defined in the variables group. At runtime, it should work something like...
# setting the value of the variable to UAT
Write-Host "##vso[task.setvariable variable=DeploymentEnvironment]UAT"
Now DevelopmentEnvironment variable has the value UAT, In another step, I want to fetch the Password for the UAT deployment environment, which is only known at runtime.
# I want to get the Password
# The following works! but not useful for me, UAT is hard-coded!!
$deployPwd = $(DeployUATApiPassword) # works! but not useful for me, UAT is hard-coded!!
# I want to get the Password
# the following doesn't work, I only know the environment at runtime
# Replaces the inner variable to `DeployUATApiPassword`
# Raises an error, DeployUATApiPassword : The term 'DeployUATApiPassword' is not recognized as the name of a cmdlet...
$deployPwd = $(Deploy$(DeploymentEnvironment)ApiPassword)
# All the following didn't work either, but no error...
Write-Host $('Deploy$(DeploymentEnvironment)ApiPassword') # Output: DeployUATApiPassword
Write-Host $($("Deploy$(DeploymentEnvironment)ApiPassword")) # Output: DeployUATApiPassword
Write-Host { 'Deploy$(DeploymentEnvironment)ApiPassword' } # Output: 'DeployUATApiPassword'
Write-Host { Deploy$(DeploymentEnvironment)ApiPassword } # Output: DeployUATApiPassword
Write-Host { $(Deploy$(DeploymentEnvironment)ApiPassword) } # Output: $(DeployUATApiPassword)
Similarly, I tried to fetch the pwd in several ways, nothing worked.
For instance, one of the ways was to create another variable DeployApiPassword and I did set the value of the variable to Deploy$(DeploymentEnvironment)ApiPassword. No luck in this either...
$deployPwd = $(DeployApiPassword) # Output: DeployUATApiPassword
DESIRED OUTPUT
I want to fetch the password from one of the variables which is set in a variables group. The password variable name contains the deployment environment. Deployment environment is only set at runtime.
# I know something is wrong with the following, but that's how I want to run.
$deployPwd = $(Deploy$(DeploymentEnvironment)ApiPassword)
Write-Host $deployPwd # output: *** (of course, the pwd is hidden, but at least it fetches)
Variables set in Azure Pipelines Variable group would be used as environment variables in PowerShell task. So, basically, you need to get the value as :
$environment = $env:DeploymentEnvironment
$deployPwd = $env:DeployUATApiPassword
At the same time, as your want to dynamically get the password based on the environment, you may try the following:
$environment= $env:DeploymentEnvironment
Write-Host "Deployment Environment is " $environment
$realName = $("Deploy${environment}ApiPassword")
$pwd = [Environment]::GetEnvironmentVariable($realName)
#I used UAT password, check it here
Write-Host $pwd.Equals("123456")
Output:
I noticed that the value returned by 'Deploy$(DeploymentEnvironment)ApiPassword' is a string type, however $() accepts a variable not a string.
In the secret variables official document, it says the secret cannot be referenced directly like normal variable. You have to manually explicitly map them in using the Environment section.
You will need to use if statement. And in the Environment Variables sections
Map the secret variables to variables UATpassword and PRODpassword and Then refer to them in the scripts using $env:UATpassword
From below log, we can see the password is retrieved in the script.

Calling a PowerShell script from Azure batch custom activity

I am trying to run a PowerShell script from within an Azure, Data Factory, Batch Service, Custom Activity. The closest I've gotten to this working is the following:
powershell powershell -command '$env:AZ_BATCH_TASK_DIR\wd\processInAzure.ps1'
When I run this I get the following error message
At line:1 char:23
+ $env:AZ_BATCH_TASK_DIR\wd\processInAzure.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '\wd\processInAzure.ps1' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I've been able to get a directory listing of $env:AZ_BATCH_TASK_DIR\wd and see that processInAzure.ps1 exists at this location. I've been able to Write-Host "Hello from Azure" so I can see powershell is working. What I'm not getting is how to reference the ps1 script file using an environment variable. Would anyone know the syntax sugar to get this working?
With Architect Jamie's input (including his deleted edit!!! Put edit back it directly led to the solution) I was able to put a few things together to get this to work. The double powershell at the beginning of the command line is not a typo BTW. This is what ended up working:
powershell powershell -command ("$env:AZ_BATCH_TASK_DIR" + '\wd\processInAzure.ps1')
What didn't work is the following:
powershell powershell -command ("$env:AZ_BATCH_TASK_DIR" + "\wd\processInAzure.ps1")
powershell powershell -command ("$env:AZ_BATCH_TASK_DIR\wd\processInAzure.ps1")
powershell -command ("$env:AZ_BATCH_TASK_DIR" + '\wd\processInAzure.ps1')
Try this:
powershell -command "$($env:AZ_BATCH_TASK_DIR)\ws\processInAzure.ps1"
It's not possible to access object member properties or methods inside single quote qualified strings. Using the double quote in PowerShell allows you to expand variables at runtime.
Edit:
Though the above is true, in this instance the reason for the error is that PowerShell is treating the path being tacked on as part of the environment variable identifier. Using $() variable expansion as above will work, and you should also be able to use ('$env:AZ_BATCH_TASK_DIR' + '\ws\processInAzure.ps1')

Resources