Bitbucket Pipelines: Using PS, how to use variables in JSON message

Suzanne August 23, 2024

Hello, I'm sending an alert to JSM/OpsGenie via PS Invoke-RestMethod in my Bitbucket pipeline. I'm trying to use variables in the JSON message. It works when I hard-code the value in the JSON message, the alert is updated in JSM. When I replace the value with a Bitbucket variable, it doesn't work. I do not get an error nor is JSM getting the alert. Does anyone have any ideas? I've tried using different combinations of double and single quotes as well as curly braces around the variable name but no luck. Thank you, Suzanne

Example: "id":"$env:TEAM_ID" 

- Invoke-RestMethod -Method Post -ContentType 'application/json' -Uri "https://api.atlassian.com/jsm/ops/api/$env:CLOUD_ID/v1/alerts" -Headers $HEADER -Body '{ "message":"Deployment failed - Test", "responders":[ { "id":"$env:TEAM_ID", "type":"team" } ], "visibleTo":[ { "id":"$env:TEAM_ID", "type":"team" } ], "alias":"Test 123 alert", "description":"Deployment pipeline test", "priority":"P1" }'

1 answer

0 votes
Patrik S
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
August 27, 2024

Hey @Suzanne ,

thank you for reaching out to Community!

In PowerShell, variables inside double-quoted strings are expanded, but only if they are not within single quotes. Your JSON body is enclosed in single quotes, which means that variables are not being expanded.

I would suggest construct the JSON body as a PowerShell object and then convert it to JSON using ConvertTo-Json :

$body = @{
message = "Deployment failed - Test"
responders = @(
@{
id = $env:TEAM_ID
type = "team"
}
)
visibleTo = @(
@{
id = $env:TEAM_ID
type = "team"
}
)
alias = "Test 123 alert"
description = "Deployment pipeline test"
priority = "P1"
}

Invoke-RestMethod -Method Post -ContentType 'application/json' -Uri "https://api.atlassian.com/jsm/ops/api/$($env:CLOUD_ID)/v1/alerts" -Headers $header -Body ($body | ConvertTo-Json)

Could you try that approach and let us know how it goes ?

Should you have any questions, feel free to ask.

Thank you, @Suzanne !

Patrik S 

Suzanne August 28, 2024

Thank you Patrik. I resolved my issue by concatenating a double and single quote on each side of the variable:   {"id":"' + $env:TEAM_ID + '"}

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events