for each host need to print only one item

Viewed 78

I have a list of descriptions that will be added one per host. I would like to print one item per host and it is becoming harder than I expected. The same item is being printed per each host.

  tasks:
  - name: items in list
    debug:
      msg: "{{ item }}"
    with_items:
      - ['a', 'b']

THIS IS WHAT I GET:

TASK [items in list] *****************************************************************************************************************************************************************************************************************************
ok: [Host1] => (item=a) => {
    "msg": "a"
}
ok: [Host2] => (item=a) => {
    "msg": "a"
}
ok: [Host1] => (item=b) => {
    "msg": "b"
}
ok: [Host2] => (item=b) => {
    "msg": "b"
}

THIS IS WHAT I WANT:

TASK [items in list] *****************************************************************************************************************************************************************************************************************************
ok: [Host1] => (item=a) => {
    "msg": "a"
}
ok: [Host2] => (item=b) => {
    "msg": "b"
}
1 Answers

There are many options. For example,

  1. Create lists for the hosts
    - name: items in list
      debug:
        msg: "{{ item }}"
      loop: "{{ _list[inventory_hostname] }}"
      vars:
        _list:
          host1: ['a']
          host2: ['b']

gives

ok: [host1] => (item=['a']) => 
  msg: a
ok: [host2] => (item=['b']) => 
  msg: b
  1. Calculate the index of the host in the group, e.g.
    - name: items in list
      debug:
        msg: "{{ _list[_idx|int] }}"
      vars:
        _list: ['a', 'b']
        _idx: "{{ groups.all.index(inventory_hostname) }}"

gives

ok: [host2] => 
  msg: b
ok: [host1] => 
  msg: a
  1. Run the task once and iterate the sequence, e.g.
    - name: items in list
      debug:
        msg: "{{ _list[item|int] }}"
      with_sequence: start=0 end="{{ groups.all|length -1 }}"
      vars:
        _list: ['a', 'b']
      run_once: true
      delegate_to: localhost

gives

ok: [host1 -> localhost] => (item=0) => 
  msg: a
ok: [host1 -> localhost] => (item=1) => 
  msg: b
Related