Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite file in Ansible

Tags:

ansible

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.

like image 579
user10373379 Avatar asked Sep 21 '18 07:09

user10373379


People also ask

Does ansible use SCP?

If you want to copy a file from an Ansible Control Master to remote hosts, the COPY (scp) module would be just fine.

Which ansible modules can be used to change the contents of a file?

Ansible ini_file module This module is a life-saver when modifying ini type files with many changes.

What is chdir in ansible?

Changing the Default Directory You can change and specify the directory path where you want to run the command using the chdir parameter. This parameter is available for both command and shell module. You can also change the default shell by specifying the absolute path of the require shell in the executable parameter.


1 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
like image 166
codeymcgoo Avatar answered Sep 20 '22 11:09

codeymcgoo