0

I tried to pass value manually to a specific variable by using command

ansible-playbook test.yml --extra-var variable1=ntpd

Can you please help me to know how to pass value to variable in list, to pick one by one using command?

I've tried as below did not work

ansible-playbook test.yml --extra-var "variable1=ntpd,crond,sysconf"

Tried as but no luck

ansible-playbook test.yml --extra-var "variable1=ntpd,crond,sysconf"
ansible-playbook test.yml  -e '{"variable1":["ntpd", "crond"]}'

The playbook should pick 1st value as ntpd and then second value as crond and so on.

U880D
  • 8,601
  • 6
  • 24
  • 40
Sandhya S
  • 9
  • 2
  • As an adhoc test => `-ansible localhost --extra-var '{"variable1":["ntpd","crond","sysconf"]}' -m debug -a var=variable1[0]` – Zeitounator Jan 25 '23 at 18:37

1 Answers1

0

You may have a look into the following minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Show provided content and type
    debug:
      msg:
       - "var1 contains {{ var1 }}"
       - "var1 is of tpye {{ var1 | type_debug  }}"

which will called with

ansible-playbook extra.yml --extra-vars="var1=a,b,c"

resulting into an output of

TASK [Show provided content and type] ******
ok: [localhost] =>
  msg:
  - var1 contains a,b,c
  - var1 is of tpye unicode

I understand that you like to get a list out of it for further processing. Since there is a string of comma separated values this is quite simple to achieve, just split the string on the separator.

  - name: Create list and loop over elements
    debug:
      msg: "{{ item }}"
    loop: "{{ var1 | split(',') }}"

will result into an output of

TASK [Create list and loop over elements] ******
ok: [localhost] => (item=a) =>
  msg: a
ok: [localhost] => (item=b) =>
  msg: b
ok: [localhost] => (item=c) =>
  msg: c

As the example show packages names, the use cause might be to install or validate packages and which are provided in a list of comma separated values (pkgcsv).

In example for the yum module – Manages packages with the yum package manager and because of the Notes

When used with a loop: each package will be processed individually, it is much more efficient to pass the list directly to the name option.

one should better proceed further with

- name: Install a list of packages with a list variable
  ansible.builtin.yum:
    name: "{{ pkgcsv | split(',') }}"

or, as the module has the capabilities to do so, one could also leave the CSV just as it is

- name: Install a list of packages with a list variable
  ansible.builtin.yum:
    name: "{{ pkgcsv }}"

Further Reading

As this could be helpful for other or in future cases.

U880D
  • 8,601
  • 6
  • 24
  • 40