且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ansible AWS:无法连接到EC2实例

更新时间:2022-01-17 09:09:03

Ansible要求在VM上安装Python才能正常工作.

Ansible requires Python installed on VM to work.

这是您所需的代码:

  - name: upload an ssh keypair to ec2
    hosts: localhost
    connection: local
    gather_facts: False
    vars:
      keypair_name: Key_name
      key_material: "{{ lookup('file', 'keyfile') }}"
      region: "{{ region }}"


    tasks:
      - name: ssh keypair for ec2
        ec2_key:
          aws_access_key: "xxxxxxxxxxxxxxxxxxx"
          aws_secret_key: "Xxxxxxxxxxxxxxxxxxx"
          region: "{{ region }}"
          name: "{{ keypair_name }}"
          key_material: "{{ key_material }}"
          state: present


  - name: Power up an ec2 with LAMP stack installed
    hosts: localhost
    become: true
    become_user: root
    gather_facts: False
    vars:
      keypair: myKeyPair
      security_group: launch-wizard-1
      instance_type: t2.micro
      image: ami-47205e28
      region: x-x-x
      my_user_data: |   # install Python: Ansible needs Python pre-installed on the instance to work!
        #!/bin/bash
        sudo apt-get install python -y

    tasks:
      - name: Adding Python-pip
        apt: name=python-pip state=latest

      - name: Install Boto Library
        pip: name=boto

      - name: Launch instance (Amazon Linux)
        ec2:
           key_name: "{{ keypair }}"
           group: "{{ security_group }}"
           instance_type: "{{ instance_type }}"
           image: "{{ image }}"
           wait: true
           wait_timeout: 300
           user_data: "{{my_user_data}}"
           region: "{{ region }}"
           aws_access_key: "xxxxxxxxxxxxxxxxxxx"
           aws_secret_key: "Xxxxxxxxxxxxxxxxxxx"
        register: ec2

      - name: Add all instance public IPs to host group
        add_host: hostname={{ item.public_ip }} groups=ec2hosts
        with_items: "{{ ec2.instances }}"