安全 |专有网络 | EC2 |动态库存文件创建错误 |

Ansible | VPC | Ec2 | Dynamic Inventory file creation error |

我正在尝试创建一个 VPC 并从本地主机部署两个 ec2 实例。创建清单文件时出错,public IP 未从循环中获取。

这是代码:


  ######################Launching Web Server#######################
    - name: "Launching Web Server"
      ec2:
        aws_access_key: "{{ aws_access_key }}"
        aws_secret_key: "{{ aws_secret_key }}"
        region: "{{ region }}"
        key_name: "{{ keypair_name }}"
        instance_type: "{{ instance_type }}"
        image: "{{ image_id }}"
        group: Webserver-sg
        vpc_subnet_id: "{{ web_subnet.subnet.id }}"
        instance_tags:
          Name: "webserver"
        count_tag:
          Name: "webserver"
        exact_count: 1
        wait: true

 
    - name: "Fetching Ec2 Instance Details"
      ec2_instance_info:
        aws_access_key: "{{ aws_access_key }}"
        aws_secret_key: "{{ aws_secret_key }}"
        region: "{{ region }}"
        filters:
          vpc-id: "{{ vpc_id }}"
          instance-state-name: [ "running"]
      register: ec2
            
  ###########Creating Dynamic Inventory for webserver###############

    - name: "Creating Dynamic Inventory"
      add_host:
        name: "{{ item.public_ip }}"
        groups: "local_webserver"
        ansible_host: "{{ item.public_ip }}"
        ansible_port: 22
        ansible_user: "ec2-user"
        ansible_ssh_private_key_file: "{{ keypair_name }}.pem"
        ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
      with_items: "{{ ec2.instances }}"
      

下面是创建动态库存文件时的错误。

TASK [Creating Dynamic Inventory] ********************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'public_ip'\n\nThe error appears to be in '/root/new_vpc/main.yml': line 215, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  ###########Creating Dynamic Inventory for webserver###############\n    - name: \"Creating Dynamic Inventory\"\n      ^ here\n"}

NO MORE HOSTS LEFT ***********************************************************************************************************************************


正如他们的页面所说,use of ec2: is not recommended and that's likely why it does not document the return values the same way that ec2_instance: does, otherwise one could have seen that the attribute is public_ip_address