【问题标题】:How to pass the specific array value to the variable in ansible如何将特定数组值传递给ansible中的变量
【发布时间】:2022-01-24 08:31:52
【问题描述】:

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

谁能帮我实现这个目标

示例代码:

数组;

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

【问题讨论】:

    标签: arrays arraylist ansible


    【解决方案1】:

    您可以使用 Playbook Loopswith_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"
    

    【讨论】:

    • 你能帮我替换with_sequence中的变量吗?因为那是我卡住的地方
    • ``` - 主机:本地主机收集事实:无变量:ID:“['1','2','3','4']”任务:-名称:打印前 2数组调试中的值: msg: "{{ ID[item] }}" with_sequence: - "1-2" ``` 你建议这样做吗?
    • @Alfred,我已经用一个工作示例相应地更新了答案。
    【解决方案2】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2023-02-13
      • 2019-08-18
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多