---
-
  name: Ensure dependencies are present.
  ansible.builtin.apt:
    name:
      - apt-transport-https
      - python3-debian
      - gnupg2
    state: present

-
  name: Download NodeSource's signing key.
  # NodeSource's web server discriminates the User-Agent used by the deb822_repository module.
  # https://github.com/nodesource/distributions/issues/1723
  ansible.builtin.get_url:
    url: https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key
    dest: /etc/apt/signing-key-nodesource-repo.asc
    owner: root
    group: root
    mode: '0444'
  register: node_signing_key

-
  name: Add NodeSource repositories for Node.js.
  ansible.builtin.deb822_repository:
    name: nodesource_{{ nodejs_version }}
    uris: "https://deb.nodesource.com/node_{{ nodejs_version }}"
    types: deb
    suites: nodistro
    components: main
    signed_by: "{{ node_signing_key.dest }}"
    state: present
  register: node_repo

-
  name: Update apt cache if repo was added.
  ansible.builtin.apt:
    update_cache: true
    cache_valid_time: 600
  when: node_repo is changed
  tags: ['skip_ansible_lint']

-
  name: Ensure Node.js and npm are installed.
  ansible.builtin.apt:
    name: "nodejs={{ nodejs_version | regex_replace('x', '') }}*"
    state: present
