Ansible: delegate_to and variables

One nice feature of Ansible is its ability to “delegate” tasks to the control machine, or any other host that the control machine can SSH to.

The official documentation for the usage of delegate_to is here

Waiting for a server to restart using delegate_to

I was playing around with a task that could delegate a VM to attempt to test port 22 on a VM that isn’t connected directly to the internet, and I couldn’t figure out why this didn’t work;


- name: Wait for the server to come back
  wait_for:
    host: "{{ inventory_hostname }}"
    port: 22 
    state: started
  sudo: false
  delegate_to: "{{ ssh_delegate }}"
  

but this worked as expected;


- name: Wait for the server to come back
  wait_for:
    host: "{{ inventory_hostname }}"
    port: 22 
    state: started
  sudo: false
  delegate_to: 10.128.0.100
  

This was quite irritating, as I wanted to be able to define the hostname in a variable taken from Terraform

The Fix

For some reason, putting the delegate_to hostname in a with_items loop works without any issues.


- name: Wait for the server to come back
  wait_for:
    host: "{{ inventory_hostname }}"
    port: 22 
    state: started
  sudo: false
  delegate_to: "{{ item }}"
  with_items:
    - "{{ ssh_delegate }}"
  

I have raised a github issue for this.

comments powered by Disqus