我正在尝试使用 Ansible 的
lineinfile
模块向 nginx 配置文件中现有的 log_format
指令添加新参数。然而,我在让模块按预期工作时遇到了困难。
这是我的 nginx 配置文件摘录:
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
我希望将其更改为:
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
这是我正在使用的 Ansible 任务:
- name: Add string between groups of regex in nginx.conf
ansible.builtin.lineinfile:
path: nginx.conf
backrefs: yes
regexp: '(log_format[^;]*?)(;)'
line: '\1 my_string \2'
尽管尝试了不同的
regex
模式和配置,文件保持不变,Ansible 只是返回 ok
而不进行任何更改。我已经使用 regex101 等在线工具验证了正则表达式,它似乎准确匹配文件的所需部分。
PS:我也尝试过其他正则表达式,但它们似乎都不起作用。例如:
(log_format\s*\S*;)
(log_format\s*\S*;)
在这种情况下,建议尽可能简化用例。你可以考虑
template
模块 – 将文件模板输出到目标主机是一个可行的选择吗?copy
模块 – 将文件复制到远程位置是一个可行的选择吗?log_format
模块将 blockinfile
作为块进行管理 – 插入/更新/删除由标记线包围的文本块等等...
例如,如果行顺序并不重要,则可以使用最小的剧本
---
- hosts: localhost
become: false
gather_facts: false
vars:
my_string: >-
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'
tasks:
- debug:
var: my_string
- lineinfile:
path: nginx.conf
firstmatch: true
insertbefore: "\"';"
line: "\t\t\t{{ my_string }}"
state: present
diff: true
将产生
的输出TASK [debug] ********************************************************************************************************************
ok: [localhost] =>
my_string: '''rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'''
TASK [lineinfile] ***************************************************************************************************************
--- before: nginx.conf (content)
+++ after: nginx.conf (content)
@@ -2,6 +2,7 @@
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
+ 'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
changed: [localhost]
和文件内容
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;