Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check file exists and create a symlink

Tags:

salt-stack

I want to do something like that:

if file A exists or there is no symlink B, I want to create a symlink B -> A.

For now I have:

 B:
   file:
    - symlink:
       - target: A
    - exists:
        - name: A

But this is bad it checks not the thing I want. How can I achive this simple thing in salt ?

like image 383
Darek Avatar asked Mar 26 '14 21:03

Darek


2 Answers

We can use file.directory_exists

{% if not salt['file.directory_exists' ]('/symlink/path/A') %}
symlink:
  file.symlink:
    - name: /path/to/A
    - target: /symlink/path/A
{% endif %}
like image 126
Abhilash Joseph Avatar answered Sep 22 '22 09:09

Abhilash Joseph


/path/to/symlink/B:
  file.symlink:
    - target: /path/to/target/A
    - onlyif:
      - test -f /path/to/target/A      # check that the target exists
      - test ! -L /path/to/symlink/B   # check that B is not a symlink

This will require both conditions to be True for the symlink to be created. Note that -L will also return 1 (False) if the file exists but is not a symlink.

From the docs:

The onlyif requisite specifies that if each command listed in onlyif returns True, then the state is run. If any of the specified commands return False, the state will not run.

NOTE: Under the hood onlyif calls cmd.retcode with python_shell=True. This means the commands referenced by onlyif will be parsed by a shell, so beware of side-effects as this shell will be run with the same privileges as the salt-minion. Also be aware that the boolean value is determined by the shell's concept of True and False, rather than Python's concept of True and False.

like image 31
bgdnlp Avatar answered Sep 21 '22 09:09

bgdnlp