Is it possible to clone a Variable Group between PROJECTS? - azure-devops

I know you can clone Variable Groups, but this is limited within the Project.
Is it possible to clone it to a different Project?

There is no such a feature to clone variable groups between Projects in azure devops UI portal.
However, you can achieve this using variable group rest api.
First, you need to call get variable group rest api to get the variables content.
GET https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups/{groupId}?api-version=5.1-preview.1
Then use add variable group rest api to add the a new variable group to another project with the variable content from the Get rest api.
POST https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups?api-version=5.1-preview.1
Please below powershell script example:
# Get the variable group in projectA
$url = "https://dev.azure.com/{organization}/{projectA}/_apis/distributedtask/variablegroups/{groupId}?api-version=5.1-preview.1"
$PAT = "Personal access token"
$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$result=Invoke-RestMethod -Uri $url -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method get -ContentType "application/json"
# Call add variable group rest api to add variable group in ProjectB
$updateurl = "https://dev.azure.com/{organization}/{projectB}/_apis/distributedtask/variablegroups?api-version=5.1-preview.1"
$body = $result | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri $updateurl -Headers #{Authorization = "Basic {0}" -f $base64AuthInfo} -ContentType "application/json" -Method post -Body $body
You can also use azure devops command line az pipelines variable-group create. See here for more information.

An approach - using curl, jq and xargs - that has worked for me:
curl -H "Content-Type: application/json" -X GET -u 'username':'<PAT>' 'https://dev.azure.com/<organization>/<url encoded source project-name>/_apis/distributedtask/variablegroups?api-version=6.1-preview.1' \
| jq -c '.value[] | del(.id, .createdBy, .modifiedBy, .createdOn, .modifiedOn)' \
| xargs -d'\n' -L1 -I'{}' \
curl -H "Content-Type: application/json" -X POST -u 'username':'<PAT>' -d "{}" 'https://dev.azure.com/<organization>/<url encoded target project-name>/_apis/distributedtask/variablegroups?api-version=6.1-preview.1'
The first curl command gets all available variable groups from the source project
jq removes the specified keys from each json object and outputs them line by line (-c)
xargs splits the input by newline (-d'\n') and passes each line (-L1) to the curl command, that creates a new variable group in the target project

Related

Translate cURL -F (--form) statement to PowerShell

I have a working cURL statement that takes the contents of a .csv file and posts them to a REST endpoint:
curl \
'https://app.sleuth.io/api/1/deployments/<ORG_SLUG>/<DEPLOYMENT_SLUG>/import_deploys' \
-H 'Authorization: apikey <APIKEY>' \
-F 'csv_file=#<FILENAME>.csv'
I am trying to convert it to PowerShell format, but can't seem to get there.
I am fairly new to APIs, so I've been using the Curl2PS tool for translating cURL commands to PowerShell, and it worked fairly well with other types, but it struggles with the -F (--form) parameter. This is what I get when I input the above cURL statement:
WARNING: The parameter '-F' is not yet supported. Please refer to curl man pages: https://curl.se/docs/manpage.html
Invoke-RestMethod -Method Get -Uri 'https://app.sleuth.io/api/1/deployments/<ORG_SLUG>/<DEPLOYMENT_SLUG>/import_deploys' -Verbose:$false -Headers #{
'Authorization' = 'apikey <APIKEY>'
}
It basically only does a partial job at converting the statement and skips the -F part completely, leaving it blank.
After some googling I tried using the -Infile method, but I probably did it wrong (again, noob here):
Invoke-RestMethod -Method POST -Uri 'https://app.sleuth.io/api/1/deployments/<ORG_SLUG>/<DEPLOYMENT_SLUG>/import_deploys'-Verbose -Headers #{
'Authorization' = 'apikey <APIKEY>'
'Content-Type' = 'multipart/form-data'
} -Infile '<FILENAME>.csv'
Unfortunately, I get a Bad Request (400) error.
I tried googling for a solution, but couldn't really find one, so any input here would be much appreciated.

Using GET in PowerShell & Exporting JSON to CSV

I'm using the following CURL command, to read/fetch table data from an API:
curl -X GET \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer *myAccessToken*' \
https://www.myWebsite.com/api/orders
This command/API Call returns a table in JSON format. I need to do two things with this.
[1] I need to run this in powershell. I've tried using the above code, and returns a general syntax error:
A parameter cannot be found that matches parameter name 'X'.
[2] In PowerShell, Have the JSON output converted & saved as a CSV file
Any ideas? Thanks!
You can use Invoke-RestMethod Cmdlet to Sends an HTTP or HTTPS request to a RESTful web service.
$uri = "https://www.myWebsite.com/api/orders"
$headers = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer <AccessToken>'
'Accept'= 'application/json'
}
$response = Invoke-RestMethod -Uri $uri -Method GET -Headers $headers
PowerShell formats the response based to the data type. For JavaScript Object Notation (JSON) or XML, PowerShell converts, or deserializes, the content into [PSCustomObject] objects. So you can select the columns you want to export and pipe it into Export-Csv Cmdlet
$response | Select ColumnName1,ColumnName2 | Export-Csv -Path "filename.csv" -NoTypeInformation

Download Artifactory Folder as an Archive using PowerShell

I'm trying to download an Artifactory folder as a tar.gz file using the PowerShell command line. In Bash, the following command does the job:
curl -i -v -XGET -H 'X-JFrog-Art-Api:<my API key>' "https://artifactory.<myrepo.com>/path/to/files?archiveType=tar.gz" --output ./file_location/filename.tar.gz
In PowerShell, however, this doesn't seem to work:
Invoke-RestMethod -uri "https://artifactory.<myrepo.com>/path/to/files?archiveType=tar.gz" -Method 'Get' -OutFile .\file_location\filename.tar.gz -H #{'X-JFrog-Art-Api' ='<my API key>';'Content-Type'='multipart/form-data'}
This operation creates filename.tar.gz, but the file is just a HTML file giving the directory structure rather than the actual files.
If I only want an individual file, I can use PowerShell to download files (not an archive) with:
Invoke-RestMethod -uri "https://artifactory.<myrepo.com>/path/to/files/filename.xyz" -Method 'Get' -OutFile .\file_location\filename.xyz -H #{'X-JFrog-Art-Api' ='<my API key>';'Content-Type'='multipart/form-data'}
And filename.xyz is transferred to the local machine. So I'm a bit confused with why the tool to make an archive fails.
I figured it out!
Invoke-RestMethod -Uri "https://my-artifactory-server/artifactory/api/archive/download/path/to/some/folder?archiveType=zip -Method "Get" -Headers #{"Authorization"="Basic $my_artifactory_api_token"; 'Content-Type'='multipart/form-data'} -Outfile c:\destination_location\folder.zip
You need to add "api/archive/download" to the Uri, after the hostname.

Powershell Multi-part-form-data convert from curl

I'm trying to run a powershell script to perform an invoke-webrequest using the -ContentType multi-part/form-data parameter.
I have an example of a working curl command and need to convert it to powershell.
curl -v -u user#yourcompany.com:test -F "helpdesk_ticket[attachments][][resource]=#/path/to/attachment1.ext" -F "helpdesk_ticket[attachments][][resource]=#/path/to/attachment2.ext" -F "helpdesk_ticket[email]=example#example.com" -F "helpdesk_ticket[subject]=Ticket Title" -F "helpdesk_ticket[description]=this is a sample ticket" -X POST https://domain.webaddress.com/helpdesk/tickets.json
I have tried to do this with hash tables but having no luck.
So far I have:
$body = #{"helpdesk_ticket[attachments][][resource]"="$/path/to/attachment.ext";"helpdesk_ticket[email]"="example#example.com"; "helpdesk_ticket[subject]"="Ticket Title"; "helpdesk_ticket[description]"="this is a sample ticket"}
Invoke-WebRequest -Uri https://domain.webaddress.com/helpdesk/tickets.json -Headers $FSHeaders -ContentType multi-part/form-data -Body $Body -Method POST
The error returned suggests the data in the body is incorrect as authentication (hidden in the header variable) is correct.

Convert Gitlab CI Trigger Curl to Powershell Invoke-RestMethod

Does anyone know if it's possible to convert the curl command used to trigger builds in Gitlab-CI to a Powershell equivalent using Invoke-RestMethod?
Example curl command:
curl --request POST \
--form token=TOKEN \
--form ref=master \
--form "variables[UPLOAD_TO_S3]=true" \
https://gitlab.example.com/api/v3/projects/9/trigger/builds
This was taken from Gitlab's documentation page.
I found quite a few postings about converting a curl script for Powershell but I haven't had any luck in getting it to work. Here are some of the links I referenced:
How to send multipart/form-data with PowerShell Invoke-RestMethod
PowerShell equivalent of curl
Running curl via powershell - how to construct arguments?
Any help would be appreciated.
You can pass the token and the branch parameters directly in the URL. As for variables, putting it into the body variable should do the trick.
$Body = #{
"variables[UPLOAD_TO_S3]" = "true"
}
Invoke-RestMethod -Method Post -Uri "https://gitlab.example.com/api/v3/projects/9/trigger/builds?token=$Token&ref=$Ref" -Body $Body
Alternatively you can pass all arguments in the body parameter:
$form = #{token = $CI_JOB_TOKEN;ref = $BRANCH_TO_BUILD; "variables[SERVER_IMAGE_TAG]" = $CI_COMMIT_REF_NAME}
Invoke-WebRequest -Method POST -Body $form -Uri https://gitlab.example.com/api/v4/projects/602/trigger/pipeline -UseBasicParsing