Ŀ¼
ansible允许jinja2模板中使用条件判断和循环,但是不允许在playbook中使用
{{ EXPR }}输出变量值,会输出自定义的变量值或facts 1)playbook文件使用template模块 2)模板文件里面变量使用{{名称}},比如{{PORT}}或使用facts
#循环表达式 {% for i in EXPR %} {% endfor %} #条件判断 {% if EXPR %} {% elif EXPR %} {% else %} {% ednif %} #注释 {# COMMENT #}
- 编辑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
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
#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 } }
[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
[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 } }
来源:博客园
作者:1naonao
链接:https://www.cnblogs.com/1naonao/p/11575271.html