我正在写一本ansible-playbook,将nginx.conf与include分开。我认为将nginx.conf与这样的选项一起使用会更舒适,因为我可以在剧本vars中包含或排除一些配置块。
目前,我遇到了部分问题:name: 2. Copy nginx.conf config.
playbook.yml:
- name: "setup_nginx"
hosts: "TEST_HOST"
gather_facts: yes
remote_user: root
vars:
nginx_worker_processes: "{{ ansible_processor_cores }}"
nginx_worker_connections: "32768"
nginx_worker_rlimit_nofile: "{{ (ansible_processor_cores*{{ nginx_worker_connections }}*2)|int|abs }}"
nginx_directories:
- directory: inc
nginx_files:
- file: "gzip.inc"
- file: "logs.inc"
- file: "mime.types"
- file: "tuning.inc"
- file: "proxy.inc"
- file: "ssl.inc"
- directory: sites
nginx_files:
- file: "mysite1"
- file: "mysite2"
- tasks:
- name: 1. Create nginx directories
file:
path: "/etc/nginx/{{ item.directory }}"
state: directory
owner: nginx
group: nginx
with_items:
- "{{ nginx_directories }}"
- name: 2. Copy nginx.conf config.
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
mode: 0640
owner: nginx
group: nginx
backup: yes
with_subelements:
- "{{ nginx_directories }}"
- nginx_files
nginx.conf.j2:
user nginx;
worker_processes {{ ansible_processor_cores }};
events {
worker_connections 32768;
use epoll;
multi_accept on;
}
worker_rlimit_nofile {{ (ansible_processor_cores*32768*2)|int|abs }};
http {
{% for val in nginx_directories %}
include /etc/nginx/{{ item.0.directory }}/{{ item.1.file }};
{% endfor %}
}
我希望得到结果:
user nginx;
worker_processes 1;
events {
worker_connections 32768;
use epoll;
multi_accept on;
}
worker_rlimit_nofile 65536;
http {
include /etc/nginx/inc/gzip.inc;
include /etc/nginx/inc/logs.inc;
include /etc/nginx/inc/mime.types;
include /etc/nginx/inc/tuning.inc;
include /etc/nginx/inc/proxy.inc;
include /etc/nginx/inc/ssl.inc;
include /etc/nginx/sites/mysite1;
include /etc/nginx/sites/mysite2;
}
但实际结果:
user nginx;
worker_processes 1;
events {
worker_connections 32768;
use epoll;
multi_accept on;
}
worker_rlimit_nofile 65536;
http {
include /etc/nginx/sites/mysite2.j2;
include /etc/nginx/sites/mysite2.j2;
}
我认为麻烦是我没有在模板nginx.conf.j2上正确定义子元素。
致谢
答案 0 :(得分:2)
删除模板任务中的循环以及模板使用中的循环
{% for val in nginx_directories | subelements('nginx_files') %}
include /etc/nginx/{{ val.0.directory }}/{{ val.1.file }};
{% endfor %}
FWIW。 config_encoder_filters有一个优雅的解决方案,可以对YAML数据进行编码
my_nginx_vhost_config:
- server:
- listen 8080
- server_name www.example.com
- "location /":
- root /usr/local/www/nginx-dist/
- index index.html
带有简单模板
# {{ ansible_managed }}
{{ my_nginx_vhost_config | encode_nginx }}
到nginx配置
# cat /usr/local/etc/nginx/conf.d/default.conf
# Ansible managed
server {
listen 8080;
server_name www.example.com;
location / {
root /usr/local/www/nginx-dist/;
index index.html;
}
}
详细信息在nginx role中。