Ansible-Jinja2模板

文章目录

一、Jinja2介绍

什么是

Python的模板引擎,有自带的模板语法

Jinja2与Ansible关系

二、Ansible如何使用Jinja2

使用template模板

Jinja2文件中使用判断和循环

Jinja2文件中使用判断

*shell判断:

语法
jinja2 复制代码
{% if 条件1 %}
动作1
{% elif 条件2 %}
动作2
{% else %}
动作3
{% endif %}

解释:

如果满足条件1,执行动作1,如果不满足条件1,但满足条件2,则执行动作2;

如果条件1、2都不满足,那么执行动作3

示例

Jinja2文件中使用循环

语法
jinja2 复制代码
{% for n in 条件 %}
动作
{% endfor %}
示例

案例:Ansible使用Jinja2模板生成keepalived配置文件

已知:主机清单有如下配置:

ini 复制代码
[lb_servers]
lb01		ansible_ssh_host=172.16.1.5
lb02		ansible_ssh_host=172.16.1.6

编写keepalived.j2文件

jinja2 复制代码
global_defs {
	router_id {{ansible_hostname}}
}

vrrp_instance VI_lb {
	<% if ansible_hostname == 'lb01' %>
		state MASTER
		priority 100
	<% else %>
		state BACKUP
		priority 99
	<% endif %>	
	
	virtual_router_id 43
	authentication {
		auth_type PASS
		auth_pass 1234
	}
	virtual_ipaddress {
		10.0.0.43/32
	}
	...
}

编写ansible playbook文件

yaml 复制代码
---
- name: the play1
  hosts: lb_servers
  become: no
  tasks:
    - name: 安装keepalived
    - name: 配置keepalived
      template:
        src: keeplived.j2
        dest: /etc/keeplived/keepalive.conf
      notify: restart_keepalived
  handlers:
    - name: restart_keepalived
      service:
        name: keepalived
        state: restarted 

案例:Ansible使用Jinja2生成负载均衡Nginx配置文件

编写xxx.j2文件

jinja2 复制代码
upstream backend {
<% for n in range(1,11) %>
server 172.16.1.{{n}};
<% endfor %>
}

server{
	listen 80;
	server_name xxx.com;
	location /{
		proxy_pass http://backend;
	}
}

编写ansible playbook文件

yaml 复制代码
---
- name: the play1
  hosts: all
  become: no
  tasks:
    - name: the task1
      template:
        src: xxx.j2
        dest: /etc/nginx/conf.d/xxx.conf 
      
相关推荐
K_i1342 天前
Ansible实战:VMware下K8s自动化部署指南
kubernetes·自动化·ansible
许泽宇的技术分享2 天前
Ansible核心架构深度剖析:从源码看IT自动化的“简单“哲学
python·ansible·自动化运维·devops·it基础设施
荣光波比2 天前
Ansible(三)—— 使用Ansible自动化部署LNMP环境实战指南
运维·自动化·云计算·ansible
tt666qq3 天前
运维自动化之 Ansible 核心知识点总结
运维·自动化·ansible
C-20028 天前
初探 ansible 部署 devops 持续集成持续交付
ci/cd·ansible·devops
东窗西篱梦8 天前
Ansible自动化运维:从入门到实战,告别重复劳动!
运维·自动化·ansible
weixin_5078479510 天前
Ansible
ansible
小白不想白a10 天前
【ansible/K8s】K8s的自动化部署源码分享
kubernetes·自动化·ansible
三坛海会大神55511 天前
Ansible详解(一)Ansible简介和基础命令及操作
运维·ansible
東雪蓮☆11 天前
Ansible Playbook 编写与模块详解
linux·运维·网络·ansible