如何为Ansible的service_facts模块声明服务名称变量
问题根因
你的vars段语法不符合Ansible规范,vars字段为键值对(字典)结构,不能使用列表项前缀-,这是导致变量未被正确识别、报VARIABLE NOT DEFINED的直接原因。
正确写法
1. Play级变量声明(和hosts、tasks平级,全局生效)
--- - name: Check service status hosts: all gather_facts: no vars: SERVICE: firewalld.service tasks: - name: Service Facts service_facts: - debug: var: ansible_facts.services[SERVICE]['status']
2. Task级变量声明(写在tasks段下对应任务中,仅对单个任务生效)
如果你需要将变量声明在tasks段下方,可以用task级变量的写法:
--- - name: Check service status hosts: all gather_facts: no tasks: - name: Service Facts service_facts: - name: Print service status vars: SERVICE: firewalld.service debug: var: ansible_facts.services[SERVICE]['status']
两种写法都可以正常解析SERVICE变量,获取到对应服务的状态值。
内容的提问来源于stack exchange,提问作者user3880406
相关产品推荐
相关产品推荐

