具有可变键的 Ansible docker_container etc_hosts

Ansible docker_container etc_hosts with variable key

我有一个 ansible 脚本,通过它我生成了一个 docker 容器并向其中添加了一些主机条目,因为 etc_hosts 将密钥作为主机名和相应的 IP 地址。在我的例子中,我需要让主机名和 IP 地址都由某个变量驱动,例如

docker_container:
name: image-name
image: image-to-be-pulled
state: started
restart_policy: always
etc_hosts:
  "{{ domain_1 }}": "{{ domain_1_ip }}"
  domain_2 : "{{ domain_2_ip }}"
  domain_3 : "{{ domain_3_ip }}"  

当我进行上述配置时,它会在主机文件中创建一个条目

xx.xx.xx.xxx {{ domain_1 }}

理想情况下,主机文件应包含针对 IP 的主机名,有人可以建议我如何实现这一点。提前致谢

试试这个语法:

docker_container:
  name: image-name
  image: image-to-be-pulled
  state: started
  restart_policy: always
  etc_hosts: >
    {
      "{{ domain_1 }}": "{{ domain_1_ip }}",
      "domain_2" : "{{ domain_2_ip }}",
      "domain_3" : "{{ domain_3_ip }}"
    }

这将形成类似 dict 的字符串,ansible 的模板器会将其评估为 dict。
请注意,每个项目都应该被引用并且对之间用逗号分隔。

我成功了...

在我的剧本(书)中:

- vars:
    my_etc_hosts: 
      {
        "host1.example.com host1": 10.3.1.5,
        "host2.example.com host2": 10.3.1.3
      }

(与接受的答案相比,没有“>”字符)

脱离剧本,角色...

在任务中:

- name: have the container created
  docker_container:
    etc_hosts: "{{ my_etc_hosts | default({}) }}"

在defaults/main.yml:

my_etc_hosts: {}

另外(上面的任务不需要,但是另一个模板任务的一部分):

在模板中,使用 jinja2:

{% for host in my_etc_hosts | default([]) %}
    --add-host "{{ host }}":{{ my_etc_hosts[host] }} \
{% endfor %}

(另外,您会看到如何处理一个 IP 地址的两个主机名:"fqdn alias1"。如果您将它们分成两个值,它们将在 /etc/hosts 中形成两行相同的 IP,根据手册页这是不正确的。)