如何将特定数组值传递给ansible中的变量

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

我有一个场景,我只需要在 ansible 中打印“N”数组的第 0 个数组和第一个数组。

有人可以帮我实现这个吗

示例代码:

数组;

ID = [1,2,3,4]

Ansible 代码:

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

预期输出:

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

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

实际输出:

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

你可以用 Playbook Loops and with_sequence

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

感谢

要获取数组的值,您可以使用 ID[item]。您可以查看以下循环示例和 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"

使用slice notation,例如

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

给出(删节)

  item: 1
  item: 2

如果需要,您可以连接切片,例如获取第 1、2、4 项

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

给出(删节)

  item: 1
  item: 2
  item: 4