Ansible模块[10]:lineinfile

应用

  • 此模块可以帮助我们对文件内容镜像操作。
    • 替换文件中的某一行内容。
    • 在文件中的某一行之前或之后插入内容。
    • 删除文件中的某一行。

参数

  • path:指明需要修改的文件。

  • regexp:在文件中匹配时使用的正则表达式。

  • line:要插入或替换到文件中的内容。

  • mode:设置生成的文件或目录的权限。

  • state

    • absent:删除模式,此模式下删除匹配到的行。
    • present:插入模式,此模式下插入匹配到的最后一行的下一行或上一行。
  • insertafter:与“state=present”一起使用。如果指定,该行将在指定正则表达式的最后一次匹配之后插入。如果需要第一个匹配,请使用“firstmatch=yes”。

  • insertbefore:与“state=present”一起使用。如果指定,该行将在指定正则表达式的最后一个匹配项之前插入。如果需要第一个匹配,请使用“firstmatch=yes”。

示例

  • 修改文件中以SELINUX开头的行,修改为SELINUX=disabled

    - name: Ensure SELinux is set to disabled mode
      lineinfile:
        path: /etc/selinux/config
        regexp: '^SELINUX='
        line: SELINUX=disabled
    
  • 删除文件中以%wheel开头的行。

    - name: Make sure group wheel is not in the sudoers configuration
      lineinfile:
        path: /etc/sudoers
        state: absent
        regexp: '^%wheel'
    
  • /etc/hosts文件中找到开头为127.0.0.1的行,替换为127.0.0.1 localhost,并修改文件/etc/hosts的属主为root、属组为root、文件权限为644

    - name: Replace a localhost entry with our own
      lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.0\.1'
        line: 127.0.0.1 localhost
        owner: root
        group: root
        mode: '0644'
    
  • /etc/httpd/conf/httpd.conf文件中匹配以Listen开头的行。如果匹配到了,则将此行替换为Listen 8080,如果没有匹配到,则将在文件中匹配以 ^#Listen开头的行,并在匹配到的行的后一行插入Listen 8080

     name: Ensure the default Apache port is 8080
      lineinfile:
        path: /etc/httpd/conf/httpd.conf
        regexp: '^Listen '
        insertafter: '^#Listen '
        line: Listen 8080
    
  • /etc/services文件中匹配以# port for http开头的行。如果匹配到了,则将此行替换为# port for http by default,如果没有匹配到,则将在文件中匹配以www.*80/tcp开头的行,并在匹配到的行的前一行插入# port for http by default

    - name: Ensure we have our own comment added to /etc/services
      lineinfile:
        path: /etc/services
        regexp: '^# port for http'
        insertbefore: '^www.*80/tcp'
        line: '# port for http by default'
    
  • /tmp/testfile文件中添加192.168.1.99 foo.lab.net foo如果文件不存在,就会创建文件,再将192.168.1.99 foo.lab.net foo添加到新建的文件中。

    - name: Add a line to a file if the file does not exist, without passing regexp
      lineinfile:
        path: /tmp/testfile
        line: 192.168.1.99 foo.lab.net foo
        create: yes
    
posted @ 2021-06-30 10:40  lizhi_box  阅读(189)  评论(0)    收藏  举报