Fork me on GitHub

Jinja2

掌握了Jinja才是深入Ansible-playbook的开始

Jinja2 For循环

变量的提取使用 {{variable}}
{%statement execution%} 括起来的内容为Jinja2命令执行语句

{% for item in all_items %}
    {{ item }}
    {% endfor %}
#导入模块
from jinja2 import Template

#设置模板内容
template_content = ''' 
{% for id in range(201,211) %} 
192.168.37.{{ id }} web{{ "%02d"|format(id-200) }}.magedu
{% endfor %} 
''' 
# 创建模板对象 
template = Template(template_content)

# 渲染模板 
output = template.render()

# 打印模板
print(output)

Jinja2 If 条件

{% if my_conditional %}
       ...
    {% endif %}

编排目录结构

mysqlconf.yaml
roles/mysqlconf/
        ├── templates
        │ └── mycnf.j2
mkdir -p roles/mysqlconf/templates

只定义了Templates而没有定义Tasks,Ansible也支持这样的方式,只是mysqlconf这个role的功能不全而已,但不影响其正常使用

我们本次的Tasks调度配置在mysqlconf.yaml文件中

mysqlconf.yaml

- name : Mysql conf template
  hosts : ubuntu
  vars:
    PORT: 1331
  tasks:
   - template: 
      src: roles/mysqlconf/templates/mycnf.j2 
      dest: /etc/mycnf.conf.yaml

roles/mysqlconf/templates/mycnf.j2

{% if PORT %}
    bind-address=0.0.0.0:{{ PORT }}
{% else %}
    bind-address=0.0.0.0:3306
{% endif %}
ansible-playbook mysqlconf.yaml 

PLAY [Mysql conf template] ******

TASK [Gathering Facts] ******
ok: [192.168.255.110]

TASK [template] ******
changed: [192.168.255.110]

PLAY RECAP ******
192.168.255.110            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Jinja多值合并

{% for node in groups["db"] %}
    {{ node | join("") }}:5672
    {% if not loop.last %}
    {% endif %}
{% endfor %}
posted on 2024-08-21 18:30  anyux  阅读(83)  评论(0)    收藏  举报