Wednesday, 24 February 2016

Ansible playbook to start or stop AWS EC2 instances

How to start or stop ec2 instances with ansible

or

Ansible task to start and stop ec2 instances


Ansible supports modules to interact with AWS to manage the ec2 instances. In this post we are going to see the task/playbook that can stop and start the ec2 instances.

Note: if you don't have ansible installed, get it installed from here.

Note: You must set your AWS access key and secret key in your ~/.bashrc file as shown below


export AWS_ACCESS_KEY_ID='XXXXXXXXXXXX'
export AWS_SECRET_ACCESS_KEY='XXXXXXXXXXXXXXXXXXXXX'


Stop ec2 Instance

Now, let's see the playbook to stop the ec2 instance


---
- hosts: myserver
  remote_user: ubuntu
  tasks:
  - name: Gather facts
    action: ec2_facts

  - name: Stop myserver instance
    local_action:
        module: ec2
        region: "ap-southeast-1"
        instance_ids: "{{ansible_ec2_instance_id}}"
        state: stopped

Here the hosts 'myserver' should be defined in the hosts inventory file.
The ec2_facts gathers information about myserver like the instance_id
The module ec2 is used to stop the instance with state stopped.

Run the above playbook to stop the instance.


ansible-playbook -i hosts stop-myserver.yml -vvvv


Start ec2 instance

We can start the ec2 instance with ansible by the following playbook


---
- name: Start  instances
  hosts: localhost
  gather_facts: false
  connection: local
  vars:
    instance_ids:
      - 'i-XXXXXXXX'
    region: ap-southeast-1
  tasks:
    - name: Start the feature instances
      ec2:
        instance_ids: '{{ instance_ids }}'
        region: '{{ region }}'
        state: running
        wait: True

The instance_ids has to be specified to let the ansible know which all instances we want to start.
The region should be changed as per the region of the instance.

Now run the playbook as follows to start the instance.



ansible-playbook -i hosts start-myserver.yml -vvvv


1 comments:

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel