Ansible ping 结果进入 Jinja2 模板

Ansible ping result into Jinja2 template

我想从以下 Ansible 脚本制作一个 Jinja2 模板。基本上,脚本会检查主机是否可达。

---
- name: check reachable hosts
  hosts: group1
  gather_facts: no
  tasks:
  - set_fact:
    ping_state: "failed"
  - debug: msg="play hosts {{ ansible_play_batch }}"
    run_once: true
  - ping:
    register: ping_result
    ignore_errors: yes
  - group_by: key=reachable
    when: ping_result|success
  - set_fact:
    ping_state: "OK"

- name: run command
  hosts: reachable
  become: yes
  gather_facts: yes
  tasks:
  - debug: msg="this is {{ ansible_hostname }}"

- name: print ping facts
  hosts: group1
  gather_facts: no
  tasks:
  - meta: clear_host_errors
  - debug:
    var: ping_state

在 Jinja2 模板中,我想要所有主机名及其 ping 状态。我怎样才能做到这一点?

此致,

罗曼

这是一种不同的方法,它基于在远程主机上收集事实,然后在本地主机上处理模板:

使用方法:

在您的主机中添加 [ping_test] 组,其中包含您要检查连接的所有主机。

然后是剧本:

---
- hosts: ping_test
  gather_facts: true
  tasks:

- hosts: localhost
  gather_facts: false
  vars:
    newline_character: "\n"
  tasks:
  - name: print all
    debug:
      var: hostvars['{{item}}']['ansible_all_ipv4_addresses']
    with_items: "{{ groups['ping_test'] }}"

  - name: process template
    template:
      src: templates/ping_test.j2
      dest: /tmp/ping_test.txt

最后,templates/ 文件夹中的模板 ping_test.j2

#################
REACHABLE units:
{% for host in groups['ping_test'] -%}
{% if hostvars[host]['ansible_all_ipv4_addresses'] is defined -%}
{{newline_character}}- {{ host }} is pingable
{%- endif %}
{%- endfor %}

#################
UNREACHABLE units:
{% for host in groups['ping_test'] -%}
{% if hostvars[host]['ansible_all_ipv4_addresses'] is not defined -%}
{{newline_character}}- {{ host }} is NOT pingable
{%- endif %}
{%- endfor %}

#################

运行 剧本,您在 /tmp

中找到一个 ping_test.txt 文件

示例执行,仅最后几行:

PLAY RECAP **********************************************************************************************************************************************************************************************************
greenhat                   : ok=1    changed=0    unreachable=0    failed=0   
localhost                  : ok=2    changed=0    unreachable=0    failed=0   
rhel-green                 : ok=1    changed=0    unreachable=0    failed=0   
rhel-red                   : ok=0    changed=0    unreachable=1    failed=0   

[root@optima-ansible ILIAS]# cat /tmp/ping_test.txt 
#################
REACHABLE units:

- rhel-green is pingable
- greenhat is pingable
#################
UNREACHABLE units:

- rhel-red is NOT pingable
#################
[root@optima-ansible ILIAS]# 

我从众多可用的事实中随机选择了一个 ansible_all_ipv4_addresses。您可以检查收集到的事实,如果它更适合您的需要,再选择一个。这个想法是,对于一个无法连接到的主机,这个变量将不会被定义。