Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start the stopped AWS instances using ansible playbook

I am trying to stop/start the particular group of instances listed in the hosts file under group [target]. following playbook works fine to stop the instances.

---
- hosts: target
  remote_user: ubuntu

  tasks:
  - name: Gather facts
    action: ec2_facts

  - name: Stop Instances
    local_action:
        module: ec2
        region: "{{region}}"
        instance_ids: "{{ansible_ec2_instance_id}}"
        state: stopped

But when I am trying to start these instances, it's not working as the ec2_facts is not able to ssh into the instances (since they are stopped now) and get the instance-ids

---
- hosts: target
  remote_user: ubuntu

  tasks:
  - name: start instances
    local_action:
        module: ec2
        region: "{{region}}"
        instance_ids: "{{ansible_ec2_instance_id}}"
        state: running

I have already seen the documentation which make use of dynamic inventory file for hosts and the way of hard-coding the instance-ids. I want to start the instances whose IPs are listed in the target group of hosts file.

like image 533
Ajeet Khan Avatar asked Dec 28 '15 14:12

Ajeet Khan


People also ask

How do I start a stopped instance?

To start the stopped instance, select the instance, and choose Instance state, Start instance. It can take a few minutes for the instance to enter the running state.

How do you launch an EC2 instance after it is terminated?

Launch a replacement EC2 instance using Amazon EBS snapshots or Amazon Machine Images (AMI) backups that were created from the terminated Amazon EC2 instance. Attach an EBS volume from the terminated instance to another EC2 instance. You can then access the data contained in those volumes.


2 Answers

Got the solution, Following is the ansible-task that worked for me.

---
- 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

Here is the Blog post on How to start/stop ec2 instances with ansible

like image 195
Ajeet Khan Avatar answered Sep 28 '22 20:09

Ajeet Khan


You have 2 options:

Option 1

Use AWS CLI to query the instance-id of a stopped instance using its IP or name. For example, to query the instance id for a given instance name:

shell: aws ec2 describe-instances --filters 'Name=tag:Name,Values={{inst_name}}' --output text --query 'Reservations[*].Instances[*].InstanceId'
register: inst_id

Option 2

Upgrade Ansible to version 2.0 (Over the Hills and Far Away) and use the new ec2_remote_facts module

- ec2_remote_facts:
    filters:
      instance-state-name: stopped
like image 23
helloV Avatar answered Sep 28 '22 20:09

helloV