lineinfile模块
常用参数说明
path: 指定修改的文件
regexp: 匹配要修改的行,以行为单位,匹配用正则表达式
line: 修改后的内容,是字符串
state: present表示插入和修改,absent表示删除匹配的行
insertbefore: 表示在匹配的行之前插入,匹配用正则表达式
insertafter: 表示在匹配的行之后插入,匹配用正则表达式
backup: 是否备份文件
create: 文件不存在则创建文件
validate: 验证文件修改的有效性,需要文件自带验证机制
例子:
追加行
#追加行,默认在文件末尾- hosts: node1tasks:- name: edit index.htmllineinfile:path: /var/www/html/index.htmlline: |"welcome toyutianedu"create: yes
修改指定的行
#修改指定的行[admin@ansible ansible]$ cat lineinfile.yml- hosts: node1tasks:- name: disable selinuxlineinfile:path: /etc/selinux/configregexp: "^SELINUX="line: "SELINUX=enforcing"state: presentbackup: yes
保存前验证文件
- hosts: node1tasks:- name: Validate the sudoers file before savinglineinfile:path: /etc/sudoers.d/user1state: presentcreate: yesline: 'user1 ALL=(ALL) NOPASSWD: ALL'validate: /usr/sbin/visudo -cf %s #验证文件的语法规则,需要命令支持
#参数backrefs说明:
当backrefs为no时,如果regex没有匹配到行,则添加一行,如果Regx匹配到行,则修改该行
当backrefs为yes时,如果regex没有匹配到行,则保持原文件不变,如果regex匹配到行,则修改该行
backrefs默认为no。
- hosts: node1tasks:- name: Validate the sudoers file before savinglineinfile:path: /tmp/redhatstate: presentcreate: yesregexp: "^barl"line: "bar hello"backrefs: yes
blockinfile模块
blockinfile对多行操作,对文件进行多行操作,可以插入和追加内容到文件
blockinfile不能匹配具体的行,而是通过marker标识来进行区分
参数说明:
block:要插入的文本内容
marker:指定块标记,”# {mark} ANSIBLE MANAGED BLOCK”
例子:
插入文本内容
- hosts: node1tasks:- name: Insert/Update configuration using a local file and validate itblockinfile:block: "{{ lookup('file', './local/sshd_config') }}"dest: /tmp/sshd_configbackup: yesvalidate: /usr/sbin/sshd -T -f %s
删除文本内容:
- hosts: node1tasks:- name: remove"Match User" configuration block in /tmp/sshd_configblockinfile:path: /tmp/sshd_configstate: absentmarker: "#this is blockinfile content" #删除该标识符的内容
设置标记文本内容

