Warm tip: This article is reproduced from serverfault.com, please click

YAML anchors for PowerShell scripts

发布于 2020-12-01 23:56:48

I have YAML file for GitLab CI/CD Pipeline

.myanchor: &myanchor
  - 'echo "Some Test"'

My Job:
  script:
    - 'echo "Some Text"'
    - '*myanchor'

When I run pipeline, I get an error "myanchor : The term '*myanchor' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

I tried removing quotes in a string - '*myanchor' but then CLint says that YAML is incorrect.

What am I doing wrong?

Questioner
Roman Kopaev
Viewed
0
flyx 2020-12-02 22:12:30

'*myanchor' is a YAML scalar and will be loaded as string. If you want to refer to the node with the anchor &myanchor, you must not use quotes.

If you drop the quotes, the structure in My Job will be

My Job:
  script:
    - 'echo "Some Text"'
    - - 'echo "Some Text"'

It is likely that nested sequences are not supported for the content of script: (this is not a limitation of YAML per se, but a limitation of the tool that processes this structure).

To fix it, you need to put the anchor on the sequence item instead of the list:

.myanchor:
  - &myanchor 'echo "Some Test"'

My Job:
  script:
    - 'echo "Some Text"'
    - *myanchor

Now the problem is probably that you want to reference multiple items with *myanchor and put each of them as item directly into the script: sequence. That is simply not possible with YAML so you need to find another solution – perhaps preprocessing your YAML with a templating engine (lots of YAML's heavy users like e.g. Ansible and SaltStack do this).