簡體   English   中英

Ansible lineinfile無法識別正則表達式

[英]Ansible lineinfile doesn't recognize regular expression

要編輯的文件

#CentOS-Base.repo
#
[base]
name=CentOS-$releasever - Base

[updates]
name=CentOS-$releasever - Updates

[contrib]
name=CentOS-$releasever - Contrib

艱巨的任務

- name: PostgreSQL | Yum | exclude old version
  remote_user: root
  sudo: no
  lineinfile: dest=/etc/yum.repos.d/CentOS-Base.repo
              line='exclude=postgresql*'
              insertafter={{ item }}
  with_items:
    - ^\[base\]
    - ^\[updates\]

結果:

該行僅添加到文件一次,並且在EOF處添加,而不是在[base]和[updates]之后的下一行添加。

我相當確定正則表達式有效(已在https://pythex.org/上選中)。

代替使用lineinfile模塊,請考慮使用ini_file模塊 這樣,您就不會因正則表達式表達式而感到頭疼。

管理(添加,刪除,更改)INI樣式文件中的各個設置,而不必使用例如模板或匯編文件來整體管理文件。 如果缺少的部分不存在,則添加它們。

例:

# Ensure "fav=lemonade is in section "[drinks]" in specified file
- ini_file: dest=/etc/conf section=drinks option=fav value=lemonade mode=0600 backup=yes

- ini_file: dest=/etc/anotherconf
            section=drinks
            option=temperature
            value=cold
            backup=yes

在同一文件中多次使用lineinfile是Ansible中的代碼味道 而是使用copytemplate

但是,這是一種實現方法。 請注意,它的行數多於文件+復制命令的行數。

- name: PostgreSQL | Yum | exclude old version
  lineinfile: dest=test.repo
              line="\1\nexclude=postgresql*"
              insertafter="\[{{ item }}\]"
              regexp="(\[{{ item }}\])"
              backrefs=true
  with_items:
    - base
    - updates

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM