1

I have a scenario where I need to print only 0th array and 1st array of 'N'of array in ansible.

Could someone help me to achieve this

Sample code:

Array;

ID = [1,2,3,4]

Ansible Code:

- hosts: localhost
  gather_facts: no
  tasks:
    - name: Print the first 2 values in the array
      debug:
        msg: "{{ item }}"
      with_items: "{{ ID }}"

Expected Output:

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

TASK [Print the first 2 values in the array] *******************************************************************************************************************************************************************
ok: [localhost] => (item=1) => {
    "msg": "1"
}
ok: [localhost] => (item=2) => {
    "msg": "2"
}

Actual Output:

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

TASK [Print the first 2 values in the array] *******************************************************************************************************************************************************************
ok: [localhost] => (item=1) => {
    "msg": "1"
}
ok: [localhost] => (item=2) => {
    "msg": "2"
}
ok: [localhost] => (item=3) => {
    "msg": "3"
}
ok: [localhost] => (item=4) => {
    "msg": "4"
}
Alfred
  • 73
  • 1
  • 7

2 Answers2

2

You could do this with Playbook Loops and with_sequence

- name: Show sequence
  debug:
    msg: "{{ item }}"
  with_sequence:
    - "0-1"

Thanks to

To get the value of an array you would use ID[item]. You may have a look into the following loop example and how it works.

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

  vars:

    ID: [A, B, C, D]

  tasks:

- name: Show entry
  debug:
    msg:
      - "{{ item }} {{ ID[item | int] }}"
  with_sequence:
    - "0-1"
U880D
  • 8,601
  • 6
  • 24
  • 40
  • can you help me in replacing the variable in with_sequence? because that's where i get stuck – Alfred Jan 24 '22 at 09:27
  • ``` - hosts: localhost gather_facts: no vars: ID: "['1','2','3','4']" tasks: - name: Print the first 2 values in the array debug: msg: "{{ ID[item] }}" with_sequence: - "1-2" ``` is this you're suggesting to do? – Alfred Jan 24 '22 at 09:31
  • @Alfred, I've updated the answer accordingly with an working example. – U880D Jan 24 '22 at 09:34
2

Use slice notation, e.g.

    - debug:
        var: item
      loop: "{{ ID[0:2] }}"

gives (abridged)

  item: 1
  item: 2

You can concatenate slices if you want to, e.g. to get the 1st, 2nd, and 4th item

    - debug:
        var: item
      loop: "{{ ID[0:2] + ID[3:4] }}"

gives (abridged)

  item: 1
  item: 2
  item: 4
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63