By default Ubuntu/Debian docker images do not include python as part of the distribution. Before running Ansible tasks against containers, including fact gathering, python must be installed.

The value of ansible_os_family can not be used because it’s not available until after facts have been gathered.

- hosts: docker-containers
  gather_facts: False
  pre_tasks:
    - name: Check for apt (Debian family)
      raw: "test -e /usr/bin/apt"
      register: apt_installed
      ignore_errors: true
    - name: Install python for Ansible
      raw: "[ -e /usr/bin/python ] || (apt -y update && apt install -y python-minimal)"
      register: output
      when: apt_installed and apt_installed.rc == 0
      changed_when: output.stdout != ""

Answering a couple questions that the above might cause:

Q: Why not use the Ansible stat module to test if /usr/bin/apt is installed? A: It uses python.

Q: Why are errors ignored? A: A test failure is an error, and Ansible will stop processing if /usr/bin/apt doesn’t exist.