首页 > 解决方案 > Ansible:从列表中获取除输入之外的其他数字

问题描述

我有一组三个数字:19、20 和 21,我需要得到其中一个,除了输入的那个。我的方法是使用 jinja-difference 过滤器,它工作正常,但我不知道如何在差异中用变量(在我的示例中为“hostnumber”)替换硬编码数字(在我的示例中为“19”) -文件管理器。

例子:

ansible-playbook get_other_host.yml -e "hostname=abcd0015"

---
- hosts: all
  gather_facts: false
  tasks:

    - name: Extract the hostnumber
      set_fact:
        hostnumber: "{{ (hostname[6:] | int) + 4 }}"

# Output is: 19
    - name: The hostnumber is
      debug:
        msg: "{{ hostnumber }}"

# Output is: 20 and 21
    - name: The other hosts are
      debug:
        msg: "{{ [19,20,21] | difference([19]) }}"

# Output is: 20 or 21
    - name: One other host is
      debug:
        msg: "{{ [19,20,21] | difference([19]) | random }}"

标签: ansiblejinja2

解决方案


Jinja2 可以访问所有变量,包括hostnumber之前设置的变量;它可能已经是int,但是| int在已经是的变量上使用int是无害的

- debug:
    msg: "{{ [19,20,21] | difference([hostnumber | int]) }}"

推荐阅读