---
- name: apt | Add mongodb key
  become: yes
  apt_key:
    # Don't use mongodb.org key location due to SNI verification problems under Ubuntu Trusty
    keyserver: "hkp://keyserver.ubuntu.com:80"
    id: "{{ mongodb_apt_keys[mongodb_major_minor_version] }}"
    state: present
  register: _task
  retries: 5
  delay: 3
  until: _task is succeeded
  tags: [databases, mongodb]

- name: apt | Add mongodb repository
  become: yes
  apt_repository:
    repo: 'deb http://repo.mongodb.org/apt/{{ ansible_facts.distribution|lower }} {{ ansible_facts.distribution_release|lower }}/mongodb-org/{{ mongodb_major_minor_version }} multiverse'
    state: present
  tags: [databases, mongodb]

- name: apt | Install mongodb
  become: yes
  apt:
    name:
      # re-installing different version of 'mongodb-org' meta package doesn't automatically
      # upgrade or downgrade its dependencies. So we need to explicitly list them one-by-one.
      - mongodb-org={{ mongodb_version }}*
      - mongodb-org-shell={{ mongodb_version }}*
      - mongodb-org-server={{ mongodb_version }}*
      - mongodb-org-mongos={{ mongodb_version }}*
      - mongodb-org-tools={{ mongodb_version }}*
    state: present
  register: _task
  retries: 5
  delay: 3
  until: _task is succeeded
  notify: restart mongodb
  tags: [databases, mongodb]

---
- name: apt | Install gpg
  become: true
  ansible.builtin.apt:
    state: present
    update_cache: true
    name: gpg

- name: apt | Add mongodb key
  become: yes
  apt_key:
    # Don't use mongodb.org key location due to SNI verification problems under Ubuntu Trusty
    keyserver: "hkp://keyserver.ubuntu.com:80"
    id: "{{ mongodb_apt_keys[mongodb_major_minor_version] }}"
    state: present
  register: _task
  retries: 5
  delay: 3
  until: _task is succeeded
  tags: [databases, mongodb]

- name: apt | Add mongodb repository
  become: yes
  apt_repository:
    repo: 'deb http://repo.mongodb.org/apt/{{ ansible_facts.distribution|lower }} {{ ansible_facts.distribution_release|lower }}/mongodb-org/{{ mongodb_major_minor_version }} multiverse'
    state: present
  tags: [databases, mongodb]

- name: apt | Install mongodb
  become: yes
  apt:
    name:
      # re-installing different version of 'mongodb-org' meta package doesn't automatically
      # upgrade or downgrade its dependencies. So we need to explicitly list them one-by-one.
      - mongodb-org={{ mongodb_version }}*
      - mongodb-org-shell={{ mongodb_version }}*
      - mongodb-org-server={{ mongodb_version }}*
      - mongodb-org-mongos={{ mongodb_version }}*
      - mongodb-org-tools={{ mongodb_version }}*
    state: present
  register: _task
  retries: 5
  delay: 3
  until: _task is succeeded
  notify: restart mongodb
  tags: [databases, mongodb]

Install gpg before calling apt_key
Install gpg before calling apt_key
