Execute azure command in powrershell without writing error to console? - azure

I am using powershell script in pipeline and the problem I have with this query.
$value = $(az appconfig kv show -n ThisisEnv --key thisisconfigkey) | ConvertFrom-Json
What this query does is get the data related to key if exist. If this key doesn't exist it give the error like
ERROR: Key 'abcdefg' with label 'None' does not exist.
It is work as expected. In pipeline when the key doesn't exist, it's printed a error on CLI. The pipeline see it as error and show it as failed. Is there a way I can make it work.
Is there a way I can stop it printing it on console. Any powershell operator which help me to get the value from azure command but also let me get it without print anything on console.

You could try to redirect the standard error using 2> $null
$value = $(az appconfig kv show -n ThisisEnv --key thisisconfigkey 2> $null) | ConvertFrom-Json
This will suppress the error within the console. You might also want to set the powerShellIgnoreLASTEXITCODE within the Azure CLI Task in order that the pipeline run doesn't fail - or as a workaround, set the $LASTEXITCODE to 0

Related

Why is azure CLI adding 0 to my returned list

I'm working with azure CLI to build out some automation around repo creation, etc. I'm using python as a sort of wrapper around various CLI commands to bundle up the automation. I want to write in a simple check to see if a repo name has been used and exists or not.
repoName comes from a system input and would be whatever the user wants to name their fresh repository.
So far I have this:
azRepoListCmd = "az repos list --query \"[?contains(name, \'" + repoName + "\')].[name]\" --organization https://myOrganizationHere.visualstudio.com/ --project myProject -o tsv"
azRepoList = os.system(azRepoListCmd)
print(azRepoList)
what the above returns is :
test-project-2
0
What is this "0" and where does it come from? Expected result would just be the name or an empty array if it didn't find anything.
The 0 is the resultcode of running os.system, which doesn't capture output.
https://docs.python.org/3/library/os.html#os.system
So your azRepoList = ... line is actually what's outputting the repo name, then the next line is outputting the result code.
What you want instead is subprocess.
import subprocess as sp
output = sp.getoutput("az repos list --query \"[?contains(name, 'PartsUnlimited')].[name]\" --project \"Parts Unlimited\" -o tsv")
print (output)
PartsUnlimited

Get KeyVault Get Access Policies via Powershell AZ CLI

I am trying to read in the access policies using the az cmdlets but struggling to do this. I thought this would work
$foo = az keyvault show -g "my-rg" -n "my-kv"
This returns a value back and was hoping to do:
$accessPolicies = $foo.accessPolicies
However this returns a null. I did notice the output produces properties so I also tried
$accessPolicies = $foo.properties.accessPolicies
Clearly doing something wrong here. Any ideas how I do this?
You could directly query the accessPolicies properties from the Azure CLI command.
$accessPolicies = az keyvault show -g "my-rg" -n "my-kv" --query 'properties.accessPolicies'
The --query parameter needs the JMESPath query string. See http://jmespath.org/ for more information and examples.
If you want to use the PowerShell commands, you can do it like this:
$accessPolicies= (Get-AzKeyVault -vaultname "my-kv" -resourcegroupname "my-rg").AccessPolicies

Manipulating output return from az cli command in powershell or azcli

I ran the following AZ cli command below, whilst it provided me with the information I was after, I could not filter or select the columns I wanted.
az pipelines list --org org_url --project az_project --out table
I am after the name and status column only, and would like to filter on where the name matches the string "dev"
Another option i looked at was piping this out in Powershell
$output = az pipelines list --org org_url --project az_project --out table
$output | select-object name, status
I found that this didnt work either, as looking at the members of $output suggests it was not converted to a custom object. I am thinking there must be a way to do this in powershell.
Credit to #AdminOfThings
This is what I was trying to do.
az pipelines list --org org_url --project az_project | ConvertFrom-Json -Depth 10 | Select Name,Status | where {$_.Name -like "*name*"}

Unable to register Patch baselineid with Patch Group by aws cli

I am registering patch baseline with Patch Group by AWS CLI and I am getting an error as mentioned in the subject.
Command used to create a Patch baseline is below:
baselineid=$(aws ssm create-patch-baseline --name "Test-NonProd-Baseline" --operating-system "WINDOWS" --tags "Key=Environment,Value=Production" --approval-rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important]},{Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,ServicePacks,UpdateRollups,CriticalUpdates]}]},ApproveAfterDays=7}]" --description "Baseline containing all updates approved for production systems" --query BaselineId)
I used then above id to register patch baseline with patch group as like below
aws ssm register-patch-baseline-for-patch-group --baseline-id $baselineid --patch-group "Group A"
Unfortunately, I get the error below:
An error occurred (ValidationException) when calling the RegisterPatchBaselineForPatchGroup operation: 1 validation error detected: Value '"pb-08a507ce98777b410"' at 'baselineId' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9_\-:/]{20,128}$.
Note: Even if I use double quotes around "$baslineid" still I do get the same error.
Variable $baselineid has a valid value, please see below:
[ec2-user#ip-172-31-40-59 ~]$ echo $baselineid
"pb-08a507ce98777b410"
Want to understand what is the issue when I'm getting a legit value and how to have it resolved.
You can perhaps use this in your second command, basically using tr utility to truncate the double qoutes:
echo $baselineid| tr -d '"'
The solution to the double quote issue has many possible fixes in this SO post:
Shell script - remove first and last quote (") from a variable
So a possible solution command could be something like this:
aws ssm register-patch-baseline-for-patch-group --baseline-id $(echo $baselineid| tr -d '"') --patch-group "Group A"

Can't set variable using Azure CLI within DevOps Release Pipeline

I'm trying to save a key value to pass on to the next step in my release pipeline, but no matter what I do I can't save the result of my command to a variable. I've already checked many of the articles here dealing with this with no success. Here is what I am trying:
$KEY=(az storage account show-connection-string --key primary -n myStorageAccount -g myResourceGroup --query "connectionString" -o tsv)
echo "Attempting to set variable"
echo $KEY
echo ##vso[task.setvariable variable=AZURE_STORAGE_CONNECTION_STRING;]$KEY
echo $AZURE_STORAGE_CONNECTION_STRING
Running on Windows Agent by the way. I've tried all kinds of variations: SET KEY=, SET $KEY=, SET $(KEY)=, $KEY=, $(KEY)=, KEY=, none of it works. Likewise I've tried referencing the variable differently in the echo statements with no luck. If I just run the az storage account command, I do get back the connection string. But either I get that $KEY is not a recognizeable command or if I'm using SET, echo simply gives me back $KEY and the vso line gives me nothing.
I can accomplish most of this, including saving to variable, in Azure Cloud Shell (via syntax $KEY= and echo $KEY). But of course that doesn't help my pipeline. Any idea the proper syntax to get this value into my next release pipeline step, or is the another method to accomplish this?
Can't set variable using Azure CLI within DevOps Release Pipeline
If you are using Azure CLI version 1.*, try to use following scripts:
for /f "tokens=1 USEBACKQ" %%F in (`Yourcommand`) do echo ##vso[task.setvariable variable=AZURE_STORAGE_CONNECTION_STRING;]%%F
If you are using Azure CLI version 2.*, you can also use a powershell command:
$KEY= & YourCommand
Write-Output("##vso[task.setvariable variable=AZURE_STORAGE_CONNECTION_STRING;]$KEY")
Check this thread for some more details.
Hope this helps.

Resources