大网数据广告活动
服务器运维问答

How do I set configure the hosts file for hosts in ansible inventory?

· 52CE 我爱测

I've started learning and using ansible for configuring my staging and production servers. One thing I'd like to do is configure /etc/hosts through the inventory file. It seems that this is possible. Here is one such usage: https…

问题原文

原帖链接 · hookenz · CC BY-SA 3.0

I've started learning and using ansible for configuring my staging and production servers. One thing I'd like to do is configure /etc/hosts through the inventory file.

It seems that this is possible. Here is one such usage: https://gist.github.com/rothgar/8793800

However, I'm a little green to Ansible and I don't get it. Can someone please explain in plain english how I make it work in practice?

For example, if my inventory file contains.

[compute]
1.2.3.4 
5.6.7.8

[db]
2.3.4.5
6.7.8.9
10.11.12.13

[all]
compute
db

[all:vars]
...

I'd like to say with consistency that my hosts file after running the playbook contained

2.3.4.5 db1
6.7.8.9 db2
10.11.12.13 db3
1.2.3.4 compute1
5.6.7.8 compute2

Is this possible?

已采纳解答

原帖链接 · larsks · CC BY-SA 3.0

You could generate your hosts entries from a template. Loop over the list of groups, discard groups like all and ungrouped, and then loop over the list of hosts in each group:

{# this loops over the list of groups.  inside the loop #}
{# "group" will be the group name and "hosts" will be the #}
{# list of hosts in that group. #}
{% for group,hosts in groups.items() %}

{# skip the "all" and "ungrouped" groups, which presumably #}
{# you don't want in your hosts file #}
{% if group not in ["ungrouped", "all"] %}

{# generate a hosts entry for each host, using the "loop.index" #}
{# variable and the group name to generate a unique hostname. #}
{% for host in hosts %}
{{host}} {{group}}{{loop.index}}
{% endfor %}

{% endif %}
{% endfor %}

The above is using {{host}} for the ip address, because this lets me tested it out on my system, but you would probably prefer {{hostvars[host]['ansible_default_ipv4']['address']}} in a real environment, unless you are positive you are always using ip addresses in your inventory.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-02-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。