如何启动多个 aws 实例并使用 ansible 分配给定的 IP 地址范围?

How to spin up multiple aws instances and assign given range of IP addresses using ansible?

objective 是启动多个实例,这可以使用 count 来实现,但我已经给出了特定范围的私有 IP 地址,并想将它们分配给实例。

下面是我现在的剧本,

---
  - name: Provision an EC2 Instance
    hosts: local
    connection: local
    gather_facts: False
    tags: provisioning
    # Necessary Variables for creating/provisioning the EC2 Instance
    vars:
      instance_type: t2.micro
      security_group: default # Change the security group name here
      image: ami-a9d276c9 # Change the AMI, from which you want to launch the server
      region: us-west-2 # Change the Region
      keypair: ansible # Change the keypair name
      ip_addresses:
        - 172.31.1.117/32
        - 172.31.1.118/32
      count: 2

    tasks:

      - name: Launch the new EC2 Instance
        local_action: ec2
                      group={{ security_group }}
                      instance_type={{ instance_type}}
                      image={{ image }}
                      wait=true
                      region={{ region }}
                      keypair={{ keypair }}
                      count={{count}}
                      vpc_subnet_id=subnet-xxxxxxx
#                      private_ip={{private_ip}}
        with_items: ip_addresses
        register: ec2

      - name: Wait for SSH to come up
        local_action: wait_for
                      host={{ item.public_ip }}
                      port=22
                      state=started
        with_items: ec2.instances

      - name: Add tag to Instance(s)
        local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
        with_items: ec2.instances
        args:
          tags:
            Name: ansible

      - name: Update system
        apt: update_cache=yes

      - name: Install Git
        apt:
          name: git
          state: present

      - name: Install Python2.7
        apt:
          name: python=2.7
          state: present

      - name: Install Java
        apt:
          name: openjdk-8-jdk
          state: present

虽然启动了实例但没有分配要分配的 IP 地址。我收到以下警告

PLAY [Provision an EC2 Instance] ***********************************************

TASK [Launch the new EC2 Instance] *********************************************
changed: [localhost -> localhost] => (item=172.31.1.117/32)
changed: [localhost -> localhost] => (item=172.31.1.118/32)
[DEPRECATION WARNING]: Skipping task due to undefined attribute, in the future this will be a fatal error.. This feature will be removed in a future release. Deprecation warnings can be 
disabled by setting deprecation_warnings=False in ansible.cfg.

请建议我实现此目标的最佳方法。

  • 您正在提供 count=2,因此将启动 2 个实例
  • 您的 IP 地址错误,您提供的是 CIDR 而不是 IP
  • 启动实例时,您没有在代码中的任何地方使用 IP 地址

如何修复?

  ip_addresses:
    - 172.31.1.117
    - 172.31.1.118
  • 不要在 ec2 模块中指定 count
  • 遍历 IP 地址列表(有 2 个)
  • 请确保您通过引用 {item}
  • 使用 IP

像这样:

private_ip={{item}}