ansible - Ansible 获取清单主机组的主机名和 IP
问题描述
我正在尝试获取主机的主机名和 IP 地址并将它们保存到文件中。
我有这个解决方案;
- name: Create File with hosts and IP address.
when: inventory_hostname in groups['local']
lineinfile:
dest: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/hosts.txt"
create: yes
line: "{{hostvars[inventory_hostname].ansible_hostname}}:{{hostvars[inventory_hostname].ansible_default_ipv4.address}}"
但问题出在我的 hosts 文件中,我有两个组,local
并且Servers
. 我想得到Servers
唯一而不是唯一的local
组localhost
。
我已经尝试了下面的行,但它不起作用,它给了我一个错误。
line: "{{ hostvars[ groups['Servers'][0] ].ansible_hostname }} :{{ hostvars[ groups['Servers'][0] ].ansible_default_ipv4.address }}"
我四处搜索,这就是我发现的,我该怎么做?
解决方案
我会为此使用 jinja 模板:
# hosts_file.j2
{% for server in groups['Servers'] %}
{{hostvars[server]['ansible_facts']['hostname']}}:{{hostvars[server]['ansible_facts']['default_ipv4']['address']}}
{% endfor %}
- hosts: localhost
tasks:
- name: create hosts file from template
template:
src: hosts_file.j2
dest: {{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/hosts.txt
推荐阅读
- flutter - 动态 ListView 内的 ListView ( Pagewise )
- css - 父容器有overflow:auto,但是当屏幕高度改变时子容器的高度仍然改变
- javascript - DataTables - 从单元格数据中的跨度获取 ID
- ajax - 使用分页的 Wordpress 延迟加载
- r - 警告信息 - 来自 dummies 包的 dummy
- c++ - 无法在不使用变量的情况下比较 C++ 中的字符串
- python-3.x - Python 停止了打开 Jupiter 笔记本的工作
- python - 如何在枚举的 for 循环中获取索引结果列表
- angular - 当输入值不变时如何强制对输入进行更改检测
- python - 在 Django 虚拟环境中使用 mysqlclient 进行迁移时出现问题