ansible template

ansible template

template介绍

Jinja是基于Python的模板引擎。template类是Jinja的另一个重要组件,可以看作一个编译过的模块文件,用来生产目标文本,传递Python的变量给模板去替换模板中的标记。

他与ansible的copy模块功能相似,都是拷贝文件到目标机器,唯一区别是

  • copy:不支持变量
  • template:支持变量,可以把配置文件根据变量渲染后再发送到目标机器

实例

实例1

cat temnginx.yaml 
---
- hosts: test
  remote_user: root
  vars: 
​    nginx_vhosts:
​      - listen: 80
  tasks:
​    - name: config file 
​      template: src=./template/nginx.conf.j2 dest=/data/nginx.conf
 cat template/nginx.conf.j2 
{% for vhost in nginx_vhosts %}
server {
  listen {{ vhost.listen }}
}
{% endfor %}
生成的结果
cat nginx.conf 
server {
  listen 80
}

实例2

cat temnginx2.yaml 
---
- hosts: test
  remote_user: root
  vars:
​    nginx_vhosts:
​      - 81
​      - 82 
​      - 83
  tasks:
​    - name: template config
​      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

cat nginx.conf.j2 
{% for vhost in nginx_vhosts %}
server {
  listen {{ vhost.listen }}
}
{% endfor %}
生成的结果
server {
  listen 81
}
server {
  listen 82
}
server {
  listen 83
}

实例3

cat temnginx3.yaml 
---
- hosts: test
  remote_user: root
  vars:
​    nginx_vhosts:  
​      - listen: 8080
​        server_name: "web1.baidu.com"
​        root: /var/www/nginx/web1/
​      - listen: 8081
​        server_name: "web1.baidu.com"
​        root: "/var/www/nginx/web2/"
  tasks:
​    - name: template config
​      template: src=./template/nginx.conf2.j2 dest=/data/nginx2.conf

cat nginx.conf2.j2
{% for vhost in nginx_vhosts %}
server{
  listen {{ vhost.listen }}
  server_name {{ vhost.server_name }}
  root {{ vhost.root }}
}
{% endfor %}

实例4

在模板文件中还可以使用if条件判断,决定是否生成相关的配置信息

cat templnginx4.yaml 
- hosts: test
  remote_user: root
  vars:
​    nginx_vhosts:
​      - web1:
​        listen: 8080
​        root: "/var/www/nginx/web1/"
​      - web2: 
​        listen: 8080
​        server_name: "web2.baidu.com"
​        root: "/var/www/nginx/web2/"
​      - web3: 
​        listen: 8080
​        server_name: "web3.baidu.com"
​        root: "/var/www/nginx/web3/"
  tasks:
​    - name: template config to 
​      template: src=./template/nginx.conf3.j2 dest=/data/nginx3.conf

cat template/nginx.conf3.j2 
{% for vhost in nginx_vhosts %}
server {
  listen {{ vhost.listen }}
  {% if vhost.server_name is defined %}
server_name {{ vhost.server_name }}
  {% endif %}
root {{ vhost.root }}
}
{% endfor %}

输出结果:
cat nginx3.conf 
server {
  listen 8080
  root /var/www/nginx/web1/
}

server {
  listen 8080
  server_name web2.baidu.com
  root /var/www/nginx/web2/
}
server {
  listen 8080
  server_name web3.baidu.com
  root /var/www/nginx/web3/
}

posted @ 2022-09-28 14:04  liwenchao1995  阅读(99)  评论(0编辑  收藏  举报