pytest-testinfra icon indicating copy to clipboard operation
pytest-testinfra copied to clipboard

ansible_host set to another variable fails

Open divansantana opened this issue 4 years ago • 4 comments

Trying to use ansible connection backend, it seems to fail when ansible_host variable is set to another variable, like so inventories/host_vars/my_host.yml

---
network_interfaces:
  - name: ens3
    address: 10.254.14.18
    netmask: 255.255.255.0
    gateway: 10.254.14.1

ansible_host: "{{ network_interfaces[0]['address'] }}"

when running testinfra this results in:

E           RuntimeError: CommandResult(command=b"sudo /bin/sh -c 'getent ahosts mail.example.com'", exit_status=255, stdout=None, stderr=b"ssh: Could not resolve hostname {{ network_interfaces[0]['address'] }}: Name or service not known\r\n")

A workaround is changing the host inventory file like so, but this is not ideal:

---
network_interfaces:
  - name: ens3
    address: 10.254.14.18
    netmask: 255.255.255.0
    gateway: 10.254.14.1

ansible_host: 10.254.14.18 

Is this a limitation in testinfra, or am I doing something wrong?

versions using:

Python 3.8.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
plugins: testinfra-6.4.0
ansible == 4.1.0

divansantana avatar Jul 26 '21 10:07 divansantana

Im digging into this to see if testinfra would work for our setup.

current issue is that testinfra gets its data from the ansible-inventory -i % --list command which doesn't automatically resolve variables like this.

https://github.com/pytest-dev/pytest-testinfra/blob/master/testinfra/utils/ansible_runner.py#L50

image

joshzcold avatar Nov 01 '22 22:11 joshzcold

Something like this could probably make those resolve ANSIBLE_VERBOSITY=0 ansible localhost -i inventory -m debug -a 'msg={{ hostvars }}'

joshzcold avatar Nov 01 '22 22:11 joshzcold

@divansantana I just got over this problem by creating a wrapper script around py.test and invoking the ansible api to return the results of set_fact

https://gist.github.com/joshzcold/d99993400ae0cce77041a74f5a06e081

Im sure this could get baked into testinfra

allows you to do something like -i inventory -i inventory2 and still have your ansible_host: {{ varablized_ip}} passed down to py.test correctly.

joshzcold avatar Nov 03 '22 20:11 joshzcold

@joshzcold nice debug and solution.

divansantana avatar Nov 11 '22 13:11 divansantana