We have some jobs running Powershell against our Windows servers and I recently added a few lines of Powershell to one of them using
ansible.windows.win_powershell:
script: |
Despite this already being common usage throughout the file, the line I added is generating the following error:
The offending line appears to be:
$metaData= Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2025-04-07" -ErrorAction SilentlyContinue
^ here
There appears to be both 'k=v' shorthand syntax and YAML in this task. Only one syntax may be used.
Presumably it needs escaping in some way, as it’s perfectly valid Powershell code. Some searches variously showed people using quotes or curly brackets, but none had examples for Powershell. Alternatively, if anyone has any suggestions of alternatives (it just gets the meta data of the Azure VM), please feel free.
PS. the ^ here is below the first = in the original error message, not sure if the forum will keep that.
This is likely caused by a YAML indentation problem, but it’s hard to know for sure without seeing more of the YAML syntax.
For docs on YAML block scalars see:
To help catch Ansible YAML syntax problems right in your editor, consider installing an Ansible Language Server, which are packaged for popular editors like VS Code and Neovim.
Thanks, will have a read. I don’t use YAML that much as I mainly do native PS, so think my brain is pre-programmed to self-destruct on YAML spacing and indents. Here goes with a larger snippet for completeness:
- name: Run tasks on windows hosts
hosts: windows
gather_facts: no
vars_files:
- vars.yml
- predefined_vars.yml
tasks:
- name: Ping Test
win_ping:
ignore_errors: true
- name: Get VM Metadata
ansible.windows.win_powershell:
script: |
$metaData = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2025-04-07" -ErrorAction SilentlyContinue
if ($metaData) {
"Metadata"
}
else { write-warning "No metadata" }
I ran the YAML through ansible-lint and it appears to be fine.
The error is being thrown by Ansible’s YAML parser. Whether or not it’s a bug in the parser depends on whether the “k=v” syntax is intended to be supported for block scalars like this.
A workaround is move to your script to file and run it from there, like:
The error is probably unrelated to k=v syntax, that’s just a heuristic attempt to explain why parsing might have failed. The actual error will be printed before The offending line appears to be:, not after.