ansible Templates

Files和templates

  files和templates均用于ansible文件处理,两者的主要区别是:Files目录下的文件无需写绝对路径即可将文件传输到远程主机,templates目录下文件以Jinja2渲染,支持传送到主机文件的变量替换

  template变量示例可看 https://www.cnblogs.com/FRESHMANS/p/8204721.html,template文件内的变量可在vars目录里直接定义

 

Jinja2模板高度自定义

①、for循环

语法:
{% for i in  all_items %}
{{ item }}
{% endfor%}


示例:循环10个数,打印出ip , web{{id-200}}.edu.cn
{% for id in range(201,211)  %}
10.10.10.{{ id }}  web{{ "%02d | format(id-200)" }}.edu.cn
{% endfor %}


执行效果:

10.10.10.201 web01.edu.cn
......
10.10.10.210 web10.edu.cn

 

②、if语句

语法:
{% if my_conditional %}
.....
{% endif %}


示例:配置mysql配置文件。如果有设置变量则按变量,如果没有按默认

tasks.yml

---
- name: mysql
  hosts: all
  vars: 
       PORT: 3301
  tasks: 
        - template: src=/templates/mycnf.j2 dest=/etc/my.cnf      #src这里写mycnf.j2的tempalte目录


mycnf.j2

{% if PORT % }
bind-address=0.0.0.0:{{ PORT }}
{% else %}
bind-address=0.0.0.0:3306
{% endif %}

 

可用一句概括

bind-address=0.0.0.0{{ PORT | default(3306)}}

 

 

③、多值合并

目录结构:

ansible
├── join.yml
└── roles
    └── join
        └── templates
            └── list.j2


[root@bogon ansible]# cat join.yml 
---
- hosts: test
  gather_facts: no
  vars: 
    port: 1111
  tasks:
    - template: src=roles/join/templates/list.j2  dest=/root/list.txt
  roles:
    - { role: join} 
[root@bogon ansible]# cat roles
/join/templates/list.j2 {% for node in groups['test'] %} {{ node | join("-") }}:5673            #这里意思为将hosts文件里 test组下的ip,加上端口5673,合并,join表示不在ip中间加任何东西 {% if not loop.last %} {% endif %} {% endfor %} 执行结果: [root@node1 ~]# cat list.txt 10.10.10.12:5673 10.10.10.162:5673

 

posted @ 2018-08-10 11:14  FRESHMANS  阅读(710)  评论(0编辑  收藏  举报