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

Upp*_*ppi 3 amazon-ec2 jinja2 ansible

- 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 }}"
Run Code Online (Sandbox Code Playgroud)

我在这本剧本中的意图是获取 tag_Name 并在实例中设置与主机名相同。我正在尝试不同的东西,但是在“循环主机主机”任务中使用标签属性时卡住了。我如何提及 Tag = "Name" 以将其保存为主机名,因为它是嵌套属性?

Kon*_*rov 5

你应该把你的剧本分成两部剧:

  1. 生成内存清单
  2. 在主机上运行任务

下面是一个例子:

- 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 }}
Run Code Online (Sandbox Code Playgroud)