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
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With