1

In Ansible, I have an array like this:

tab:
  - 'val1'
  - 'val2'

And I want to execute a remote script like this:

- name: launch Script
  script: "scripts/script.ps1 -tab {{ tab }}"

But the json format is not well recognized ([uval1 uval2]). I have to convert it to a PowerShell format:

$new_tab =  $tab -replace '"','' -replace ']','' -replace '\[','' -split ","

Is there a better solution?

2 Answers 2

2

I suggest you use join()

scripts/script.ps1 -tab {{ tab | join(',') }}

and then it will create a string like this: val1,val2

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

2 Comments

What about escaping?
i suggest you raise a new question, instead of asking a question in the comments
1

To complement 4c74356b41's useful answer:

If you have to preserve the quotes of your list elements, you can use the following logic:

- name: launch Script
  script: "scripts/script.ps1 -tab {{ '\"' + tab | join('\",\"') + '\"' }}"

This will add double quotes to each element and PowerShell will be able to evaluate each string (e. g. expanding variables etc. (read more)). If you want to wrap your elements in single quotes instead, you can do it like this:

- name: launch Script
  script: "scripts/script.ps1 -tab {{ "'" + tab | join("','") + "'" }}"

Be aware that the quote filter is not useful in this case, as it is designed for shell usage and will not quote every string.

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.