使用insertafter进行Ansible lineinfile复制

myo*_*yol 8 regex jinja2 ansible

我正在尝试/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
Run Code Online (Sandbox Code Playgroud)

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

文档确实说;

修改一行时,正则表达式通常应匹配行的初始状态以及更换后的行状态,以确保幂等性.

但我不确定这对我的正则表达式有何影响.目前我的戏是;

- 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
Run Code Online (Sandbox Code Playgroud)

哪里domainmysite.local.

我看过这个答案,但我很确定backrefs自从文档说明以来我无法使用;

该标志稍微改变了模块的操作; insertbefore和insertafter将被忽略,如果正则表达式与文件中的任何位置不匹配,则文件将保持不变.

我试过了;

regex: '127\.0\.0\.1\s+?{{ domain|regex_escape() }}'
Run Code Online (Sandbox Code Playgroud)

也没有运气

小智 1

看来那firstmatch: yes是在破坏事情。它适合我执行以下任务(我用选项卡替换了空格以获得奇特的外观,但空格也可以工作):

  - 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'
Run Code Online (Sandbox Code Playgroud)