How to overwrite file in Ansible

Viewed 29788

I want to ovrwrite file on remote location using Ansible. No matter content in zip file is changes or not, everytime I run playbook file needs to be overwrite on destination server.

Below is my playbook

- hosts: localhost
  tasks:
  - name: Checking if File is exsists to copy to update servers.
    stat:
      path: "/var/lib/abc.zip"
      get_checksum: False
      get_md5: False
    register: win_stat_result

  - debug:
      var: win_stat_result.stat.exists


- hosts: uploads
  tasks:
    - name: Getting VARs
      debug:
        var: hostvars['localhost']['win_stat_result']['stat']  ['exists']

    - name: copy Files to Destination Servers
      win_copy:
        src: "/var/lib/abc.zip"
        dest: E:\xyz\data\charts.zip
        force: yes
      when: hostvars['localhost']['win_stat_result']['stat']['exists']

When I run this playbook it didn't overwrite file on destination as file is already exists. I used force=yes but it didn't worked.

2 Answers

Try the Ansible copy module.

The copy module defaults to overwriting an existing file that is set to the dest parameter (i.e. force defaults to yes). The source file can either come from the remote server you're connected to or the local machine your playbook runs from. Here's a code snippet:

- name: Overwrite file if it exists, the remote server has the source file bc remote_src is set below
  copy:
    src: "/var/lib/abc.zip"
    dest: E:\xyz\data\charts.zip
    remote_src: yes

You can remove the file before copy the new one:

- name: Delete file before copy
  win_file:
    path: E:\xyz\data\charts.zip
    state: absent
Related