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 
      
相关推荐
lbb 小魔仙19 小时前
【Linux】Ansible 自动化运维实战:2000+ 节点配置标准化教程
linux·运维·ansible
扑火的小飞蛾4 天前
【Ansible学习笔记01】 批量执行 shell 命令
笔记·学习·ansible
oMcLin4 天前
如何在 Red Hat Linux 服务器上使用 Ansible 自动化部署并管理多节点 Hadoop 集群?
linux·服务器·ansible
曲幽6 天前
FastAPI响应实战:从JSON到HTML,轻松驾驭多种数据格式
python·html·json·fastapi·web·jinja2·responses
linux修理工7 天前
vagrant ubuntu 22.04 ansible 配置
ubuntu·ansible·vagrant
biubiubiu07068 天前
Ansible自动化
运维·自动化·ansible
秋4278 天前
ansible配置与模块介绍
ansible
秋4279 天前
ansible剧本
linux·服务器·ansible
码农101号10 天前
Ansible - Role介绍 和 使用playbook部署wordPress
android·ansible
大千AI助手11 天前
BashOperator 中 bash_command 以 .sh 结尾会被误判为模板文件的问题分析
任务调度·airflow·jinja2·模版·大千ai助手·bashoperator·找不到模版