如何为ansible清单中的主机设置配置hosts文件?

hoo*_*enz 1 ansible

我已经开始学习和使用 ansible 来配置我的临时和生产服务器。我想做的一件事是通过清单文件配置 /etc/hosts。

这似乎是可能的。这是一种这样的用法:https : //gist.github.com/rothgar/8793800

但是,我对 Ansible 有点生疏,我不明白。有人可以用简单的英语解释一下我是如何让它在实践中工作的吗?

例如,如果我的库存文件包含。

[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]
...
Run Code Online (Sandbox Code Playgroud)

我想一致地说,运行剧本后我的主机文件包含

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
Run Code Online (Sandbox Code Playgroud)

这可能吗?

lar*_*sks 5

您可以从模板生成主机条目。循环遍历组列表,丢弃像alland这样的组,ungrouped然后遍历每个组中的主机列表:

{# 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 %}
Run Code Online (Sandbox Code Playgroud)

以上{{host}}用于 ip 地址,因为这让我可以在我的系统上对其进行测试,但您可能更喜欢{{hostvars[host]['ansible_default_ipv4']['address']}}在真实环境中,除非您确定您总是在库存中使用 ip 地址。