如何使用ansible在docker中运行etcd集群?

时间:2017-06-19 12:57:47

标签: docker ansible cluster-computing etcd

我正试图通过ansible在docker中运行etcd cluster。

我使用docker_container ansible模块,这就是我所拥有的:

- name: Run etcd KV node
      docker_container:
        name: "etcd0"
        image: quay.io/coreos/etcd
        network_mode: host
        command: [ "/usr/local/bin/etcd", \
        "-name etcd0", \
        "-advertise-client-urls http://{{ ansible_default_ipv4['address'] }}:2379,http://{{ ansible_default_ipv4['address'] }}:4001", \
        "-listen-client-urls http://0.0.0.0:2379,http://0.0.0.0:4001", \
        "-initial-advertise-peer-urls http://{{ ansible_default_ipv4['address'] }}:2380", \
        "-initial-cluster etcd0=http://{{ ansible_default_ipv4['address'] }}:2380", \
        "-initial-cluster-token etcd-cluster", \
        "-listen-peer-urls http://0.0.0.0:2380", \
        "-initial-cluster-state new" ]

这项工作在单一模式下,但是有多个节点出现问题,因为有etcd参数-initial-cluster应该包含所有节点,例如,如果有3个节点:

-initial-cluster etcd0=http://192.168.12.50:2380,etcd1=http://192.168.12.51:2380,etcd2=http://192.168.12.52:2380

我不知道如何循环遍历所有节点并构建此字符串以运行一个docker容器。有可能吗?

1 个答案:

答案 0 :(得分:2)

您服务的

hostvars魔法变量:

- name: Generate useful facts for current node 1
  set_fact:
    ip_addr: "{{ ansible_default_ipv4.address }}"
    etcd_name: "etcd{{ ansible_play_hosts.index(inventory_hostname) }}"

- name: Generate useful facts for current node 2
  set_fact:
    etcd_uri: "{{ etcd_name }}=http://{{ ip_addr }}:2380"

- name: Run etcd KV node
  docker_container:
    name: "{{ etcd_name }}"
    image: quay.io/coreos/etcd
    network_mode: host
    command:
      - /usr/local/bin/etcd
      - -name {{ etcd_name }}
      - -advertise-client-urls http://{{ ip_addr }}:2379,http://{{ ip_addr }}:4001
      - -listen-client-urls http://0.0.0.0:2379,http://0.0.0.0:4001
      - -initial-advertise-peer-urls http://{{ ip_addr }}:2380
      - -initial-cluster {{ ansible_play_hosts | map('extract',hostvars,'etcd_uri') | list | join(',') }}
      - -initial-cluster-token etcd-cluster
      - -listen-peer-urls http://0.0.0.0:2380
      - -initial-cluster-state new

P.S。我还重新格式化了你的command参数。