Ansible: how to get host specific variable value by hostname

▼魔方 西西 提交于 2019-12-11 05:52:17

问题


I'd like to insert initial values to a client's sqlite by Ansible and the values are different for every host.

I created myrole/vars/main.yml:

hostname1:
    id: id_1
    value: value_1
hostname2:
    id: id_2
    value: value_2

I want to to get it by {{ {{ inventory_hostname }}.id }} and insert the template of .sql, but it is not working.


回答1:


You can achieve by modify your variable like this:

clients:
  hostname1:
    id: id_1
    value: value_1
  hostname2:
    id: id_2
    value: value_2

Then in your template:

{{ clients[inventory_hostname].id }}

where inventory_hostname will be hostname1,hostname2 etc.

Hope that help you.




回答2:


A role should not include host specific configuration. Instead store host specific configuration in host vars. Create a file for every host relative to your playbook in the host_vars directory, e.g. host_vars/hostname1 with the content

id: id_1
value: value_1

This file is automatically loaded by Ansible and you can use the vars id and value right away.

If you need to access the variables from other hosts or from local tasks, you can access them through the global hostvars dict:

hostvars[inventory_hostname].id


来源:https://stackoverflow.com/questions/37832916/ansible-how-to-get-host-specific-variable-value-by-hostname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!