首页 > 解决方案 > Ansible 角色断言在基于清单组中的主机计数构建的 var 上失败

问题描述

团队,使用角色不直接剧本。我正在尝试计算某些组下库存中的主机数量,然后断言该值。但在输出中得到未定义的值响应。另外,有没有更好的方法来做到这一点?

      - name: "Ensure KUBECONFIG"
        shell: echo $KUBECONFIG
        register: kubeconfig_exists
        failed_when: kubeconfig_exists.rc != 0
      - debug:
          var: kubeconfig_exists.stdout_lines

      - name: "Find $PATH where Ansible looks for binaries on target system"
        register: echo_path
        shell: echo $PATH
      - debug:
          var: echo_path.stdout_lines

      - debug:
        vars:
            gpu_count: "{{ groups['k8s_gpu_nodes'] | length }}"
            cpu_count: "{{ groups['k8s_cpu_nodes'] | length }}"
      - assert:
               that:
                  - "gpu_count | int <= 1"
                  - "cpu_count | int >= 1"
               msg: "Assure k8s_nodes are not empty"

输出:

TASK [3_validations_on_ssh : Ensure KUBECONFIG] ************
changed: [localhost]

TASK [3_validations_on_ssh : debug] ******************
ok: [localhost] => {
    "msg": "Hello world!"
}

TASK [3_validations_on_ssh : assert] ****************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'gpu_count | int <= 1' failed. The error was: error while evaluating conditional (gpu_count | int <= 1): 'gpu_count' is undefined"}

库存.txt

target1 ansible_host='{{ target1_hostip }}' ansible_ssh_pass='{{ target1_pass }}'
[k8s_gpu_nodes]
host1
host2
[k8s_cpu_nodes]
host3
host4

标签: ansibleansible-2.xansible-inventoryansible-facts

解决方案


这是一个修正了单个所需任务的剧本:

---
- name: Check nodes in groups
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Check everything is ok
      vars:
        gpu_count: "{{ groups['k8s_gpu_nodes'] | length }}"
        cpu_count: "{{ groups['k8s_cpu_nodes'] | length }}"
      assert:
        that:
          - gpu_count | int > 0
          - cpu_count | int > 0
        msg: "Assure k8s_nodes are not empty"

当我使用您的上述库存播放此剧本时,结果如下:

$ ansible-playbook -i inventories/hosts.ini playbook.yml

PLAY [Check nodes in groups] ****************************************************************************************************************************************************************************

TASK [Check everything is ok] ***************************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "msg": "All assertions passed"
}

PLAY RECAP **********************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

推荐阅读