如果我们使用这个模块“service_facts”,我们将在manual中获得所有运行服务的结果。 输出结果以JSON格式输出,如下所示(这是结果的一部分)
{
"ansible_facts.services": {
"rsyslog": {
"name": "rsyslog",
"source": "sysv",
"state": "running"
},
"rsyslog.service": {
"name": "rsyslog.service",
"source": "systemd",
"state": "running"
},
"sendsigs.service": {
"name": "sendsigs.service",
"source": "systemd",
"state": "stopped"
}
}
}
我在Ansible的新手。
如何在Ansible中正确过滤输出?
答案 0 :(得分:1)
我同意,这个模块创建了一个元素的关联数组[] => array(),这使得它很难在ansible中处理,如果它注入的[services]元素是一个列表会更好。
无论如何,这是一个剧本,它将为你分配运行列表变量的服务和一个未运行的列表变量(状态!=“正在运行”)
---
- hosts: localhost
gather_facts: no
vars:
newline_character: "\n"
services_running: []
services_NOT_running: []
tasks:
- name: populate service facts
service_facts:
- name: populate running services
set_fact:
services_running: "{{ services_running + [item] }}"
when: hostvars[inventory_hostname]['services']['{{item}}']['state'] == "running"
with_items: "{{ hostvars[inventory_hostname]['services'].keys() }}"
- name: populate NOT running services
set_fact:
services_NOT_running: "{{ services_NOT_running + [item] }}"
when: hostvars[inventory_hostname]['services']['{{item}}']['state'] != "running"
with_items: "{{ hostvars[inventory_hostname]['services'].keys() }}"
- debug:
msg: "running services: {{ services_running }}"
- debug:
msg: "NOT running services: {{ services_NOT_running }}"
答案 1 :(得分:0)
也许您也有兴趣过滤掉已停止/正在运行的服务并将其分配给此帖子中的单独变量: