Run tasks on different hosts within an imported task

Viewed 522

The calling playbook has:

- hosts: ssh_servers
  tasks:
  - import_tasks: create_files.yml

Then, in create_files.yml, I'd like to run some tasks on hosts other than ssh_servers, such as:

- Hosts: other_servers
  tasks:
  - file:

I get: ERROR! conflicting action statements: hosts, tasks .

Is this because I'm trying to run against hosts that were never included in the calling task ? Is there a way to accomplish this other than in the calling playbook have:

- hosts: 
   - ssh_servers
   - other_servers
  tasks:
  - import_tasks: create_files.yml

Thank you.

1 Answers

Is this because I'm trying to run against hosts that were never included in the calling task ? Is there a way to accomplish this other than in the calling playbook

I believe the answer is yes, although it'll be weird and could cause subsequent folks who interact with your playbook some confusion

given a hypothetical create_files.yml of:

- name: create /tmp/hello_world on hosts "not_known_at_launch_time"
  file:
    path: /tmp/hello_world
    state: present
  delegate_to: '{{ item }}'
  with_items: '{{ groups["not_known_at_launch_time"] }}'

then the glue needed to bridge them together is the dynamic creation of a group and that delegate_to: keyword

- hosts: ssh_hosts
  tasks:
  - add_host:
      groups: not_known_at_launch_time
      name: secret-host-0
      ansible_host: 192.168.1.1  # or whatever
      # ... other hostvars here ...
  - include_tasks: create_files.yml

it may be possible to combine those inside create_files.yml, via some shared vars: that say which host-and-ip should be added to the magic group name, which also has the benefit of keeping the magic group name localized to the file that consumes it.

BE AWARE, I did actually test this, but not extensively, so there may be some weird things such as the need to run_once: yes on them to keep the tasks from being run groups.ssh_hosts|length times or similar stuff

As Vladimir correctly pointed out, what you actually want to happen is to make that relationship formal:

- hosts: ssh_hosts
  tasks:
  ... whatever tasks you had before
  - add_host: ... as before ...

- hosts: anonymous_group_name_goes_here
  tasks:
  - include_tasks: create_files.yml

- hosts: ssh_hosts
  tasks:
  - debug:
      msg: and now you are back to the ssh_hosts to pick up what they were supposed to be doing when you stopped to post on SO
Related