Use data from variable in bash - bash

This is what I am trying to do in bash. Here is a PowerShell example:
$metaData = Invoke-RestMethod -Headers #{"Metadata"="true"} -URI http://169.254.169.254/metadata/instance?api-version=2019-04-30 -Method GET
$azEnv = $metadata.compute.azEnvironment
The above command gives me the value of azEnviroment from the Json output and saves that as a variable called $azEnv.
How can I do this in bash?

You can do something like this,
PC_VMSIZE=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2018-10-01" | jq -r '.compute.vmSize')
export AZHPC_VMSIZE=${AZHPC_VMSIZE,,}
#echo "Running on $PC_VMSIZE"

Related

How To set Azure pipeline variable from PowerShell

I am trying to set the Azure pipeline variable value in PowerShell. I have created one variable winversion in the Azure pipeline. Now, in a PowerShell task, I want to assign some values to the winversion variable.
My simple question is how can I change the value of an Azure PipeLine variable at run time?
Write-Host "Main value is $winversion"
$env:WINVERSION="abhinav";
Write-Host "Modified value is $env:WINVERSION"
Write-Host "Main value is $(winversion)"
Firstline print: original value is 123
Thirdline Print: Modified value is abhinav
Fourth Line print: 123
I want when I change the value of winversion from "123" to "abhinav" so it actually changes the pipeline variable value to abhinav.
I want to update this variable through Powershell. I am using one PowerShell script calling the API and trying to update its variable but getting the page not found error:-
param(
[string]$winVersion
)
$body = "{ 'definition' : { 'id' :85}
}"
$valueName="Winver"
$definitionId=85
$User=""
$Password=""
$base64authinfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $Password)))
$Uri = "https://Muac.visualstudio.com/OSGCXE/_apis/release/releases?api-version=2.0"
$urlDef = "https://Muac.visualstudio.com/OSGCXE/_apis/release/definitions/" + $definitionId + "?api-version=2.0"
$definition = Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64authInfo)} -Method Get -Uri $urlDef
#Write-Host $definition
$definition.variables.$valueName.Value = "$winVersion"
$definitionJson = $definition | ConvertTo-Json -Depth 50 -Compress
#Write-Host (ConvertTo-Json $definition -Depth 100)
$update=Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64authInfo)} -Method Put -Uri $urlDef -Body $definitionJson -ContentType "application/json"
#Write-Host "$update"
#$buildresponse = Invoke-RestMethod -Method Post -ContentType application/json -Uri $Uri -Headers #{Authorization=("Basic {0}" -f $base64authinfo)} -Body $body
#write-Host $buildresponse.status
How To set azure pipeline variable from PowerShell
There is a bit of confusion here, you use the variable $winversion in the powershell scripts, but the variable is set testvar in the pipeline variable.
Anyway, no matter we overwrite the pipeline variable value directly like you, or use the script "##vso[task.setvariable variable=testvar;]testvalue" to overwrite it, the overwrite value only work for current build pipeline. When you use the $(winversion) to get the value, it will still pull the value from pipeline variable value. To get the current value, you need use $env:WINVERSION.
Besides, you said:
I want when I change the value of winversion from "123" to "abhinav"
so it actually changes the pipeline variable value to abhinav.
If you mean you want change the pipeline variable value on the web portal, you need the REST API (Definitions - Update) to update the value of the build pipeline definition variable from a build task.
There is a very similar thread, you can check the answer for the details:
How to modify Azure DevOps release definition variable from a release task?
Note:Change the API to the build definitions:
PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0
Hope this helps.
I found this link helpful: https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=powershell
This has the complete options of what you can do:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch
You can reuse set variable from task to task, and also job to job.
I couldn't find anything on stage to stage.
In summary:
jobs:
# Set an output variable from job A
- job: A
pool:
vmImage: 'vs2017-win2016'
steps:
- powershell: echo "##vso[task.setvariable variable=myOutputVar;isOutput=true]this is the value"
name: setvarStep
- script: echo $(setvarStep.myOutputVar)
name: echovar
# Map the variable into job B
- job: B
dependsOn: A
pool:
vmImage: 'ubuntu-16.04'
variables:
myVarFromJobA: $[ dependencies.A.outputs['setvarStep.myOutputVar'] ] # map in the variable
# remember, expressions require single quotes
steps:
- script: echo $(myVarFromJobA)
name: echovar

How call invoke-expression to pass arguments when calling a remote script in powershell? [duplicate]

This question already has answers here:
What is shortest possible way to download script from HTTP and run it with parameters using Powershell?
(2 answers)
Closed 1 year ago.
My script content:
param (
[string]$arg1 = "2.2.2",
[string]$arg2 = "master"
)
& {
Write-Host "show $arg1 and $arg2 .."
}
Then I want to call this script in remote machine via http.
Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content
But I don't know how to pass parameters to the script. Like this?
Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content -arg1 2.2.1 -arg2 dev
How can help me? thanks!
If I do not pass arguments, the following commands are working fine.
Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content
Download the code, create a scriptblock from it, and provide the arguments when calling Invoke() on the scriptblock.
$script = Invoke-RestMethod -Uri 'https://gist.githubusercontent.com/gittorta/75838602b2712d49c44e85ea0bc179e9/raw/8392f437943f66d47731423b674b81bd74378e4b/myscript.ps1'
$sb = [scriptblock]::Create($script)
$arg1 = "test1"
$arg2 = "test2"
$sb.Invoke($arg1, $arg2)
Output
show test1 and test2 ..
Same command condensed into a one-liner
([scriptblock]::Create((Invoke-RestMethod -Uri 'https://gist.githubusercontent.com/gittorta/75838602b2712d49c44e85ea0bc179e9/raw/8392f437943f66d47731423b674b81bd74378e4b/myscript.ps1'))).Invoke("test1", "test2")

Cannot get value from bash shell output for pg_isready to a variable

I'm trying to get the value for the bash binary call pg_isready to a bash variable
I've tried the following in my script:
#!/bin/bash
haspostgresdb = ${pg_isready -h "ipaddress"}
echo $haspostgresbd
haspostgresdb = ${pg_isready -h ipaddress}
echo $haspostgresbd
haspostgresdb = ${pg_isready -hipaddress}
echo $haspostgresbd
haspostgresdb = ${pg_isready -h"ipaddress"}
echo $haspostgresbd
All return bad substitution as the response. And I did some research and it looks like im doing it correctly
Any suggestions?
Use command substitution and get rid of blanks in the assign command:
haspostgresdb="$(pg_isready -h "ipaddress")"

Powershell - 'PUT' files to URL that require parameters

I've been trying for a while now to find a way in Powershell to take a list of files and upload them to a URL. (ive been able to do it in Unix Bash no problem).
However, I think there are issues with the parameters passing in and the URI building - causing a 500 internal server Error.
What I currently have is this:
$logfiles = "\\location\trace\logs"
$buildName = "NewBuild"
$EngineName = "DefaultEngine"
$request = "http://localhost:9005/parser/singleUploadTracerLib.do?
blockingUpload=true&autocommit=true&tracerSetName=$buildName&$EngineName"
foreach($f in $logfiles | Get-ChildItem) {
Invoke-WebRequest -Uri $Url -Verbose -Method PUT `
-InfileĀ $f.FullName -ContentType 'application/octet-stream'
}
When I do this in bash - i have no issues (see below for comparison) so i assume I need to pass in the prams another way?
In Bash(works):
ls -N ${pathToLogs} | grep clean | sort | xargs -I {} echo "-F
inputs[]=#${pathToLogs}{}" | xargs curl -X POST
"${Url}/parser/singleUploadTracerLib.do?
blockingUpload=true&autocommit=true&
tracerSetName=${buildName}&EngineName=${engineName}"
any kind person got any ideas? it would be much appreciated.

Posting to Twitter account using Windows .bat file code

I'm trying to setup an automatic tweet script that runs after a git commit. I'm using Windows 7 have curl available in the command line.
I'm not sure how to set variables with the language windows scripts run and also am not positive about the oauth process.
I have the api key and secret, and also the consumer key and secret but I'm just not sure how to wrap it all together.
Here is a paper clipped mashup of code I'm trying to use as a foundation:
#!/bin/sh
# PATH modification needed for http_post and oauth_sign
export PATH=$PATH:/usr/local/bin
toplevel_path=`git rev-parse --show-toplevel`
toplevel_dir=`basename "$toplevel_path"`
branch=`git rev-parse --abbrev-ref HEAD`
subject=`git log --pretty=format:%s -n1`
hashtags="#code #$toplevel_dir"
tweet=$hashtags' ['$branch']: "'$subject'"'
# truncate tweets that are longer than 140 characters
if [ ${#tweet} -gt 140 ]
then
tweet_trunc=$(echo $tweet | cut -c1-137)
tweet=${tweet_trunc}...
fi
//set vars
consumer_key="mPijnvYpD0sHAY8r*******"
consumer_secret="OWuvuyQeYrT3ToJgyvNdR6baNuDldmTDF5IIJCI************"
access_token="2476143012-ld78CrgnNY3kUmD0QRdvIchXeDC13nO3********"
access_secret="3HTdOlf8jCVzPi5I9usV7rIbGFtM5f****************"
//build oauth
//post data
//example curl code found during research
curl --request 'POST' 'https://api.twitter.com/1.1/statuses/update.json' --header 'Authorization: OAuth oauth_consumer_key="mPijnvYpD0sHAY8r6fkox0KBj", oauth_nonce="OWuvuyQeYrT3ToJgyvNdR6baNuDldmTDF5IIJCIablQbyHA2PS", oauth_signature="Ba6IB8uH2SjtrK8a%2FgZnqCgvIKs%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1346207448", oauth_token="14814762-vvYtBOLX8hBAQ0i0f1k4wxrioG1jOk49MJrqn3myE", oauth_version="1.0"' --verbose -F "media[]=#mack.jpg" -F "status=Test from cURL" --header "Expect: "
Any help at all is appreciated.
Bro, on Windows you should use PowerShell now. .bat is lame!
$toplevel_path = git rev-parse --show-toplevel
$toplevel_dir = Split-Path $toplevel_path -Leaf
$branch = git rev-parse --abbrev-ref HEAD
$subject = git log --pretty=format:%s -n1
$hashtags = "#code #$toplevel_dir"
$tweet = '{0} [{1}]: "{2}"' -f $hashtags, $branch, $subject
if ($tweet.length -gt 140) {
$tweet = $tweet.substring(0,137)
}
$oauths =
'oauth_consumer_key="mPijnvYpD0sHAY8r6fkox0KBj"',
'oauth_nonce="OWuvuyQeYrT3ToJgyvNdR6baNuDldmTDF5IIJCIablQbyHA2PS"',
'oauth_signature="Ba6IB8uH2SjtrK8a%2FgZnqCgvIKs%3D"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="1346207448"',
'oauth_token="14814762-vvYtBOLX8hBAQ0i0f1k4wxrioG1jOk49MJrqn3myE"',
'oauth_version="1.0"'
$header = 'Authorization: OAuth {0}' -f ($oauths -join ',')
curl --verbose --request POST -F 'media[]=#mack.jpg' `
-F 'status=Test from cURL' --header 'Expect: ' `
--header $header https://api.twitter.com/1.1/statuses/update.json
command substitution is actually better than with Bash
PowerShell "printf" is cool
arrays are cool
the continuation character ` is too small though, hard to see

Resources