- name: Create ec2 instance
  hosts: localhost
  connection: local
  gather_facts: True
  vars:
    keypair: continuous-integration
    instance_type: t2.medium
    security_group: sandbox-vpc
    # ubuntu 16.04 - 20170721
    ami: ami-cd0f5cb6
    region: us-east-1
    zone: us-east-1c
    instance_tags:
      environment: sandbox
      github_username: temp
      Name: sandbox-temp
      source: provisioning-script
      owner: temp
    root_ebs_size: 50
    dns_name: temp
    instance_initiated_shutdown_behavior: stop
    dns_zone: sandbox.edx.org
    name_tag: sandbox-temp
    elb: false
    ec2_vpc_subnet_id: subnet-cd867aba
    instance_userdata: |
      #!/bin/bash
      set -x
      set -e
      export RUN_ANSIBLE=false;
      wget https://raw.githubusercontent.com/edx/configuration/{{ configuration_version }}/util/install/ansible-bootstrap.sh -O - | bash;
    launch_wait_time: 5
  roles:
    - role: launch_ec2
      keypair: "{{ keypair }}"
      instance_type: "{{ instance_type }}"
      instance_initiated_shutdown_behavior: "{{ instance_initiated_shutdown_behavior }}"
      security_group: "{{ security_group }}"
      ami: "{{ ami }}"
      region: "{{ region }}"
      instance_tags: "{{ instance_tags }}"
      root_ebs_size: "{{ root_ebs_size }}"
      dns_name: "{{ dns_name }}"
      dns_zone: "{{ dns_zone }}"
      zone: "{{ zone }}"
      vpc_subnet_id: "{{ ec2_vpc_subnet_id }}"
      assign_public_ip: yes
      terminate_instance: true
      instance_profile_name: sandbox
      user_data: "{{ instance_userdata }}"
      launch_ec2_wait_time: "{{ launch_wait_time }}"

- name: Configure instance(s)
  hosts: launched
  become: True
  gather_facts: False
  vars:
    elb: False
  pre_tasks:
    - name: Wait for cloud-init to finish
      wait_for:
        path: /var/log/cloud-init.log
        timeout: 15
        search_regex: "final-message"
    - name: gather_facts
      setup: ""
  vars_files:
    - roles/edxapp/defaults/main.yml
    - roles/xqueue/defaults/main.yml
    - roles/xserver/defaults/main.yml
    - roles/forum/defaults/main.yml
  roles:
    # rerun common to set the hostname, nginx to set basic auth
    - common
    - aws
    - edx-sandbox
    - role: nginx
      nginx_sites:
      - cms
      - lms
      - xqueue
      - xserver
      - forum
      nginx_default_sites:
      - lms
  post_tasks:
    - name: get instance id for elb registration
      local_action:
        module: ec2_lookup
        region: us-east-1
        tags:
          - Name: "{{ name_tag }}"
      register: ec2_info
      when: elb
      become: False
    - name: register instance into an elb if one was provided
      local_action:
        module: ec2_elb
        region: "{{ region }}"
        instance_id: "{{ ec2_info.instance_ids[0] }}"
        state: present
        ec2_elbs:
          - "{{ elb }}"
      when: elb
      become: False