Copy specific file to specific server using Ansible

I have 2 Files. File A and File B. Now after I create 2 Servers, I want to push File A to server1 only and File B to server2 only.

The solution I have below works well for 2 files. But its not very efficient when I have to scale out this model to more than 10 servers.

    - name: Copy file with owner and permissions
      copy:
        src: /srv/myfiles/serverA.file
        dest: /my/destination
      when: "serverA" in inventory_hostname

Can somebody point on how to accomplish below scenario more effectively using Ansible
File A to server A File B to server B File C to server C File Z to server Z.

1 answer

  • answered 2020-11-25 02:43 antogx

    If your server names host1, host2, host3
    
    In Control node your files are in /tmp
    host1.txt
    host2.txt
    host3.txt
    
    The playbook to copy the files to respective host's /tmp/ :
    
    - hosts: all
      gather_facts: no
      tasks:
      - copy:
          src: "/tmp/{{ item }}"
          dest: /tmp/
        with_lines: ls /tmp
        when: inventory_hostname in item
    
    Depending on the hostname and file name change the logic if required.