如何为主机configuration主机文件的主机文件?

我已经开始学习和使用可以configuration我的舞台和生产服务器。 我想要做的一件事是通过库存文件configuration/ 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] ... 

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

 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 

这可能吗?

您可以从模板生成您的主机条目。 循环播放组列表,放弃all组和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 %} 

以上是使用IP地址{{host}} ,因为这可以让我在我的系统上进行testing,但是您可能更喜欢{{hostvars[host]['ansible_default_ipv4']['address']}}真实的环境,除非你是积极的,你总是在你的库存中使用IP地址。

在清单文件中:

  [myhosts] 192.168.29.2 host_name=host1 192.168.29.3 host_name=host2 

在playbook.yaml

  - name: Update /etc/hosts from inventory lineinfile: dest=/etc/hosts regexp='.*{{item}}$' line='{{hostvars[item]['ansible_eth1']['ipv4']['address'] }} {{hostvars[item]['host_name']}} ' state=present with_items: '{{groups.myhosts}}'