代码之家  ›  专栏  ›  技术社区  ›  myol

Ansible lineinfile使用insertafter复制

  •  8
  • myol  · 技术社区  · 7 年前

    我正在尝试将一个条目添加到我的 /etc/hosts 使用ansibles文件 lineinfile . 我希望逻辑是,如果它找到了条目 127.0.0.1 mysite.local 127.0.1.1

    127.0.0.1   localhost
    127.0.1.1   mypc
    127.0.0.1      mysite.local
    

    我有插入后,部分工作,但它似乎是实际的正则表达式搜索无法找到现有的条目,所以我不断得到重复的插入 127.0.0.1 mysite.local

    文件确实说;

    修改行时,regexp通常应匹配行的初始状态以及被行替换后的状态,以确保幂等性。

    但我不确定这怎么适用于我的正则表达式。目前我的剧本是;

    - name: Add the site to hosts
      lineinfile:
        path: /etc/hosts
        # Escape special chars
        regex: "^{{ domain|regex_escape() }}"
        line: "127.0.0.1      {{ domain }}"
        insertafter: '127\.0\.1\.1'
        firstmatch: yes
      become: yes
    

    哪里 domain mysite.local

    我看过 this backrefs 自文件状态起;

    该标志稍微改变了模块的操作;insertbefore和insertafter将被忽略,如果regexp与文件中的任何地方都不匹配,则文件将保持不变。

    我试过了;

    regex: '127\.0\.0\.1\s+?{{ domain|regex_escape() }}'
    

    也没有运气

    3 回复  |  直到 7 年前
        1
  •  1
  •   Vladimir    7 年前

    看来 firstmatch: yes 他在破坏东西。以下任务对我有效(我用tab替换了空格,以获得奇特的外观,但空格也有效):

      - name: Add the site to hosts
        lineinfile:
          path: /etc/hosts
          # Escape special chars
          regexp: "{{ domain|regex_escape() }}"
          line: "127.0.0.1{{ '\t' }}{{ domain }}"
          insertafter: '127\.0\.1\.1'
    
        2
  •  1
  •   jaytea    7 年前

    根据 this link ,lineinfle扫描文件并一次应用一行正则表达式,这意味着您不能使用查看整个文件的正则表达式。我不熟悉lineinfle工具,但是如果您可以使用上面链接中使用的“replace”工具,那么您可以根据需要使用以下Python正则表达式进行匹配:

    \A((?:(?!127\.0\.0\.1\s)[\s\S])*?)(?:\Z|127\.0\.0\.1\s+(?!{{ domain|regex_escape() }})\S+\n|(127\.0\.1\.1\s+\S+(?![\s\S]*\n127\.0\.0\.1\s)\n))
    

    替换为“\1\2127.0.0.1{{domain}}\n”

    非捕获组处理三种不同的情况:

    1. Case 1 :127.0.1.1和127.0.0.1不存在,因此在末尾插入
    2. Case 2 :127.0.0.1与其他主机存在,因此请替换该条目
    3. Case 3 :127.0.1.1存在,因此在其后面插入

    第二种情况是通过避免匹配“127.0.0.1”(如果已经存在)的条目来处理幂等性。

        3
  •  0
  •   Vladimir Botka    7 年前

    这个 doc 说:

    插入者:。。。如果正则表达式同时传递给regexp和insertafter,则只有在找不到与regexp匹配的表达式时,才会使用insertafter。

    任务中的正则表达式扩展为

    regex: ^mysite\.local
    

    找不到此正则表达式,因为没有以“mysite.local”开头的行。因此 插入器 将被尊重,并在后面插入“行” 127.0.1.1