-1

I have below structure in inventory file

[master_server]
192.168.10.10
[backup_server]
192.168.10.11
192.168.10.12
192.168.10.13

I want to copy master.sh to 192.168.10.10 and backup.sh to all servers from backup_server group.

How do I achieve this in an Ansible playbook?

U880D
  • 8,601
  • 6
  • 24
  • 40
Ganesh Shinde
  • 65
  • 2
  • 7

3 Answers3

0

I understand that you like to execute a task for a server only if a server belongs to certain group of hosts in your inventory file.

How do I achieve this in Ansible playbook?

By using

In example like in

---
- hosts: test
  become: true
  gather_facts: true

  tasks:

  - name: Copy file to target group nodes
    copy:
      src: master.sh
      dest: "/home/{{ ansible_user }}"
    register: result
    when: "'master_server' in group_names

  - name: Show result
    debug:
      var: result

Similar Q&A

U880D
  • 8,601
  • 6
  • 24
  • 40
0

Another way is to name the files you want to copy by the name of the host group master_server.sh and backup_server.sh:

  - name: Copy file to target group nodes
    copy:
      src: "{{ group_names[0] }}.sh"
      dest: "/tmp/"

This will determine the group name of the host the task is running on and copies the equivalent file.

Khaled
  • 775
  • 1
  • 5
  • 19
0

Create the name of the file according to the name of the group. For example,

my_file: "{{ group_names.0.split('_')|first }}.sh"

This will work only if the first group of a host is either master_* or backup_*.


Example of a complete playbook for testing

- hosts: all
  gather_facts: false
  vars:
    my_file: "{{ group_names.0.split('_')|first }}.sh"
  tasks:
    - debug:
        msg: "Copy {{ my_file }} to {{ inventory_hostname }}"

gives (abridged)

  msg: Copy master.sh to 192.168.10.10
  msg: Copy backup.sh to 192.168.10.11
  msg: Copy backup.sh to 192.168.10.12
  msg: Copy backup.sh to 192.168.10.13
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63