- name: Download heptio-authenticator-aws
  get_url:
    dest: /usr/local/bin/heptio-authenticator-aws
    checksum: sha256:246f6d13b051bbfb12962edca074c8f67436930e84b2bec3a45a5d9242dc6f0c
    mode: 0755
    url: https://amazon-eks.s3-us-west-2.amazonaws.com/1.10.3/2018-06-05/bin/linux/amd64/heptio-authenticator-aws

- name: Install packages
  package:
    name: "{{ item }}"
    state: present
  with_items:
    - haproxy
    - iproute2

- name: Write haproxy config
  template:
    dest: /etc/haproxy.conf
    src: haproxy.conf.j2
  notify:
    - Restart haproxy

- name: Write haproxy systemd unit
  copy:
    dest: /etc/systemd/system/haproxy.service
    content: |
      [Install]
      WantedBy=multi-user.target
      [Unit]
      After=network-online.target
      Wants=network-online.target
      [Service]
      Type=simple
      ExecStart=/usr/sbin/haproxy -f /etc/haproxy.conf -db
      RestartSec=5
      Restart=always

- name: Start haproxy
  systemd:
    name: haproxy
    daemon_reload: yes
    enabled: yes
    state: started
  become: yes

- name: Configure eth1
  blockinfile:
    dest: /etc/network/interfaces.d/50-cloud-init.cfg
    block: |
      auto eth1
      iface eth1 inet dhcp
  notify:
    - Restart networking

- name: force all notified handlers to run. We need eth1 to be ready.
  meta: flush_handlers

- name: Gather eth1 address
  command: ip -4 -oneline addr show eth1
  # example output:
  #   3: eth1    inet 10.3.19.198/28 brd 10.3.19.207 scope global eth1\       valid_lft forever preferred_lft forever
  register: eth1_addr_cmd
  changed_when: false
  tags:
    - eth1

- name: Set fact
  set_fact:
    eth1_addr: "{{ eth1_addr_cmd['stdout_lines'][0] | regex_replace('.*inet (\\d+[.]\\d+[.]\\d+[.]\\d+/\\d+) .*', '\\1') | ipaddr}}"

- name: Set fact
  set_fact:
    eth1_gateway: "{{ eth1_addr | ipaddr('1') | ipaddr('address') }}"

- name: Gather route table info
  command: ip route
  register: ip_route
  changed_when: false

- name: Add route to DC nodes via eth1
  command: ip route add "{{ peer }}/32" via "{{ eth1_gateway }}" dev eth1
  when: ip_route['stdout_lines'] | select('match', peer + ' via ' + eth1_gateway + ' .*') | list | length == 0
