skip to Main Content

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


  1. In SaltStack Jinja is evaluated before YAML. The file creation will (cmd.run) be executed after Jinja. So your Jinja variable is empty because the file isn’t created, yet.

    See https://docs.saltproject.io/en/latest/topics/jinja/index.html

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search