Check file exists and create a symlink
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 %}
You should use Dan Garthwaite's excellent answer here as a basis for how to check for the existence of a file. I have modified his solution to answer your question.
{% if 1 == salt['cmd.retcode']('test -f /path/to/A') %}
/path/to/A:
file.symlink:
- target: /symlink/path/A
{% endif %}
/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.