在我的ansible编码中,我想知道服务的状态,如service httpd status
(服务是否为runngin),结果将存储在变量中。使用该状态,我将在ansible中使用其他一些代码。
我使用的是ansible服务模块,没有状态选项。如果我使用shell模块,我收到了这个警告
[WARNING]: Consider using service module rather than running service
所以其他任何模块都可以获得服务状态吗?
答案 0 :(得分:3)
不,没有标准模块来获取服务的状态。
但如果您知道自己在做什么,可以取消对特定command
任务的警告:
- command: service httpd status
args:
warn: false
我刚刚发布了关于此技巧的快速note。
答案 1 :(得分:0)
希望service: allow user to query service status #3316很快就会合并到核心模块中。
您可以使用此diff to system/service.py
手动修补这是我使用ansible 2.2.0.0的差异。我在我的mac / homebrew安装上运行它,它适用于我。
这是我编辑过的文件:/usr/local/Cellar/ansible/2.2.0.0_2/libexec/lib/python2.7/site-packages/ansible/modules/core/system/service.py
@@ -36,11 +36,12 @@
- Name of the service.
state:
required: false
- choices: [ started, stopped, restarted, reloaded ]
+ choices: [ started, stopped, status, restarted, reloaded ]
description:
- C(started)/C(stopped) are idempotent actions that will not run
- commands unless necessary. C(restarted) will always bounce the
- service. C(reloaded) will always reload. B(At least one of state
+ commands unless necessary. C(status) would report the status of
+ the service C(restarted) will always bounce the service.
+ C(reloaded) will always reload. B(At least one of state
and enabled are required.)
sleep:
required: false
@@ -1455,7 +1456,7 @@
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True),
- state = dict(choices=['running', 'started', 'stopped', 'restarted', 'reloaded']),
+ state = dict(choices=['running', 'started', 'stopped', 'status', 'restarted', 'reloaded']),
sleep = dict(required=False, type='int', default=None),
pattern = dict(required=False, default=None),
enabled = dict(type='bool'),
@@ -1501,6 +1502,9 @@
else:
service.get_service_status()
+ if module.params['state'] == 'status':
+ module.exit_json(state=service.running)
+
# Calculate if request will change service state
service.check_service_changed()
答案 2 :(得分:0)
您可以使用service_facts模块。
例如,说我想查看Apache的状态。
- name: Check for apache status
service_facts:
- debug:
var: ansible_facts.services.apache2.state
输出为:
ok: [192.168.blah.blah] => {
"ansible_facts.services.apache2.state": "running"
}
如果您想查看所有这些内容,可以通过在数组中上移两个级别来实现:
var: ansible_facts.services
输出将列出所有服务,并且看起来像这样(为简洁起见被截断):
"apache2": {
"name": "apache2",
"source": "sysv",
"state": "running"
},
"apache2.service": {
"name": "apache2.service",
"source": "systemd",
"state": "running"
},
"apparmor": {
"name": "apparmor",
"source": "sysv",
"state": "running"
},
etc,
etc
我正在使用Ansible 2.7。以下是该模块的文档:Click here
答案 3 :(得分:0)
这是一个启动服务然后使用服务事实检查状态的示例,在我的示例中,您必须注册变量,然后使用debug var将其输出,并在json链中指向正确的格式,从而得到输出:
## perform start service for alertmanager
- name: Start service alertmanager if not started
become: yes
service:
name: alertmanager
state: started
## check to see the state of the alertmanager service status
- name: Check status of alertmanager service
service_facts:
register: service_state
- debug:
var: service_state.ansible_facts.services["alertmanager.service"].state