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

 

转载于:https://www.cnblogs.com/FRESHMANS/p/9450671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值