Alfred
Alfred

Reputation: 73

How to pass the specific array value to the variable in ansible

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"
}

Upvotes: 1

Views: 4176

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68179

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

Upvotes: 2

U880D
U880D

Reputation: 12127

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"

Upvotes: 2

Related Questions