Ansible 如何将布尔类型 true 和 false 转换为对应的字符串

问题描述 投票:0回答:1

这是我的剧本,我没有直接使用布尔类型来兼容以前从库存中获取的版本,我查看了剧本,它是

when: cluster_allinone == "true"
,我可能在执行脚本时忘记更改它,所以我想覆盖
cluster_allinone
的值而不修改之前的 playbook。

- name: check node counnt
  hosts: all:!gaop-vip-addresses
  tasks:
    - name: Get the number of nodes in group2
      set_fact:
        worker_count: "{{ groups['k8s-worker'] | length }}"

    - debug:
        var: worker_count

    - name: set cluster_allinone var
      set_fact:
        cluster_allinone: 'true'
      when: (worker_count | int) == 0

    - name: set cluster_allinone var
      set_fact:
        cluster_allinone: 'false'
      when: (worker_count | int) > 0

    - debug:
        var: cluster_allinone

    - debug:
        msg: single
      when: cluster_allinone == "true"

    - debug:
        msg: mutil
      when: cluster_allinone  == "false"

但是

cluster_allinone
似乎是布尔类型,我尝试过
to_json
ternary('true', 'false')

    - name: set cluster_allinone var
      set_fact:
        temp: 'true'
      when: (worker_count | int) == 0

    - name: set cluster_allinone var
      set_fact:
        temp: 'false'
      when: (worker_count | int) > 0


--- try but fail


    - name: set cluster_allinone var
      set_fact:
        cluster_allinone: "{{temp | to_json}}"

    - name: set cluster_allinone var
      set_fact:
        cluster_allinone: "{{(worker_count | int) == 0}}"

    - name: set cluster_allinone var
      set_fact:
        cluster_allinone: "{{temp | ternary('true', 'false')}}"
ansible --version
ansible 2.4.5.0
  config file = /data/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /data/ansible/lib/ansible
  executable location = /data/ansible/bin/ansible
  python version = 2.7.12 (default, Nov 19 2018, 06:48:02) [GCC 5.4.0 20160609]

在这个问题上花了太多时间,非常感谢任何帮助!

ansible ansible-inventory ansible-facts
1个回答
0
投票

为了确保与现有 playbook 的兼容性并正确处理作为字符串(“true”或“false”)的“cluster_allinone”变量,您可以使用“set_fact”显式设置“cluster_allinone”变量来调整 playbook作为基于worker_count的字符串。 您可以修复以下问题:

  • 名称:检查节点数 主机:全部:!gaop-vip-地址 任务:
    • name:获取group2中的节点数 设置事实: worker_count: "{{ groups['k8s-worker'] | length }}"

    • 调试: 变量:worker_count

    • name:如果worker_count为0,则将cluster_allinone var设置为true 设置事实: cluster_allinone: '真' 当:(worker_count | int)== 0

    • name:如果worker_count大于0,则将cluster_allinone var设置为false 设置事实: cluster_allinone: '假' 当:(worker_count | int)> 0

    • 调试: var: cluster_allinone

    • 调试: 味精:单个 当: cluster_allinone == “true”

    • 调试: 味精:多个 当: cluster_allinone == “假” 祝你好运!!!

© www.soinside.com 2019 - 2024. All rights reserved.