ansible模块lineinfile

示列:

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 移除匹配行(所有匹配到的)

原文地址:https://www.cnblogs.com/metasequoia/p/5193250.html