第 9 章 模板(jinja2)
第 9 章 模板(jinja2)
该部分分成两块:
1.条件和循环 #通过jinjia渲染出相关配置文件
2.案例:管理Nginx配置文件
1.条件和循环
条件使用跟bash shell 的if语法差不多,也就多了个{% %} 包裹,需要输出部分不使用{% %}包裹就可以了
循环也是使用跟bash shell 的for语法差不多,也就多了个{% %} 包裹,需要输出部分不使用{% %}包裹就可以了
模块template使用跟copy模块差不多,指定模块文件和输出位置即可,模板文件会自动生成你所需要配置文件在输出到你指定的位置。
示例如下,playbook脚本:
#jinja2.yml --- - hosts: web gather_facts: no remote_user: root vars: hello: ansible tasks: - template: src=f1.j2 dest=/tmp/f1.j2
模板文件:
#f1.j2
{% set list=['one','two','three'] %} #遍历数组
{% for i in list %}
{% if i == 'two' %} #根据if条件输出
-> 2
{% elif i == 'three' %}
-> 3
{% endif %}
{{hello}} #显示playbook脚本传参数值
{% endfor %}
{% set dict={'zhangshan':26,'lisi':25 } %} #遍历字典
{% for key,value in dict.iteritems() %}
{{key}} -> {{value}}
{% endfor %}
2.案例:管理Nginx配置文件
完整案例playbook文件:
# cat nginx1.yml
---
- hosts: web
gather_facts: no
remote_user: root
vars:
hello: ansible
http_port: 80
server_name: test.ctnrs.com
tasks:
- name: Add repo
yum_repository:
name: nginx
description: nginx repo
baseurl: http://nginx.org/packages/centos/7/$basearch/
gpgcheck: no
enabled: 1
tags: addrepo
- name: Install nginx
yum:
name: nginx
state: latest
tags: install
- name: copy nginx config file
template: src=site1.j2 dest=/etc/nginx/conf.d/site1.conf
notify: restarted nginx
tags: copyconfig
- name: Create wwwroot directory
file:
dest: /var/www/html
state: directory
- name: Create test page index.html
#debug: msg="123 {{ansible_hostname}}"
shell: echo "hello {{hello}}" > /var/www/html/index.html
tags: test
- name: firewall 80
service: name=firewalld state=stopped
handlers:
- name: restarted nginx
service: name=nginx state=restarted
模板文件:
# cat site1.j2
server {
listen {{http_port}};
server_name {{server_name}};
location / {
root /var/www/html;
index index.html;
}
}
管理机测试文件:
curl 192.168.3.74 -H "Host:test.ctnrs.com"
文章目录
关闭
