Ansible – Installing package on AWS EC2 Instance (ec2_instance_info)

This playbook is scripted to connect to EC2 instance via tags, then install the system package(s). The example below shows how to install Git, however, this can be any package. Order of things:

You will obviously need to change the playbook values below in the script to match your AWS information. The values that need to be changed are highlighted in purple. Enjoy!

Order of things:
1. Get the ec2_instance_info,
2. connect via ssh into the instance, and
3. install git (could be any package).

- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
    - name: Gather information about all instances
      ec2_instance_info:
        filters:
          "tag:Name": webservers
      register: ec2
    - debug:
        msg: "System {{ ec2.instances }}"

    - name: Add new instance to host group
      add_host:
        hostname: "{{ item.public_ip_address }}"
        groupname: launched
      with_items: "{{ ec2.instances }}"

    - name: Wait for SSH
      wait_for:
        host: "{{ item.public_ip_address }}"
        port: 22
        state: started
      with_items: "{{ ec2.instances }}"

- name: Configure instances
  hosts: launched
  tasks:
    - name: Download
      yum:
        name: git
        state: latest
      become: yes