示列:
sshd_set.yaml
--- - hosts: test remote_user: root gather_facts: False tasks: - name: set hostname lineinfile: dest=/etc/sysconfig/network backrefs=yes regexp='^(HOSTNAME=).*' line='\1{{ inventory_hostname }}' notify: reboot handlers: - name: reboot shell: /sbin/reboot
iptables_add.yml
--- - hosts: test gather_facts: false tasks: - name: iptables test lineinfile: dest=/etc/sysconfig/iptables insertafter='^-A INPUT -i lo' line='-A INPUT -s 192.168.0.8 -m state --state NEW -m tcp -p tcp --dport 10050 -j ACCEPT' notify: reload iptables handlers: - name: reload iptables service: name=iptables state=reloaded
iptables_add.sh(iptables_add.yml的shell版)
#!/bin/bash line="\-A INPUT \-s 192.168.0.8 \-m state \-\-state NEW \-m tcp \-p tcp \-\-dport 10050 \-j ACCEPT" iptables_conf="/etc/sysconfig/iptables" grep -s "$line" $iptables_conf if [ $? != 0 ];then sed -i "/^-A INPUT -i lo/a $line" $iptables_conf /etc/init.d/iptables reload fi
說明:
ansible-doc lineinfile
替換 移除文件的單行 # 多行替換 移除參考replace模塊
Options: (= is mandatory)(= 后面的參數是強制要有的)
- backrefs(default=no)
與state=present一起使用
一、支持反向引用
二、稍微改變了模塊的操作方式
1、前插'insertbefore',后插'insertafter'失效
2、如果匹配到 替換最后一個匹配結果
3、如果未匹配到 不做任何改變
= dest
被編輯的文件
- insertafter
需要聲明 state=present
在匹配行后插入,如果未匹配到則默認為EOF。ps:如果line存在則不會再插入,不管regexp有沒有匹配到
- insertbefore
需要聲明 state=present
在匹配行前插入,如果未匹配到則默認為BOF。ps:如果line存在則不會再插入,不管regexp有沒有匹配到
- line
需要聲明 state=present
插入或替換的字符串
- regexp
使用正則匹配
- state(default=present)
present 如果匹配到就替換(最后一個匹配結果) #如果未設置backrefs=yes 未匹配到也會在最后插入line
absent 移除匹配行(所有匹配到的)