Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible - check if file exists on *local* machine

I have a situation where I need to check the status of a file on the local machine (the one where I will call ansible-playbook ...).

If a file that is created by the user exists, it needs to be copied over to the remote host(s). If it doesn't exist, then none of the remote hosts need it.

I know I've done things like :

- name: Check for ~/.blah/config
  stat: path=/home/ubuntu/.blah/config
  register: stat_blah_config

- name: Do something with blah config
  shell: ~/do_something_with_config.sh
  when: stat_aws_config.stat.exists == true

But that will only work if the file exists remotely. Is there a way to conditionally execute a task (like copy) only if the file exists locally (have the stat in the first task execute locally instead of remotely), and fail silently if it does not? I'm not sure if ansible has this kind of functionality, but it would be useful.

like image 380
FrustratedWithFormsDesigner Avatar asked Oct 05 '15 20:10

FrustratedWithFormsDesigner


People also ask

What is Local_action in Ansible?

In an Ansible playbook, when local_action is used, Ansible will run the module work mentioned under it on the controller node. Mostly modules used with local_action are shell and command. As you can do almost all the tasks using these modules on the controller node.

How do I view Ansible files?

To check whether the destination file exists and then run tasks based on its status, we can use the Ansible's stat module (or win_stat for Windows targets). With this module we can identify not only whether the destination path exists or not but also if it is a regular file, a directory or a symbolic link.


1 Answers

Delegating the tasks to the localhost via the delegate_to statement should do what you want:

- name: Check for ~/.blah/config
  delegate_to: localhost
  stat:
    path: /home/ubuntu/.blah/config
  register: stat_blah_config
like image 182
Bruce P Avatar answered Oct 02 '22 15:10

Bruce P