Ansible:如何为主机设置序列号



我正在尝试在EC2上预置主机,因此我正在使用Ansible动态清单。

我想做的是;为每个节点设置序列号。

例如:"myid"配置的 Zookeeper

Zookeeper 需要为每个节点提供名为"myid"的序列号;主机 A 为 1,主机 B 为 2,hostC 为 3,依此类推。

这是我的剧本中将"myid"文件复制到主机的部分。

- name: Set myid
  sudo: yes
  template: src=var/lib/zookeeper/myid.j2 dest=/var/lib/zookeeper/myid

下面应该是这样的myid.j2

{{ serial_number }}

问题是:变量"{{ serial_number }}"应该是什么样的?

我找到了一个使用 Ansible 的 with_index_items 语法来做到这一点的干净方法:

tasks:
  - name: Set Zookeeper Id
    set_fact: zk_id={{item.0 + 1}}
    with_indexed_items: "{{groups['tag_Name_MESOS_MASTER']}}"
    when: item.1 == "{{inventory_hostname}}"

然后可以将/etc/zookeeper/conf/myid 模板设置为

{{zk_id}}

这假设您使用的是 AWS 动态清单。

我通过在创建每个 EC2 实例时为每个 EC2 实例分配一个编号作为标签来解决此问题。然后,我在创建myid文件时引用该标记。以下是我用于创建 EC2 实例的任务,为简洁起见,省略了所有不重要的字段。

- name: Launch EC2 instance(s)
  with_sequence: count="{{ instance_count }}"
  ec2:
    instance_tags:
      number: "{{ item }}"

然后,在这些服务器上安装 ZooKeeper 时,我使用动态清单获取所有标记为 zookeeper 的服务器,并使用myid文件中的 number 标记。

- name: Render and copy myid file
  copy: >
    content={{ ec2_tag_number }}
    dest=/etc/zookeeper/conf/myid

注意:创建 EC2 实例时,我需要在ec2模块中使用with_sequence而不是count字段。否则,我将没有要为标签捕获的索引。


如果您希望 playbook 能够处理将节点添加到当前集群的问题,您可以查询标记为 zookeeper 的 EC2 实例数,并将其添加到迭代索引中。这通常很好,因为如果没有current_instance_count,它将是 0。

- name: Determine how many instances currently exist
  shell: echo "{{ groups['tag_zookeeper'] | length }}"
  register: current_instance_count
- name: Launch EC2 instance(s)
  with_sequence: count="{{ instance_count }}"
  ec2:
    instance_tags:
      number: "{{ item|int + current_instance_count.stdout|int }}"

无需使用模板,可以直接在剧本中分配myid文件的内容。假设您已将所有 ec2 实例收集到组"ec2hosts"中。

- hosts: ec2hosts
  user: ubuntu
  sudo:Trues
  tasks:
    - name: Set Zookeeper Id
      copy: >
      content={{ item.0 + 1 }}
      dest=/var/lib/zookeeper/myid
      with_indexed_items: "{{groups['ec2hosts']}}"
      when: item.1 == "{{inventory_hostname}}"

最新更新