之前写了一个安装、更新Zabbix-agentd的 ansible-playbook 文件。虽说有判断系统处理正常,发现对sudoers文件的处理用的是覆盖代替。此操作方式对之前有特殊更改的主机并不友好,故欲将其更换为添加。
一开始采取了简单粗暴的办法,用shell指令,echo添加进最后一行:
... - name: sudoers file. shell: echo "zabbix ALL=(ALL) NOPASSWD: /usr/local/zabbix/scripts/*.sh" >> /etc/sudoers ...
测试时发现报错:
ansible-playbook --list-host deploy_zabbix.yml -vvvv ... ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each: JSON: Expecting value: line 1 column 1 (char 0) Syntax Error while loading YAML. mapping values are not allowed in this context The error appears to be in '/data/ansible/roles/install/tasks/main.yml': line 41, column 41, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - name: sudoers file. shell: echo "zabbix ALL=(ALL) NOPASSWD: /usr/local/zabbix/scripts/*.sh" >> /etc/sudoers ^ here
经测试,冒号前加不加反斜杠都一样;有可能是程序把冒号解析为程序指令了。想起来当初就是此原因才更换为使用copy方法来替换文件。
在网上查找到了一番,发现使用lineinfile方法可处理此情况;且因为并不是单纯地添加行,故不会有重复添加的情况。
... - name: sudoers file. lineinfile: "dest=/etc/sudoers state=present regexp='^zabbix ALL' line='zabbix ALL=(ALL) NOPASSWD: /usr/local/zabbix/scripts/*.sh'" ...
lineinfile是Ansible是内建模块,具体说明可参见官方文档。
再次对此playbook执行命令即可成功:
ansible-playbook --list-tags deploy_zabbix.yml playbook: deploy_zabbix.yml play #1 (all): all TAGS: [] TASK TAGS: [mdfconf, upconf, upgrade]
这里使用lineinfile对文件进行操作,发现有regexp正则所匹配的行则进行修改;如没有,则在文件尾进行添加。