How can I run my ansible playbook outside of a container and have the taks executed inside the container?

    $ cat Dockerfile 
    FROM postgis/postgis
    
    $ cat docker-compose.yml 
    services:
      postgisql:
        build:
          context: .
    
    $ docker-compose up
    [...]
    
    $ docker-compose ps
                Name                           Command              State    Ports             
    ---------------------------------------------------------------------------------
    postgis_container_postgisql_1   docker-entrypoint.sh postgres   Up       5432/tcp
    
    $ cat inventory/hosts 
    container ansible_host=postgis_container_postgisql_1 ansible_connection=docker

Do a quick check:

    $ ansible container -a "hostname"
    container | CHANGED | rc=0 >>
    18cf7f56cf83

Good, seems to be the same as when we access the container via docker-compose:

    $ docker-compose exec postgisql hostname
    18cf7f56cf83

Now let’s make a quick playbook for that just to show that it indeed works:

    $ cat show_hostname.yml 
    - hosts: container
      tasks:
        - name: get hostname of running container
          shell: hostname
          register: hostname
    
        - name: display the hostname that the container returnet to us in the previous task
          debug: msg="the hostname of that container is {{ hostname.stdout }}"
    
    $ ansible-playbook show_hostname.yml
    
    PLAY [container] ***********************************************************************
    
    TASK [Gathering Facts] *****************************************************************
    ok: [container]
    
    TASK [get hostname of running container] ***********************************************
    changed: [container]
    
    TASK [display the hostname that the container returnet to us in the previous task] *****
    ok: [container] => {
        "msg": "the hostname of that container is 18cf7f56cf83"
    }
    
    PLAY RECAP *****************************************************************************
    container : ok=3  changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0   

Voilà.