# Tasks für nginx-https-proxy
---
### Install required packages
#
# At this point, we also check that apt is available,
# which is assumed for all future operations.
- name: Install nginx prerequisites
  ansible.builtin.apt:
    state: present
    name:
    - apt-transport-https
    - ca-certificates
    - gnupg2

### Setup APT cache for the nginx repository
#
# We need the nginx repository to get the ngx_stream_core_module
# for SSL passthrough.

- name: Add nginx apt-key
  apt_key:
    url: https://nginx.org/keys/nginx_signing.key
    state: present

- name: Add nginx's APT repository
  ansible.builtin.template:
    src: templates/nginx.list.j2
    dest: /etc/apt/sources.list.d/nginx.list
  register: apt_repo

- name: Set nginx APT preference
  ansible.builtin.copy:
    src: files/apt-preference-99nginx
    dest: /etc/apt/preferences.d/99nginx

- name: Update package cache # noqa 503
  ansible.builtin.apt:
    update_cache: true
  when: apt_repo.changed

### Install nginx

- name: Install nginx
  ansible.builtin.apt:
    state: present
    name:
    # This version of nginx comes with the ngx_stream_core_module module
    - nginx


### Configuration
- name: Setup passthrough matrix
  ansible.builtin.template:
    src: templates/passthrough.conf.j2
    dest: /etc/nginx/passthrough.conf
    owner: root
    group: root
    mode: '0644'
  notify: restart nginx

- name: Create directory for dehydrated forwardings
  ansible.builtin.file:
    path: /etc/nginx/dehydrated-hosts
    state: directory
    owner: root
    group: root
    mode: '0755'

- name: Setup dehydrated forwardings
  ansible.builtin.template:
    src: templates/dehydrated-host.conf.j2
    dest: "/etc/nginx/dehydrated-hosts/{{ item.server }}.conf"
    owner: root
    group: root
    mode: '0644'
  loop: "{{ ingress }}"
  notify: restart nginx

- name: Setup nginx configuration
  # Note the order here: The nginx configuration _needs_ he dehydrated-hosts
  # directory and the passthrough.conf file, so we do them first to ensure
  # a valid configuration in case the playbook is cancelled mid-way.
  ansible.builtin.copy:
    src: files/nginx.conf
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: '0644'
  notify: restart nginx