ansible get tag_Name并在多个主机上设置主机名

时间:2017-11-30 00:02:02

标签: amazon-ec2 ansible jinja2

- hosts: ALL
gather_facts: true
remote_user:test
vars:
  Env: "{{ env }}"
tasks:
  - ec2_remote_facts:
    region: us-east-1
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
    filters:
     "tag:Env": "{{ env }}"
    register: instance_facts
  - name: group_hosts
    add_host: hostname={{ item }} groups=dev
    with_items: "{{ instance_facts.instances|map(attribute="private_ip_address)|list }}"
  - name: "loop over hosts for hostnames"
    hostname:
     name: {{ item }}
     with_items: "{{ instance_facts.instances|map(attribute=' ')|list }}"

我在本手册中的目的是获取tag_Name并在实例中设置与hostname相同的内容。我正在尝试不同的东西,但是在“为主机托管的循环”任务中使用标签属性时卡住了。我如何提及Tag =“Name”将其保存为主机名,因为它将是一个嵌套属性?

3 个答案:

答案 0 :(得分:4)

你应该将你的剧本分成两个剧本:

  1. 生成内存库存
  2. 在主机上运行任务
  3. 以下是一个例子:

    - hosts: localhost
      gather_facts: no
      tasks:
        - ec2_remote_facts:
            region: us-east-1
            aws_access_key: "{{ aws_access_key }}"
            aws_secret_key: "{{ aws_secret_key }}"
            filters:
              "tag:Env": "{{ env }}"
            register: instance_facts
        - add_host:
            name: "{{ item.tags.Name }}"
            ansible_host: "{{ item.private_ip_address }}"
            group: dev
          with_items: "{{ instance_facts.instances }}"
    
    - hosts: dev
      gather_facts: true
      tasks:
        - hostname:
            name: {{ inventory_hostname }}
    

答案 1 :(得分:1)

我认为最好的方法是在userdata中设置它。

在Linux中:

pip install awscli
ID=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e "s/.$//")
NAME=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ID" --region $REGION --output=text | grep Name | awk '{ print $3 }')
#set the hostname according your distro

答案 2 :(得分:0)

@Konstantin Suvorov谢谢,这是一个很好的例子。 我将在'-add_host:'之后添加暂停,以使第二部分完成:

- name: Let's wait for SSH to come up. Usually that takes ~10 seconds
      local_action: wait_for
        host={{ item.private_ip }}
        port=22
        state=started
      with_items: '{{ instance_facts.instances }}'