大网数据广告活动
服务器运维问答

Validate nginx.conf during ansible deploy

· 52CE 我爱测

I have a single Ansible-provisioned server running a number of sites. My Ansible tasks look roughly like: - name: site nginx config template: src="nginx-site.conf.j2" dest=/etc/nginx/conf.d/{{item.name}}.conf owner=root group=roo…

问题原文

原帖链接 · Erin Call · CC BY-SA 3.0

I have a single Ansible-provisioned server running a number of sites.

My Ansible tasks look roughly like:

- name: site nginx config
  template: src="nginx-site.conf.j2" dest=/etc/nginx/conf.d/{{item.name}}.conf
            owner=root group=root mode=0444
  with_items: sites
  notify: restart nginx

- name: nginx conf
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf 
            owner=root group=root mode=0444
  notify: restart nginx

I'd like to use the validate parameter to Ansible's template module to call nginx -t and make sure my new configs are syntactically valid. It works for the main nginx.conf:

  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf 
            owner=root group=root mode=0444
            validate="/usr/sbin/nginx -c %s -t"

But it doesn't seem to pick up changes to the site-specific config files. Putting validate on the site-specific templates doesn't work, as they need to be wrapped in an http directive to be valid.

What can I do to check the validity of these site-specific files?

社区高分解答

原帖链接 · Hubbitus · CC BY-SA 4.0

You may do there some trick and validate placed file like (idea borrowed from https://gist.github.com/psd/5042334):

    validate: bash -c 'nginx -t -c /dev/stdin <<< "events {worker_connections 1;} http { include %s; }"'

Update 2022-12-14

In fresh versions of bash such construction will not work! Please refer to nginx bug-report 2381 (2425) because of changed implementation - pipe used for the here-documents instead of temporary files.

So, you may use slightly less readable construction like:

validate: bash -c 'echo "events { worker_connections 2; } http { include %s; }" > /tmp/nginx.conf; sudo nginx -T -c /tmp/nginx.conf && rm -f /tmp/nginx.conf'

Update 2024-04-15

Previous solution do not remove /tmp/nginx.conf in case of error. That may be useful if you want debug result. But in case you want to be sure it is cleared you may do (thanks to @Sergey for the edit suggestion):

validate: bash -c 'echo "events { worker_connections 2; } http { include %s; }" > /tmp/nginx.conf; sudo nginx -T -c /tmp/nginx.conf; ec=$?; rm -f /tmp/nginx.conf; exit $ec'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-03-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。