首页 > 解决方案 > 使用inventory_hostname 作为字典查找的一部分

问题描述

我想使用 inventory_hostname 作为字典查找的一部分来配置使用相同模板但具有不同变量的服务器

/etc/ansible/主机

[nodes]
node1 ansible_host=192.168.0.2

角色/角色/默认值/main.yml

node1:
  if1: eth1
  ip1: 1.1.1.1/11

node2:
  if1: eth4
  ip1: 4.4.4.4/44

角色/角色/任务/main.yml

- name: test
  debug:
    msg: "{{ [inventory_hostname].[if1] }} end test  "

预计这会显示eth1在控制台上,但出现错误

fatal: [node1]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: 'if1' is undefined\n\nThe error appears to have been in '/root/ansible/roles/role/tasks/main.yml': line 6, 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: test\n  ^ here\n"
}

标签: ansible

解决方案


您正在寻找的是vars

- name: test
  debug:
    msg: "{{ vars[ansible_hostname]['if1'] }} end test"

推荐阅读