1

I have a fact, which is a list of lists, e.g. [ [disk1, filename1], [disk2, filename2], ... [diskN,filenameN] ]

I need to run a command in the format like command -x disk1,file=filename1 -x disk2,file=filename2 ... -x diskN,file=filenameN

I can't figure out how I can flatten the list and insert the option -x and file to create the string.

Any suggestion is appreciated. Thanks Billy

1 Answer 1

1

Given the list

  disk_file:
    - [disk1, filename1]
    - [disk2, filename2]
    - [diskN, filenameN]

join the items. For example,

  params: "-x {{ disk_file|map('join', ',file=')|join(' -x ') }}"

gives

  params: -x disk1,file=filename1 -x disk2,file=filename2 -x diskN,file=filenameN

Example of a complete playbook for testing

- hosts: localhost

  vars:

    disk_file:
      - [disk1, filename1]
      - [disk2, filename2]
      - [diskN, filenameN]

    params: "-x {{ disk_file|map('join', ',file=')|join(' -x ') }}"

  tasks:

    - debug:
        var: params
    - command: echo '{{ params }}'
      register: out
    - debug:
        var: out.stdout

gives

PLAY [localhost] *****************************************************************************

TASK [debug] *********************************************************************************
ok: [localhost] => 
  params: -x disk1,file=filename1 -x disk2,file=filename2 -x diskN,file=filenameN

TASK [command] *******************************************************************************
changed: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => 
  out.stdout: -x disk1,file=filename1 -x disk2,file=filename2 -x diskN,file=filenameN

PLAY RECAP ***********************************************************************************
localhost: ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
1
  • Actually it works fine after a quick test. Awesome.
    – Billy K
    Dec 20, 2022 at 2:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .