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

时间:2016-11-14 12:51:34

标签: amazon-web-services amazon-ec2 automation ansible ansible-playbook

目标是启动可以使用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.

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

1 个答案:

答案 0 :(得分:0)

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

如何解决?

  ip_addresses:
    - 172.31.1.117
    - 172.31.1.118
  • 请勿在{{1​​}}模块
  • 中指定count
  • 遍历ipaddresses列表(其中有2个)
  • 请确保通过引用ec2
  • 来使用IP

像这样:

{item}