SaltStack - Unable to check if file exists on minion

Viewed 441

I am trying to check if a particular file with some extension exists on a centos host using salt stack.

 create:
   cmd.run:
     - name: touch /tmp/filex

{% set output = salt['cmd.run']("ls /tmp/filex") %}

output:
   cmd.run:
     - name: "echo {{ output }}"

Even if the file exists, I am getting the error as below:

ls: cannot access /tmp/filex: No such file or directory
3 Answers

I see that you already accepted an answer for this that talks about jinja being rendered first. which is true. but i wanted to add to that you don't have to use cmd.run to check the file. there is a state that is built in to salt for this.

file.exists will check for a file or directories existence in a stateful way.

One of the things about salt is you should be looking for ways to get away from cmd.run when you can.

create:
  file.managed:
    - name: /tmp/filex

check_file:
  file.exists:
    - name: /tmp/filex
    - require:
        - file: create

Jinja statements such as your set output line are evaluated when the sls file is rendered, before any of the states in it are executed. It's not seeing the file because the file hasn't been created yet.

Moving the check to the state definition should fix it:

output:
  cmd.run:
    - name: ls /tmp/filex
    # if your underlying intent is to ensure something runs only
    # once the file exists, you can enforce that here
    - require:
      - cmd: create
Related