如何通过ansible playbook获取ec2实例的公共DNS名称

时间:2016-08-29 06:55:14

标签: amazon-ec2 ansible

我正在使用ansible来自动化ec2实例。我创建了ec2实例,然后尝试通过ec2_remote_facts模块获取其公共DNS名称。但是它给出了未在输出中定义的变量。

playbook:

- hosts:  localhost
  connection: local

  tasks:
    - name: ec2 instance facts
      ec2_remote_facts:
        region: ap-southeast-2
        filters:
          instance-state-name:  running
      register: ec2

    - debug:  var=ec2.instances.public_name


Output:PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [create ec2 instance] *****************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "ec2.instances.public_name": "VARIABLE IS NOT DEFINED!"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0  



Output for ec2.instances.

ok: [localhost] => {
    "ec2.instances": [
        {
            "ami_launch_index": "0", 
            "architecture": "x86_64", 
            "client_token": "", 
            "ebs_optimized": false, 
            "groups": [
                {
                    "id": "sg-6c016a08", 
                    "name": "default"
                }
            ], 
            "hypervisor": "xen", 
            "id": "i-915b1813", 
            "image_id": "ami-fedafc9d", 
            "instance_profile": null, 
            "interfaces": [
                {
                    "id": "eni-96de4acf", 
                    "mac_address": "0a:14:ac:64:c4:13"
                }
            ], 
            "kernel": null, 
            "key_name": "ansible.key", 
            "launch_time": "2016-08-29T07:32:10.000Z", 
            "monitoring_state": "disabled", 
            "persistent": false, 
            "placement": {
                "tenancy": "default", 
                "zone": "ap-southeast-2c"
            }, 
            "private_dns_name": "ip-xx-xx-xx-107.ap-southeast-2.compute.internal", 
            "private_ip_address": "xx.xx.xx.107", 
            "public_dns_name": "ec2-xx-xxx-xx-80.ap-southeast-2.compute.amazonaws.com", 
            "ramdisk": null, 
            "region": "ap-southeast-2", 
            "requester_id": null, 
            "root_device_type": "ebs", 
            "source_destination_check": "true", 
            "spot_instance_request_id": null, 
            "state": "running", 
            "tags": {
                "Name": "Demo"
            }, 
            "virtualization_type": "hvm", 
            "vpc_id": "vpc-abcaf4ce"
        }
    ]
}

我在这里缺少什么?

由于

Benjo

1 个答案:

答案 0 :(得分:2)

如果仔细观察ec2.instances,您可能会注意到:

  • 它是一个列表,因此您可以按索引ec2.instances[0]访问项目,也可以使用with_items:结构对其进行迭代。
  • 没有public_name属性,只有public_dns_name