我想从以下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状态。我怎么能做到这一点?
致以最诚挚的问候,
罗曼
答案 0 :(得分:1)
这是一种不同的方法,基于在远程主机上收集事实,然后在本地主机上处理模板:
使用方法:
在主机中添加[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
最后,ping_test.j2
文件夹中的模板templates/
:
#################
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 %}
#################
运行playbook,你会在/tmp
示例执行,仅限最后一行:
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
中选择了一个随机的回答。您可以检查收集的事实,如果它更适合您的需要,可以选择另一个事实。这个想法是,对于ansible cant连接的主机,不会定义此变量。