Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How check if a file exists in ansible windows?

Tags:

ansible

I am using Ansible on windows and I have to check whether a file exists in C:\Temp. If the file Doesn't exist then I have to skip the task. I am trying to use the win_stat module and this is what I have which isn't working:

- name: Check that the ABC.txt exists
  win_stat:
    path: 'C:\ABC.txt '      

- name: Create DEF.txt file if ABC.txt exists
  win_file:
    path: 'C:\DEF.txt'
    state: touch
  when: stat_file.stat.exists == True 
like image 582
Shahar Hamuzim Rajuan Avatar asked Apr 06 '17 07:04

Shahar Hamuzim Rajuan


People also ask

How do you check if a file exists or not in Ansible?

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.

How do I find files in Ansible?

Ansible find module functions as same as the Linux Find command and helps to find files and directories based on various search criteria such as age of the file, accessed date, modified date, regex search pattern etcetera.

How do I run Ansible command in Windows?

The win_command module takes the command name followed by a list of space-delimited arguments. The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like $env:HOME and operations like "<" , ">" , "|" , and ";" will not work (use the ansible.

How do you delete a file if it exists in Ansible?

Delete a file if it exists You can delete a file by setting state to absent . If the file doesn't exist, Ansible will do nothing.


2 Answers

So I didn't use the win_stat module correctly,

Should have added the register argument in my first 'task'.

This is how it works-

- name: Check that the ABC.txt exists
  win_stat: path= 'C:\ABC.txt'  
  register: stat_file

- name: Create DEF.txt file if ABC.txt exists 
  win_file:
    path: 'C:\DEF.txt'
    state: touch
  when: stat_file.stat.exists == True
like image 134
Shahar Hamuzim Rajuan Avatar answered Nov 06 '22 23:11

Shahar Hamuzim Rajuan


When I tried the answer above, it gave me a syntax error, instead I had to write it this way:

- name: Check that the ABC.txt exists
  win_stat: 
    path: 'C:\ABC.txt'  
  register: stat_file

- name: Create DEF.txt file if ABC.txt exists 
  win_file:
    path: 'C:\DEF.txt'
    state: touch
  when: stat_file.stat.exists == True
like image 5
Alex Weitz Avatar answered Nov 06 '22 23:11

Alex Weitz