---
- name: fetch the default subnet id
  ec2_remote_facts:
    region: "{{ r_openshift_aws_elb_region }}"
    filters: "{{ r_openshift_aws_elb_instance_filter }}"
  register: instancesout

- name: fetch the default subnet id
  ec2_vpc_subnet_facts:
    region: "{{ r_openshift_aws_elb_region }}"
    filters:
      "tag:Name": "{{ r_openshift_aws_elb_subnet_name }}"
  register: subnetout

- name:
  debug:
    msg: "{{ r_openshift_aws_elb_listeners[r_openshift_aws_elb_type][r_openshift_aws_elb_direction]
                   if 'master' in r_openshift_aws_elb_type  or 'infra' in r_openshift_aws_elb_type
                   else r_openshift_aws_elb_listeners }}"

- name: "Create ELB {{ r_openshift_aws_elb_name }}"
  ec2_elb_lb:
    name: "{{ r_openshift_aws_elb_name }}"
    state: present
    security_group_names: "{{ r_openshift_aws_elb_security_groups }}"
    idle_timeout: "{{ r_openshift_aws_elb_idle_timout }}"
    region: "{{ r_openshift_aws_elb_region }}"
    subnets:
    - "{{ subnetout.subnets[0].id }}"
    health_check: "{{ r_openshift_aws_elb_health_check }}"
    listeners: "{{ r_openshift_aws_elb_listeners[r_openshift_aws_elb_type][r_openshift_aws_elb_direction]
                   if 'master' in r_openshift_aws_elb_type  or 'infra' in r_openshift_aws_elb_type
                   else r_openshift_aws_elb_listeners }}"
    scheme: "{{ r_openshift_aws_elb_scheme }}"
    tags:
      KubernetesCluster: "{{ r_openshift_aws_elb_clusterid }}"
  register: new_elb

# It is necessary to ignore_errors here because the instances are not in 'ready'
#  state when first added to ELB
- name: "Add instances to ELB {{ r_openshift_aws_elb_name }}"
  ec2_elb:
    instance_id: "{{ item.id }}"
    ec2_elbs: "{{ r_openshift_aws_elb_name }}"
    state: present
    region: "{{ r_openshift_aws_elb_region }}"
    wait: False
  with_items: "{{ instancesout.instances }}"
  ignore_errors: True
  retries: 10
  register: elb_call
  until: elb_call|succeeded

- debug:
    msg: "{{ item }}"
  with_items:
  - "{{ new_elb }}"
