---
# tasks file for start-ec2

- block:

  - name: Wait for instance to complete stopping
    shell: "aws --region {{ec2_region}} ec2 describe-instances --instance-ids {{ec2_id}} --query \"Reservations[].Instances[0].State.Name | [0]\" --output text"
    register: current_state
    until: current_state.stdout.find("stopped") != -1
    retries: 30
    delay: 10
    when: ec2_state == "stopping"
    delegate_to: localhost

  - name: Start EC2 Instance
    ec2_instance:
      instance_ids: ["{{ ec2_id }}"]
      region: "{{ ec2_region }}"
      state: running
      wait: True
    register: result
    until: result.instances[0].state != "running"
    retries: 60
    delay: 5
    delegate_to: localhost

  - name: Wait for SSH to become available
    wait_for:
      port: 22
      host: "{{ ec2_private_ip_address }}"
    connection: local

  when: ec2_id is defined and (ec2_state == "stopped" or ec2_state == "stopping")
