lineinfile模块

常用参数说明

path: 指定修改的文件
regexp: 匹配要修改的行,以行为单位,匹配用正则表达式
line: 修改后的内容,是字符串
state: present表示插入和修改,absent表示删除匹配的行
insertbefore: 表示在匹配的行之前插入,匹配用正则表达式
insertafter: 表示在匹配的行之后插入,匹配用正则表达式
backup: 是否备份文件
create: 文件不存在则创建文件
validate: 验证文件修改的有效性,需要文件自带验证机制

例子:

追加行

  1. #追加行,默认在文件末尾
  2. - hosts: node1
  3. tasks:
  4. - name: edit index.html
  5. lineinfile:
  6. path: /var/www/html/index.html
  7. line: |
  8. "welcome to
  9. yutianedu"
  10. create: yes

修改指定的行

  1. #修改指定的行
  2. [admin@ansible ansible]$ cat lineinfile.yml
  3. - hosts: node1
  4. tasks:
  5. - name: disable selinux
  6. lineinfile:
  7. path: /etc/selinux/config
  8. regexp: "^SELINUX="
  9. line: "SELINUX=enforcing"
  10. state: present
  11. backup: yes


保存前验证文件

  1. - hosts: node1
  2. tasks:
  3. - name: Validate the sudoers file before saving
  4. lineinfile:
  5. path: /etc/sudoers.d/user1
  6. state: present
  7. create: yes
  8. line: 'user1 ALL=(ALL) NOPASSWD: ALL'
  9. validate: /usr/sbin/visudo -cf %s #验证文件的语法规则,需要命令支持



#参数backrefs说明:

当backrefs为no时,如果regex没有匹配到行,则添加一行,如果Regx匹配到行,则修改该行
当backrefs为yes时,如果regex没有匹配到行,则保持原文件不变,如果regex匹配到行,则修改该行
backrefs默认为no。

  1. - hosts: node1
  2. tasks:
  3. - name: Validate the sudoers file before saving
  4. lineinfile:
  5. path: /tmp/redhat
  6. state: present
  7. create: yes
  8. regexp: "^barl"
  9. line: "bar hello"
  10. backrefs: yes

blockinfile模块


blockinfile对多行操作,对文件进行多行操作,可以插入和追加内容到文件
blockinfile不能匹配具体的行,而是通过marker标识来进行区分

参数说明: block:要插入的文本内容
marker:指定块标记,”# {mark} ANSIBLE MANAGED BLOCK”

例子:

插入文本内容

  1. - hosts: node1
  2. tasks:
  3. - name: Insert/Update configuration using a local file and validate it
  4. blockinfile:
  5. block: "{{ lookup('file', './local/sshd_config') }}"
  6. dest: /tmp/sshd_config
  7. backup: yes
  8. validate: /usr/sbin/sshd -T -f %s

image.png

删除文本内容:

  1. - hosts: node1
  2. tasks:
  3. - name: remove"Match User" configuration block in /tmp/sshd_config
  4. blockinfile:
  5. path: /tmp/sshd_config
  6. state: absent
  7. marker: "#this is blockinfile content" #删除该标识符的内容

设置标记文本内容

image.png