Search code examples
ansibleansible-inventory

Ansible: delegate_to group not working correctly


In my dockerized Ansible 2.8 I'm trying to change ssh settings on remote hosts that have been added to inventory dynamically using add_host

playbook.yml

# configure new VMs
- name: Configure new Azure VM
  hosts: localhost
  connection: local
  gather_facts: no
  roles:
    - az-vm-configure
  tags:
    - az-vm-configure

main.yml

- name: Configure inventory
  include: inventory.yml

- name: Configure sshd
  include: sshd.yml
  delegate_to: '{{ groups.new[0] }}'

It works fine when I use following construction: delegate_to: '{{ groups.new[0] }}' But when I'm trying to implement that for all hosts in group like this:

delegate_to: '{{ item }}'
with_items: "{{ groups['new'] }}"

my task ignores construction above and tries to execute task on localhost: task execution result

Seems like delegate_to: '{{ item }}' doesn't work in this case. Could somebody suggest any workaround?


Solution

  • When I tried to place hosts in the main.yml as mentioned above I gave an error ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path. Anyway here's my solution:

    playbook.yml

    # configure VM
    - name: Add new VM to inventory
      hosts: localhost
      connection: local
      gather_facts: no
      tasks:
        - include_role:
            name: az-vm-configure
            tasks_from: inventory.yml
      tags:
        - az-vm-configure
    
    - name: Configure new Azure VM
      hosts: new
      gather_facts: no
      tasks:
        - include_role:
            name: az-vm-configure
            tasks_from: sshd.yml
      tags:
        - az-vm-configure
    

    roles/az-vm-configure/tasks/main.yml

    - include_tasks: '{{ tasks }}'
      with_items:
        - inventory.yml
        - sshd.yml
      loop_control:
        loop_var: tasks