首页 > 解决方案 > 使用魔法变量中的变量通过 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 中的变量,例如eth0eth1。通过为不同的集群使用某些接口来使角色更加灵活。

这是不工作的例子:

    - 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 吗?谢谢!

标签: ansiblecluster-computing

解决方案


推荐阅读