0

I have four different hosts. host1, host2, host3, host4

I am trying to update following files on the these hosts.

host1
/var/www/foo1

host2
/var/www/foo1
/var/tmp/foo1

host3
/var/www/foo1

host4
/var/tmp/foo1

I am able to write two different playbook with different inventory files and group vars to achieve this task.

Inventory file 1

[group_foo1]
host1
host2
host3

Group variable

File name: group_foo1

path:/var/www

Inventory file 2

[group_foo2]
host2
host4

Group variable

File name: group_foo2

path:/var/tmp

Task

name: copy the file
copy: src=foo1 dest={{path}}

I want to do this task using single playbook.

How it can be done?

1

2 Answers 2

2

You should use synchronize module:

# Synchronize two directories on one remote host.
synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
delegate_to: "{{ inventory_hostname }}"

ALso you can try to iterate in a tasks over all hosts:

with_items: groups['all']
Sign up to request clarification or add additional context in comments.

Comments

0

You can put this in a single playbook and target the tasks to different hosts in one of the following ways:

1. Define groups in your Ansible inventory file and delegate tasks to specific hosts:

Put your hosts in groups, e.g.:

[www_hosts]
host1
host2
host3

[tmp_hosts]
host2
host4

And setup your playbook to delegate tasks to these groups like this:

- name: Copy the file to www_path
  ansible.builtin.copy:
    src: "foo1"
    dest: "/var/www"
  run_once: true
  delegate_to: "{{ item }}"
  loop: "{{ groups['www_hosts'] }}"

- name: Copy the file to tmp_path
  ansible.builtin.copy:
    src: "foo1"
    dest: "/var/tmp"
  run_once: true
  delegate_to: "{{ item }}"
  loop: "{{ groups['tmp_hosts'] }}"

Don't forget to set the run_once to true otherwise the same tasks will run (and be delegated to each host) on each host you target the playbook.

2. Setup variables as a condition to run tasks on specific hosts:

If you don't want your playbook to be dependent on a specific inventory setup you can also set it up in a variables file or section and run tasks selectively. E.g.:

Set up a vars/main.yml file (or vars-section) with:

www_hosts:
 - host1
 - host2
 - host3

tmp_hosts:
 - host2
 - host4

Make sure these vars gets loaded into your playbook/role and setup playbook tasks like this:

- name: Copy the file to www_path
  ansible.builtin.copy:
    src: "foo1"
    dest: "/var/www"
  when: ansible_fqdn in www_hosts

- name: Copy the file to tmp_path
  ansible.builtin.copy:
    src: "foo1"
    dest: "/var/tmp"
  when: ansible_fqdn in tmp_hosts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.