# Launches an ec2 instance and blocks until the instance is up
# adds it to the host group
# Will terminate an instance if one and only one already exists
# with the same name

- name: lookup tags for terminating existing instance
  local_action:
    module: ec2_lookup
    region: "{{ region }}"
    tags:
      Name: "{{ name_tag }}"
  register: tag_lookup
  when: terminate_instance == true

- name: checking for other instances
  debug: msg="Too many results returned, not terminating!"
  when: terminate_instance == true and tag_lookup.instance_ids|length > 1

- name: terminating single instance
  local_action:
    module: ec2_2_1_1_0
    state: 'absent'
    region: "{{ region }}"
    instance_ids: "{{tag_lookup.instance_ids}}"
  when: terminate_instance == true and tag_lookup.instance_ids|length == 1

- name: deregister instance from an an elb if it was in one
  local_action:
    module: ec2_elb
    region: "{{ region }}"
    instance_id: "{{ tag_lookup.instance_ids[0] }}"
    ec2_elbs:
      - "{{ elb }}"
    state: absent
  when: terminate_instance == true and elb and tag_lookup.instance_ids|length == 1

- name: Launch ec2 instance
  local_action:
    module: ec2_2_1_1_0
    keypair: "{{ keypair }}"
    group: "{{ security_group }}"
    instance_type: "{{ instance_type }}"
    image: "{{ ami }}"
    vpc_subnet_id: "{{ vpc_subnet_id }}"
    assign_public_ip: yes
    wait: true
    region: "{{ region }}"
    instance_tags: "{{ instance_tags }}"
    volumes:
      - device_name: /dev/sda1
        volume_size: "{{ root_ebs_size }}"
        delete_on_termination: true
    zone: "{{ zone }}"
    instance_profile_name: "{{ instance_profile_name }}"
    user_data: "{{ user_data }}"
  register: ec2

- name: Add DNS name
  local_action:
    module: route53_2_1_1_0
    overwrite: yes
    command: create
    zone: "{{ dns_zone }}"
    type: CNAME
    ttl: 300
    record: "{{ dns_name }}.{{ dns_zone }}"
    value: "{{ item.public_dns_name }}"
  with_items: "{{ ec2.instances }}"

- name: Add DNS names for services
  local_action:
    module: route53_2_1_1_0
    overwrite: yes
    command: create
    zone: "{{ dns_zone }}"
    type: CNAME
    ttl: 300
    record: "{{ item[1] }}-{{ dns_name }}.{{ dns_zone }}"
    value: "{{ item[0].public_dns_name }}"
  with_nested:
    - "{{ ec2.instances }}"
    - ['studio', 'ecommerce', 'preview', 'programs', 'discovery', 'credentials']

- name: Add new instance to host group
  local_action:
    module: add_host
    hostname: "{{ item.public_ip }}"
    groups: launched
  with_items: "{{ ec2.instances }}"

- name: Wait for SSH to come up
  local_action:
    module: wait_for
    host: "{{ item.public_dns_name }}"
    search_regex: OpenSSH
    port: 22
    delay: 10
  with_items: "{{ ec2.instances }}"

- name: Wait for python to install
  pause:
    minutes: "{{ launch_ec2_wait_time }}"