ansible jinja2模板概述
程序员文章站
2023-04-04 15:36:57
[toc] ansible jinja2模板概述 ansible允许jinja2模板中使用条件判断和循环,但是不允许在playbook中使用 ansible jinja2模板使用 基本语法 jinja2模板逻辑判断 jinja2示例 编辑playbook 准备motd.j2 执行playbook a ......
目录
ansible jinja2模板概述
ansible允许jinja2模板中使用条件判断和循环,但是不允许在playbook中使用
ansible jinja2模板使用
基本语法
{{ expr }}输出变量值,会输出自定义的变量值或facts 1)playbook文件使用template模块 2)模板文件里面变量使用{{名称}},比如{{port}}或使用facts
jinja2模板逻辑判断
#循环表达式 {% for i in expr %} {% endfor %} #条件判断 {% if expr %} {% elif expr %} {% else %} {% ednif %} #注释 {# comment #}
jinja2示例
- 编辑playbook
[root@m01 ~]# vim jinja2.yml - hosts: web_group tasks: - name: copy template file template: src: ./motd.j2 dest: /etc/motd
- 准备motd.j2
[root@m01 ~]# vim motd.j2 welcome to {{ ansible_fqdn }} this system total mem is : {{ ansible_memtotal_mb }} mb this system free mem is: {{ ansible_memfree_mb }} mb
- 执行playbook
ansible jinja2管理nginx
使用playbook推送文件
1.编辑playbook
[root@m01 ~]# vim lb.yml - hosts: lb_group vars: http_port: 80 server_name: www.drz.com tasks: - name: copy template: src: ./www.drz.com.conf.j2 dest: /etc/nginx/conf.d/www.drz.com.conf notify: reload nginx handlers: - name: reload nginx systemd: name: nginx state: reloaded
2.准备配置文件
[root@m01 ~]# vim lb.yml - hosts: lb_group vars: http_port: 80 server_name: www.drz.com tasks: - name: copy template: src: ./www.drz.com.conf.j2 dest: /etc/nginx/conf.d/www.drz.com.conf notify: reload nginx handlers: - name: reload nginx systemd: name: nginx state: reloaded
ansible jinja2管理keepalived
keepalived原配
#keepalived master 配置文件 global_defs { router_id lb01 } vrrp_instance vi_1 { state master interface eth0 virtual_router_id 50 priority 150 advert_int 1 authentication { auth_type pass auth_pass 1111 } virtual_ipaddress { 10.0.0.3 } } #keepalived backup配置文件 global_defs { router_id lb02 } vrrp_instance vi_1 { state backup interface eth0 virtual_router_id 50 priority 100 advert_int 1 authentication { auth_type pass auth_pass 1111 } virtual_ipaddress { 10.0.0.3 } }
推送keepalived配置文件
[root@m01 ~]# vim keepalived.yml - hosts: lb_group tasks: - name: copy file template: src: ./keepalived.j2 dest: /etc/keepalived/keepalived.conf notify: restart keepalived handlers: - name: restart keepalived systemd: name: keepalived state: restarted
准备keepalived配置文件
[root@m01 ~]# vim keepalived.j2 global_defs { router_id {{ ansible_fqdn }} } vrrp_instance vi_1 { {% if ansible_fqdn == "lb01" %} state master priority 150 {% else %} state backup priority 100 {% endif %} interface eth0 virtual_router_id 50 advert_int 1 authentication { auth_type pass auth_pass 1111 } virtual_ipaddress { 10.0.0.3 } }