ansible playbook使用jinja2语法渲染inventory下的主机名和IP到/etc/hosts

1. ansible inventory 下面的 hosts内容如下:

bash 复制代码
[all_host]
app1 ansible_host=10.2.162.147 
app2 ansible_host=10.2.162.148
app3 ansible_host=10.2.162.149
app4 ansible_host=10.2.162.150
app5 ansible_host=10.2.162.151

[nginx]
app1

2. hosts.j2内容如下

bash 复制代码
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for host in groups.all_host %}
{{ hostvars[host]['ansible_host'] }} {{ hostvars[host]['inventory_hostname'] }}
{% endfor %}

3. 渲染结果:

bash 复制代码
cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

10.2.162.147 app1
10.2.162.148 app2
10.2.162.149 app3
10.2.162.150 app4
10.2.162.151 app5
相关推荐
Minner-Scrapy6 分钟前
Scrapy 2.17 源码解析:Scheduler 调度器与磁盘/内存双队列
java·爬虫·python·scrapy·网络爬虫·twisted
CODER030416 分钟前
Anaconda和Mamba创建环境管理包常用命令合集
python·深度学习·conda·虚拟环境·mamba·常用命令大全
闲猫28 分钟前
LangGraph / Capabilities / Fault tolerance
python·agent·langgraph
IvanCodes1 小时前
Python 基础语法(一):变量、数据类型与运算符
python
程序员三藏2 小时前
浅谈性能测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·性能测试
l1258652 小时前
# RAG向量数据库优化实战:HNSW索引调参与生产级性能设计
数据库·python·mysql·langchain
meilindehuzi_a3 小时前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
Zane19943 小时前
调用了 async 函数却没执行?一文讲透协程、event loop 与 await
后端·python
OPEN-F3 小时前
Python进阶教程:装饰器与生成器深入
开发语言·python
zhipujiaoyu3 小时前
2026年大数据专科何去何从?就业前景、发展趋势全揭秘!
大数据·python