Search code examples
amazon-web-servicesamazon-ec2ansibleansible-inventory

How to run a role in EC2 instance using dynamic inventory in ansible?


I have created an ec2 instance and now when I am trying to call a role in ansible under that playbook , the roles runs in my local machine inspite of the ec2 instance .

- name: Provision an EC2 Instance
  hosts: localhost
  connection: local
  gather_facts: False
  tags: provisioning
  vars:
    secret_key: "{{ secret_key }}"
    access_key: "{{ access_key }}"
    region: us-east-1

- hosts: localhost
  roles:
     - sdirect

I have used dynamic inventories. Can anyone please help or suggest something. Thanks.


Solution

  • Here is simple example that I am using to create an ec2 instance and then run my role on it using ec2.py dynamic inventory:

    - name: Provision an EC2 Instance
      hosts: localhost
      gather_facts: False
      tags: provisioning
      vars:
        secret_key: "{{ secret_key }}"
        access_key: "{{ access_key }}"
        region: us-east-1
      tasks:
         - role: create-ec2-role
         - name: Refresh the ec2.py cache
           shell: ./inventory/ec2.py --refresh-cache # location of your ec2.py inventory
           changed_when: no
    
         - name: Refresh inventory
           meta: refresh_inventory
    
    # Let suppose you have assign the Name "my_instance" to your Instance
    - name: Run tasks on new ec2 instance
      hosts: tag_Name_my_instance
      # I assume that you have created the ubuntu ec2 instance and ssh key is in your ssh agent
      remote_user: ubuntu
      roles:
        - myrole
    

    I assue that you have a directory name inventory in the same directory where you have playbook with the following files:

    .
    |-- ec2.ini
    |-- ec2.py
    `-- hosts
    

    The content of the hosts file is simple:

    [localhost]
    127.0.0.1
    

    To run the playbook, just use this command:

    ansible-playbook -i inventory/hosts yourplaybook.yml
    

    Hope that might help you