[英]ansible lineinfile regex multiline
我正在嘗試使用 Ansible 編輯 apache.conf。 這是我的 conf 的一部分:
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
#<Directory /srv/>
# Options Indexes FollowSymLinks
AllowOverride All
# Require all granted
#</Directory>
我想改變這個塊
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
進入
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
將 AllowOverride 從無設置為全部。 我正在使用這個 ansible 任務
- name: change htaccess support
lineinfile:
dest: /etc/apache2/apache2.conf
regexp: '\s<Directory /var/www/>\n\sOptions Indexes FollowSymLinks\n\sAllowOverride'
line: "AllowOverride All"
tags:
- test
但是, AllowOverride All 總是添加到文件末尾。 完成這項工作的正確正則表達式模式是什么。 我不使用 ansible 模板,因為我只更改一行。
我通過稍微改進@mattyoung-redhatmatt 的回答來做到這一點。 事實證明, replace
模塊可以很好地處理多行正則表達式和反向引用:
- name: AllowOverride all
replace:
dest=/etc/apache2/apache2.conf
regexp='(<[dD]irectory /var/www/>[^<]*)AllowOverride None'
replace='\1AllowOverride All'
backup=yes
sudo: yes
notify:
- restart apache
我嘗試過並嘗試為此使用 blockinfile ,但我不想使用完整的模板。 我最終使用了 ansible 的替換模塊並在 regex.com 上練習了一些正則表達式:
- hosts: all
tasks:
- name: Update apache2.conf
replace: dest=/etc/apache2/apache2.conf
regexp='<Directory /var/www/>\n\tOptions Indexes FollowSymLinks\n\tAllowOverride None'
replace='<Directory /var/www/>\n\tOptions Indexes FollowSymLinks\n\tAllowOverride All'
backup=yes
notify:
- restart apache2
handlers:
- name: restart apache2
service: name=apache2 state=restarted
Ansible 的lineinfile模塊正是這樣做的,它處理文件中的單行並且不支持多行。
這讓您有幾個選擇來解決這個問題。
與 lineinfile 中最棘手的事情一樣,您最好用模板代替它。
或者,您可以嘗試使用blockinfile角色首先刪除( state=absent
)以下塊:
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
在<Directory /var/www/>
之后插入( state=present
)以下塊:
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
在<Directory /var/www/>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.