Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy local file if exists, using ansible

I'm working in a project, and we use ansible to create a deploy a cluster of servers. One of the tasks that I've to implement, is to copy a local file to the remote host, only if that file exists locally. Now I'm trying to solve this problem using this

- hosts: 127.0.0.1 
  connection: local
  tasks:
    - name: copy local filetocopy.zip to remote if exists
    - shell: if [[ -f "../filetocopy.zip" ]]; then /bin/true; else /bin/false; fi;
      register: result    
    - copy: src=../filetocopy.zip dest=/tmp/filetocopy.zip
      when: result|success

Bu this is failing with the following message: ERROR: 'action' or 'local_action' attribute missing in task "copy local filetocopy.zip to remote if exists"

I've tried to create this if with command task. I've already tried to create this task with a local_action, but I couldn't make it work. All samples that I've found, doesn't consider a shell into local_action, there are only samples of command, and neither of them have anything else then a command. Is there a way to do this task using ansible?

like image 441
dirceusemighini Avatar asked Mar 04 '15 13:03

dirceusemighini


People also ask

How do I copy files from one directory to another in ansible?

From the Ansible docs for the copy module: "The copy module copies a file on the local box to remote locations". You say that there are two files in /home/vagrant/dist. Are those located on the host you are running Ansible from, or on the host with the IP 172.16.


2 Answers

A more comprehensive answer:

If you want to check the existence of a local file before performing some task, here is the comprehensive snippet:

- name: get file stat to be able to perform a check in the following task
  local_action: stat path=/path/to/file
  register: file

- name: copy file if it exists
  copy: src=/path/to/file dest=/destination/path
  when: file.stat.exists

If you want to check the existence of a remote file before performing some task, this is the way to go:

- name: get file stat to be able to perform check in the following task
  stat: path=/path/to/file
  register: file

- name: copy file if it exists
  copy: src=/path/to/file dest=/destination/path
  when: file.stat.exists
like image 157
edelans Avatar answered Oct 16 '22 23:10

edelans


Change your first step into the following on

- name: copy local filetocopy.zip to remote if exists
  local_action: stat path="../filetocopy.zip"
  register: result    
like image 24
Sandra Parsick Avatar answered Oct 17 '22 00:10

Sandra Parsick