0

I have the following PowerShell API script:

$VMname = "abcd"
$IP_address = '2.2.2.2'

$url = "https://ansibletower.xyz.com/api/v2/job_templates/12321/launch/"
$token = "9998980fsfdfsdfdf"
$headers = @{Authorization = "Bearer $token"}
$contentType = "application/json"
$method = "POST"

#### $body = '{"extra_vars": {"vm_name": "abc", "vm_ip_address": "2.2.2.2"}}'
$body = '{"extra_vars":{"vm_name":'$VMname', "vm_ip_address":'$IP_address'}}'

Invoke-RestMethod -ContentType "$contentType" -Uri $url -Method $method -Headers $headers -Body $body 

When I try it with manually predefined values in the body (see the commented body line above) - it works. But when I try it with variables $VMname and $IP_address, I get the error:

Unexpected token '$VMname', "vm_ip_address":'$IP_address'}}'' expression or statement.

And if I remove single quotes before and after variables VMname and IP_address I get:

{"detail":"JSON parse error - Expecting value: line 1 column...Possible cause: trailing comma."}

It is obviously a problem with syntax and / or formatting but I cannot find the solution. Does anyone know?

1
  • 1
    Single-quoted strings don't apply variable substitution. Use double quoted strings with escaping, or more conveniently, use ConvertTo-Json to convert plain old PowerShell objects/hashtables to JSON rather than interpolating anything (@{extra_vars=@{vm_name=$VMname; vm_ip_address=$IP_address}}|ConvertTo-Json). As a bonus this will also take care of any JSON string escaping that might be necessary, which interpolation won't do. Commented Dec 22, 2022 at 10:36

1 Answer 1

2

Use ConvertTo-Json for this:

$VMname = "abcd"
$IP_address = '2.2.2.2'
$body = ConvertTo-Json -Compress -Depth 9 @{
    extra_vars = @{
        vm_name = $VMname
        vm_ip_address = $IP_address
    }
}

$Body
{"extra_vars":{"vm_name":"abcd","vm_ip_address":"2.2.2.2"}}

Btw, it is probably not even required to serialize your body to Json as Invoke-Restmethod is supposed to take care of that:

-body

When the input is a POST request and the body is a String, the value to the left of the first equals sign (=) is set as a key in the form data and the remaining text is set as the value. To specify multiple keys, use an IDictionary object, such as a hash table, for the Body.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.