30

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.

FrustratedWithFormsDesigner
  • 25,116
  • 30
  • 128
  • 188
  • Actually, I may have already found an answer here, using `local_action`: http://stackoverflow.com/questions/28855236/copy-local-file-if-exists-using-ansible?rq=1 – FrustratedWithFormsDesigner Oct 05 '15 at 20:35
  • Does this answer your question? [Ansible include task only if file exists](https://stackoverflow.com/questions/28119521/ansible-include-task-only-if-file-exists) – Helder Pereira Jun 09 '20 at 18:42

1 Answers1

36

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

- name: Check for ~/.blah/config
  local_action: stat path=/home/ubuntu/.blah/config
  register: stat_blah_config
Bruce P
  • 17,554
  • 7
  • 59
  • 69
  • 2
    Are there any special permission settings that need to be set in order to use `local_action`? I keep getting "permission denied" errors: `TASK: [blah_stuff | Check for ~/.blah/config] ************************************** failed: [i-34b724e0 -> 127.0.0.1] => {"failed": true, "parsed": false} BECOME-SUCCESS-tqbkvkywytucgnfrjbmokwelpwddzevz /bin/sh: 1: /tmp/.ansible/tmp/ansible-tmp-1444157688.04-230781782204943/stat: Permission denied` I did try using `sudo: true` but that didn't seem to help – FrustratedWithFormsDesigner Oct 06 '15 at 19:05
  • 1
    If `sudo:true` is failing then make sure the user you are running ansible as has the ability to sudo without a password. Ansible won't prompt you for a password, so if it can't perform the task then it will fail. – Bruce P Oct 08 '15 at 20:23