Ansible to check particular directory exists, if not create it
Asked Answered
S

1

6

I am trying to find whether particular director exists in ansible, if not, create the one..The problem i am facing here is that the below code should not create a /var/tmp/directory, but it creates while running this.. ( the below code is not for creating a directory i think)

   tasks:
     - name: Checking /var/tmp/ansible directory exists
       stat: path=/var/tmp/ansible
       register: status

can anyone please help me to fix this issue..

Sextuplicate answered 15/6, 2020 at 16:22 Comment(1)
Are you sure this is creating directory? Is there any other tasks after this? You can use status.stat.exists to check if directory exists. And if it is true, create directory using file moduleEnstatite
B
11

You should use the file module:

- name: Create a directory if it does not exist
  file:
    path: /var/tmp/ansible
    state: directory
    mode: '0755'

There is no need to use stat to check whether the directory does not exist first, unless you plan to do something else with the result of that test. The file module ensures that the file is in the desired state after running the task.

Bury answered 15/6, 2020 at 16:29 Comment(2)
What if the directory exists with different permissions?Hoo
@SvenvandenBoogaart Then the permissions will be changed. The task defines the desired state and the file module either handles the changes necessary to get there or fails.Bury

© 2022 - 2024 — McMap. All rights reserved.