Catalog
Overview of ansible jinja2 template
ansible allows conditional judgment and loops in jinja2 templates, but not in playbook
ansible jinja2 template usage
Basic grammar
{{EXPR}} outputs variable values, which output custom variable values or facts 1)playbook file uses template module 2) Variables in template files use {name}, such as {PORT} or facts
jinja2 Template Logic Judgment
#Loop expression {% for i in EXPR %} {% endfor %} #Conditional judgement {% if EXPR %} {% elif EXPR %} {% else %} {% ednif %} #Notes {# COMMENT #}
jinja2 example
- Edit playbook
[root@m01 ~]# vim jinja2.yml - hosts: web_group tasks: - name: Copy Template File template: src: ./motd.j2 dest: /etc/motd
- Prepare 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
- Execute playbook
ansible jinja2 manages nginx
Push files using playbook
1. Edit 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. Preparing configuration files
[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 management keepalived
Keeping alived original match
#keepalived master configuration file 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 configuration file 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 } }
Push the keepalived configuration file
[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
Prepare the keepalived configuration file
[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 } }