ansible over docker hosts does not as expected

Viewed 91

I'm facing a bit weird issue targeting in ansible docker containers. Inventory

el7_02 ansible_port=6000 ansible_user=user ansible_host=localhost
el7_03 ansible_port=6001 ansible_user=user ansible_host=localhost 

playbook

- shell: hostname
  register: x

- debug: msg="{{ x.stdout}}, {{ansible_hostname}}, {{ansible_user}},  {{ansible_port}}"

output

TASK [Gathering Facts] *************************************************************************************************
ok: [el7_03]
ok: [el7_02]

TASK [x : shell] *************************************************************************************************
changed: [el7_03]
changed: [el7_02]

TASK [x : debug] *************************************************************************************************
ok: [el7_03] => {
    "msg": "el7_02, el7_02, user,  6001"
}
ok: [el7_02] => {
    "msg": "el7_02, el7_02, user,  6000"
}

as you can see for some reasons I see not expected hostname for the container el7_03. While I'd expect to see in a debug tasks for the docker el7_03 the same hostname (i.e. el7_03 but not el7_02). Why I receive "the wrong" output?

checking hostnames in docker

~/ $ ssh -p 6000 user@localhost 'hostname'
el7_02
~/ $ ssh -p 6001 user@localhost 'hostname'
el7_03

if I will switch to ansible_connection=docker then I get what I expect. however, I cannot use it because when I interact with anything located outside of my laptop (installing anything or downloading from the internet) time to time (and quite often) I receive timeouts. Maybe there is a way how to get rid of timeouts?

os: macos ansible: 2.9.11 python: 3.8.5 docker: 19.0.3.8

thank you

1 Answers

you need to work around the issue that ansible looks up a host via hostname and not via hostname:port pair .

my workaround for this issue is as follows:

$ grep pi. /etc/hosts
127.0.0.1 pi1
127.0.0.1 pi2
127.0.0.1 pi3

# inventory contents:
$ cat all_rpis.ini 
pi1:3321
pi2:3322
pi3:3323
Related