问题原文
原帖链接 · 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'
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
