How to overwrite file in Ansible - 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.

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

ansible copy in different host

I write a simple playbook to copy some configuration files on a certain machine.
I need to copy this file in a different host too for backup. Is possible to declare different host in the same playbook?
I need this cause my "backup host" can be different and I retrieve it from the hostname I use.
I tried both copy and raw module and nothing seems to work
here the example of playbook
- name: find file
find:
file_type: directory
paths: /prd/viv/dat/repository/
patterns: "{{inventory_hostname}}"
recurse: yes
register: find
delegate_to: localhost
- name: Copy MASTER
raw: echo xmonit$(echo {{find.files[0].path}} | cut -d "/" -f7 )
delegate_to: localhost
register: xmonit
- debug:
msg: "{{xmonit.stdout}}"
- name: Copy MASTER raw
raw: sshpass -p "mypass" scp {{find.files[0].path}}/master.cfg myuser#{{xmonit.stdout}}:/prd
delegate_to: localhost
#- name: Copy MASTER
#copy:
#src: "{{find.files[0].path}}/master.cfg"
#dest: /prd/cnf/dat/{{inventory_hostname}}/
edit: if I use the copy module the destination remains that of the main host while the goal is to copy to a third host.
I need to declare a different host for this single task
- name: Copy MASTER
copy:
src: "{{find.files[0].path}}/master.cfg"
dest: /prd/cnf/dat/{{inventory_hostname}}/
Like Zeitounator told me in the comments copy module are the best way to act.
like this it work for me
- name: Copy MASTER
copy:
src: "{{find.files[0].path}}/master.cfg"
dest: /prd/cnf/dat/{{inventory_hostname}}/
delegate_to: xmonit.stdout_lines[0]

How to preserve mtime/ctime of a file while copying file from local to remote using ansible playbook?

I am trying to copy a script to a remote machine and I have to preserve mtime of the file.
I have tried using mode:preserve and mode=preserve as stated in ansible documentation, here!
but it seems to preserve permissions and ownership only.
- name: Transfer executable script script
copy:
src: /home/avinash/Downloads/freeradius.sh
dest: /home/ssrnd09/ansible
mode: preserve
In respect to your question and the comment of Zeitounator, I've setup a test with synchronize_module and with parameter times, which was working as required.
---
- hosts: test.example.com
become: no
gather_facts: no
tasks:
- name: Synchronize passing in extra rsync options
synchronize:
src: test.sh
dest: "/home/{{ ansible_user }}/test.sh"
times: yes
Thanks to
How to tell rsync to preserve time stamp on files

Access local_tmp from a playbook

I've been setting the destination path of every temporary files I have to download. For instance:
- name: Downloading file
uri:
url: "{{url}}"
dest: ~/.ansible/tmp/
Is there any way of reading the configuration variable local_tmp (and remote_tmp) from within the playbook?
I'm not sure why you'd want to place the temporary files under local_tmp/remote_tmp directories handled by Ansible.
There is a module called tempfile which allows you to create a temporary directory under the path specified in system temporary directory:
- name: Ensure a temporary directory for download exists
tempfile:
state: directory
suffix: my_download
register: temp_dir
- name: Ensure a file is downloaded from {{ url }}
uri:
url: "{{ url }}"
dest: "{{ temp_dir.path }}"
and if you want to persist the name across the playbook runs, just create a subdirectory in lookup('env', 'TMPDIR') | default('/tmp') for local, or ansible_env.TMPDIR | default('/tmp') for remote.

Ansible: copy a directory content to another directory

I am trying to copy the content of dist directory to nginx directory.
- name: copy html file
copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/
But when I execute the playbook it throws an error:
TASK [NGINX : copy html file] **************************************************
fatal: [172.16.8.200]: FAILED! => {"changed": false, "failed": true, "msg": "attempted to take checksum of directory:/home/vagrant/dist/"}
How can I copy a directory that has another directory and a file inside?
You could use the synchronize module. The example from the documentation:
# Synchronize two directories on one remote host.
- synchronize:
src: /first/absolute/path
dest: /second/absolute/path
delegate_to: "{{ inventory_hostname }}"
This has the added benefit that it will be more efficient for large/many files.
EDIT: This solution worked when the question was posted. Later Ansible deprecated recursive copying with remote_src
Ansible Copy module by default copies files/dirs from control machine to remote machine. If you want to copy files/dirs in remote machine and if you have Ansible 2.0, set remote_src to yes
- name: copy html file
copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/ remote_src=yes directory_mode=yes
To copy a directory's content to another directory you CAN use ansibles copy module:
- name: Copy content of directory 'files'
copy:
src: files/ # note the '/' <-- !!!
dest: /tmp/files/
From the docs about the src parameter:
If (src!) path is a directory, it is copied recursively...
... if path ends with "/", only inside contents of that directory are copied to destination.
... if it does not end with "/", the directory itself with all contents is copied.
Resolved answer:
To copy a directory's content to another directory I use the next:
- name: copy consul_ui files
command: cp -r /home/{{ user }}/dist/{{ item }} /usr/share/nginx/html
with_items:
- "index.html"
- "static/"
It copies both items to the other directory. In the example, one of the items is a directory and the other is not. It works perfectly.
The simplest solution I've found to copy the contents of a folder without copying the folder itself is to use the following:
- name: Move directory contents
command: cp -r /<source_path>/. /<dest_path>/
This resolves #surfer190's follow-up question:
Hmmm what if you want to copy the entire contents? I noticed that * doesn't work – surfer190 Jul 23 '16 at 7:29
* is a shell glob, in that it relies on your shell to enumerate all the files within the folder before running cp, while the . directly instructs cp to get the directory contents (see https://askubuntu.com/questions/86822/how-can-i-copy-the-contents-of-a-folder-to-another-folder-in-a-different-directo)
Ansible remote_src does not support recursive copying.See remote_src description in Ansible copy docs
To recursively copy the contents of a folder and to make sure the task stays idempotent I usually do it this way:
- name: get file names to copy
command: "find /home/vagrant/dist -type f"
register: files_to_copy
- name: copy files
copy:
src: "{{ item }}"
dest: "/usr/share/nginx/html"
owner: nginx
group: nginx
remote_src: True
mode: 0644
with_items:
- "{{ files_to_copy.stdout_lines }}"
Downside is that the find command still shows up as 'changed'
the ansible doc is quite clear https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html for parameter src it says the following:
Local path to a file to copy to the remote server.
This can be absolute or relative.
If path is a directory, it is copied recursively. In this case, if path ends with "/",
only inside contents of that directory are copied to destination. Otherwise, if it
does not end with "/", the directory itself with all contents is copied. This behavior
is similar to the rsync command line tool.
So what you need is skip the / at the end of your src path.
- name: copy html file
copy: src=/home/vagrant/dist dest=/usr/share/nginx/html/
I found a workaround for recursive copying from remote to remote :
- name: List files in /usr/share/easy-rsa
find:
path: /usr/share/easy-rsa
recurse: yes
file_type: any
register: find_result
- name: Create the directories
file:
path: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
state: directory
mode: "{{ item.mode }}"
with_items:
- "{{ find_result.files }}"
when:
- item.isdir
- name: Copy the files
copy:
src: "{{ item.path }}"
dest: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
remote_src: yes
mode: "{{ item.mode }}"
with_items:
- "{{ find_result.files }}"
when:
- item.isdir == False
I got involved whole a day, too! and finally found the solution in shell command instead of copy: or command: as below:
- hosts: remote-server-name
gather_facts: no
vars:
src_path: "/path/to/source/"
des_path: "/path/to/dest/"
tasks:
- name: Ansible copy files remote to remote
shell: 'cp -r {{ src_path }}/. {{ des_path }}'
strictly notice to:
1. src_path and des_path end by / symbol
2. in shell command src_path ends by . which shows all content of directory
3. I used my remote-server-name both in hosts: and execute shell
section of jenkins, instead of remote_src: specifier in playbook.
I guess it is a good advice to run below command in Execute Shell section in jenkins:
ansible-playbook copy-payment.yml -i remote-server-name
Below worked for me,
-name: Upload html app directory to Deployment host
copy: src=/var/lib/jenkins/workspace/Demoapp/html dest=/var/www/ directory_mode=yes
This I found an ideal solution for copying file from Ansible server to remote.
copying yaml file
- hosts: localhost
user: {{ user }}
connection: ssh
become: yes
gather_facts: no
tasks:
- name: Creation of directory on remote server
file:
path: /var/lib/jenkins/.aws
state: directory
mode: 0755
register: result
- debug:
var: result
- name: get file names to copy
command: "find conf/.aws -type f"
register: files_to_copy
- name: copy files
copy:
src: "{{ item }}"
dest: "/var/lib/jenkins/.aws"
owner: {{ user }}
group: {{ group }}
remote_src: True
mode: 0644
with_items:
- "{{ files_to_copy.stdout_lines }}"
How to copy directory and sub dirs's and files from ansible server to remote host
- name: copy nmonchart39 directory to {{ inventory_hostname }}
copy:
src: /home/ansib.usr.srv/automation/monitoring/nmonchart39
dest: /var/nmon/data
Where:
copy entire directory: src: /automation/monitoring/nmonchart39
copy directory contents src: nmonchart39/

Copying files from the specified hosts to others in ansible

I have three hosts available in my inventory file
[controller]
1.1.1.1
2.2.2.2
3.3.3.3
i have a variable in group_var folder which specifies the master node
master=1.1.1.1
sql.conf is available in my home directory (/home/ubuntu/sql.conf) of all 3 controller hosts.
Now, i need to copy the file (test.txt) from master to others . Is there any way in ansible to copy the files from one specific server to others.
i am trying like this but couldnt achieve though.
- hosts: all
sudo: yes
tasks:
- name: copy files
local_action: command rsync -a /home/ubuntu/test.txt {{ master }}:///home/ubuntu/test.txt
One option is to use the fetch module to copy the file from the master node to your local node, and then use the copy module normally to distribute that file to other nodes. Something like:
- hosts: master
tasks:
- fetch:
src: /path/to/myfile.txt
dest: tmp/
- hosts: all:!master
tasks:
- copy:
src: tmp/master/myfile.txt
dest: /path/to/myfile.txt

Resources