我是ansible的新手,正在尝试在远程主机上安装rsyslog并将其配置为客户端,并将事件转发到rsyslog服务器,如下所述:
- 如果已安装rsyslog:
- 不要做任何更改
- 如果rsyslog正在运行
- 打印找到的转发地址。(目前,我将脚本"listIP.py"复制到远程主机,运行它,然后删除它。这一步正在按预期进行(
- 其他
- 将配置文件替换为我预定义的rsyslog.conf(此步骤也按预期工作(
- 其他
- 安装rsyslog(工作正常(
- 替换配置文件
- 重新启动服务
当远程主机没有安装rsyslog时,我会得到错误:"在计算条件(ansible_facts.services["rsyslog.service"].state!="running"(时:"dict object"没有属性"rsyslog.service;
我认为这可能是因为rsyslog.service.state是在一开始(安装之前(填充的,因此导致了故障。
另一种可能的选择是,在安装rsyslog之后,服务处于非活动状态(已终止(。
有什么建议可以解决吗?
请看下面的剧本-
---
- hosts: Linux_Servers
become: yes
gather_facts: True
debugger: "on_failed"
handlers:
- name: Replace rsyslog config file
copy:
src: /home/controller/Desktop/rsyslog.conf
dest: /etc/rsyslog.conf
force: yes
listen: "Replace config file"
- name: verify rsyslog running
service:
name: rsyslog
state: started
listen: "Replace config file"
tasks:
- name: Gathering services state...
service_facts:
- name: do facts module to get latest information
setup:
filter:
- 'rsyslog'
- name: If Rsyslog installed, print rsyslog current status. else - move to OS based installation.
debug:
var: ansible_facts.services["rsyslog.service"]
- name: OS check
debug: msg="{{ ansible_distribution }}"
register: distro
- name: The detected OS is CentOS. Installing rsyslog...
yum:
name: rsyslog
register: installedSuccess
when: ansible_facts['distribution'] == 'CentOS'
- name: The detected OS is Ubuntu. Installing rsyslog...
apt:
name: rsyslog
register: installedSuccess
when: ansible_facts['distribution'] == "Ubuntu"
- name: After success installation, replace config file.
copy:
src: /home/controller/Desktop/rsyslog.conf
dest: /etc/rsyslog.conf
force: yes
when: installedSuccess
# update service data?
- name: Rsyslog is installed but not running. restarts service now...
service:
name: rsyslog
state: started
when: ansible_facts.services["rsyslog.service"].state != "running"
- name: Rsyslog is installed and running. Copying script to find forwrding address...
copy: src=/home/controller/Desktop/listIP.py dest=listIP.py
when: ansible_facts.services["rsyslog.service"].state == "running"
- name: search rsyslog_conf for rsyslog server IP addresses
command: python listIP.py
register: IPaddress
when: ansible_facts.services["rsyslog.service"].state == "running"
- name: Found forwarding address-
debug: msg="{{ IPaddress.stdout }}"
- name: Clean Script From Remote Host
file:
state: absent
path: "listIP.py"
when: IPaddress
- name: No forwarding address found. Replace conf file...
copy:
src: /home/controller/Desktop/rsyslog.conf
我知道这个回复晚了8个月,但我想我会把我的解决方案放在这里,以防其他人遇到这个问题。
这里的主要问题是,Ansible只在播放开始时收集事实,而不会在播放中途更新事实变量,因此,当您在安装后通过检查事实来检查服务的状态时,您是在检查初始状态。
有几种方法可以解决这个问题,但最简单、最直接的方法是再次调用Ansible设置模块(Ansible.builtin.setup(,过滤您想要的事实。类似的东西看起来是这样的:
- name: SELinux - Force ansible to regather facts
setup: filter='rsyslog'
我还没有对此进行确切的测试,但原理是合理的;调用上面的setup会重新调用setup模块,该模块在开始时收集事实我不认为这会更新ansible_facts变量,因为您很可能需要通过set_fact模块重新分配变量,或者使用不同的选项调用setup模块。