Ansible剧本,可获取我的AWS环境的所有私有IP

时间:2019-09-11 15:07:38

标签: amazon-ec2 ansible

我正在使用Ansible pLaybook对我的AWS上的所有实例进行扫描。我需要获取他们的私有IP并将其列出

我尝试使用json查询来过滤Json格式。格式输出如下所示..............

ok: [localhost] => {
    "msg": [
        { 
            "private_dns_name": "ip-10.89.3.12.ec2.internal", 
            "private_ip_address": "10.89.3.12", 
            "public_dns_name": "", 
            "public_ip_address": null, 

        }, 
- hosts: localhost
  connection: local
  gather_facts: yes
  tasks:
    - name: Gather EC2 remote facts.
      ec2_remote_facts:
        region: "{{ region | default('us-east-1') }}"
        filters:
          instance-state-name: running
      register: ec2_remote_facts
    -  set_fact:
         msg: "{{ ec2_remote_facts | json_query('results[*].instances[*].private_ip_address') }} "
    - debug: var=msg

我希望输出仅是private_IP的列表

1 个答案:

答案 0 :(得分:0)

我尝试使用“ ec2_instance_facts”,如下所示:

- hosts: localhost
  connection: local
  gather_facts: yes
  tasks:
    - name: Gather EC2 remote facts.
      ec2_instance_facts:
        filters:
          availability-zone: ap-south-1b
      register: ec2_instance_facts
    -  set_fact:
         msg: "{{ ec2_instance_facts | json_query('instances[*].private_ip_address') }} "
    - debug: var=msg

和下面是输出:

PLAY [localhost] **************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Gather EC2 remote facts.] ***********************************************************************************************************************************************************************************
ok: [localhost]

TASK [set_fact] ***************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "172.31.6.87"
    ]
}

PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

根据我创建的EC2实例,哪个是正确的。