ansible - 使用魔法变量中的变量通过 ansible 写入 /etc/hosts
问题描述
我正在尝试通过 ansible 写入文件 /etc/hosts 以用于集群目的。我想在魔法变量中使用 group_vars 变量。这是一个工作示例,我使用ansibe_default_ipv4没有 group_vars 变量:
- name: Add hosts to /etc/hosts
lineinfile:
args:
dest: "/etc/hosts"
regexp: "{{ hostvars[item]['ansible_default_ipv4']['address'] }}"
line: "{{ hostvars[item]['ansible_default_ipv4']['address'] }} {{ hostvars[item]['ansible_fqdn'] }} {{ hostvars[item]['ansible_fqdn'].split('.')[0] }}"
with_items: "{{ play_hosts }}"
tags: ha-cluster
但是我想使用ansible_{{ cluster_interface }}之类的东西而不是ansible_default_ipv4,其中cluster_interface是 group_vars 中的变量,例如eth0或eth1。通过为不同的集群使用某些接口来使角色更加灵活。
这是不工作的例子:
- name: Add hosts to /etc/hosts
lineinfile:
args:
dest: "/etc/hosts"
regexp: "{{ hostvars[item]['ansible_default_ipv4']['address'] }}"
line: "{{ hostvars[item]['ansible_{{ cluster_ineterface }}']['ipv4']['address'] }} {{ hostvars[item]['ansible_fqdn'] }} {{ hostvars[item]['ansible_fqdn'].split('.')[0] }}"
with_items: "{{ play_hosts }}"
tags: ha-cluster
错误:
fatal: [node1.linux.cluster.test]: FAILED! => {
"failed": true,
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined.
The error was: 'dict object' has no attribute 'ansible_{{ cluster_interface }}'\n
\nThe error appears to have been in '/home/name/.ansible/roles/ha-cluster/tasks/main.yml':
line 36, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n
\nThe offending line appears to be:\n\n\n- name: Add hosts to /etc/hosts\n ^ here\n"
}
Ansible 版本:2.2.1.0-2
主机:Debian 9.4
甚至可以在魔法变量中使用 group_vars 吗?谢谢!
解决方案
推荐阅读
- python - 按布尔值过滤 Pandas 系列
- python-3.x - 为什么我无法在 python 文件中暂停、恢复或退出音乐?
- reactjs - 数组上的 React setState 在调用后立即将值重置为 null(功能组件)
- android - 读取大文件并插入房间数据库
- woocommerce - WooCommerce:更新订单
- google-cloud-platform - 基于“已用”内存的 Google Compute Engine 自动缩放
- javascript - 根据 JavaScript 或 jQuery 中的其他数组值对数组进行排序
- python-3.x - 对大型文本文件中的数据进行排序并将其转换为数组
- c++ - Valgrind 在 std::string::swap 中报告 SIGILL
- authentication - Xamarin Forms - 登录后重定向问题