6

Currently I have the following rule for creating a directory

/init/dir:
  file.recurse:
    - source:  salt://init_dir/init
    - user:  name
    - group:  group
    - name:  /path/init
    - dir_mode: 2775
    - file_mode: 777

Now I want to create a directory on new minions only if the directory does not exists already.

cmidi
  • 1,880
  • 3
  • 20
  • 35
  • I don't see your point, salt always apply states only if they are not applied already. Creating a directory anyway always behaves like this (regardless of salt). – Oberix Jun 26 '15 at 06:53

2 Answers2

12

While your example does work, it's not necessary. file.directory will only attempt to create the directory if it doesn't exist.

Utah_Dave
  • 4,531
  • 24
  • 23
  • There are some cases where file.directory will fail when the directory exists. For example, if the directory is a mount point for a FUSE filesystem, the mount point will appear to be a file when the filesystem is mounted, causing the file.directory state to fail. – Craig Finch Nov 14 '17 at 01:23
9

Turned out to be pretty easy and well documented in the salt-stack documentation Below is what I came up with.

{% if not salt['file.directory_exists' ]('/home/init_dir') %}
/home/init_dir:
  file.directory:
    - user:  user
    - name:  /home/init_dir
    - group:  group
    - mode:  755
{% else %}
  cmd.run:
    - name: echo "Directory exists"
{% endif %}
cmidi
  • 1,880
  • 3
  • 20
  • 35
  • 2
    If your purpose is to create the directory if it does not exist a simple "file.directory" will suffice. Using `makedirs=True` if the root directory does not exist. I used this to set modes/perms in an SLS if it existed (with the `recurse` option) – sastorsl Jan 04 '18 at 11:31
  • There is a bug with this solution. The id and the name of the directory you want to create shouldn't be the same. – Jessica Oct 02 '22 at 08:13