Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the PS command in the variables SaltStack

I have a State, which should give me an output if the folder exists or not. I don't know how to escape the name of the folder Programs files so PS knows what I mean.

{% set label = salt['cmd.run']('powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\Folder\""') %}

{% if label == 'True' %}
  First:
    cmd.run:
      - name: Write-Host "Exist"
      - shell: powershell

{% else %}
  Secondary:
    cmd.run:
      - name: Write-Host " NOT "
      - shell: powershell
{% endif %}

I get NOT each time I try, but the folder exists

Can you tell me how to make this work. And where can I find information on how to escape lines in YAML

like image 455
Mateo Neo Avatar asked May 17 '26 20:05

Mateo Neo


2 Answers

I would recommend using the Saltstack file module to check existence of a directory with the directory_exists function.

This allows us to use the requisite system to trigger further states.

Example:

check-dir-exists:
  module.run:
    - name: file.directory_exists
    - path: 'C:\Program Files (x86)\SomeDirectory'

show-dir-exists:
  cmd.run:
    - name: Write-Host "Dir exists"
    - shell: powershell
    - require:
        - module: check-dir-exists

show-dir-not-exist:
  cmd.run:
    - name: Write-Host "Dir not exists"
    - shell: powershell
    - onfail:
        - module: check-dir-exists

Or store the return value True/False in a variable and match condition in if/else statement.

Example:

{% set label = salt['file.directory_exists']('C:\Program Files (x86)\SomeDirectory') %}

{% if label %}
show-dir-exists:
  cmd.run:
    - name: Write-Host "Dir exists"
    - shell: powershell
{% else %}
show-dir-not-exist:
  cmd.run:
    - name: Write-Host "Dir not exists"
    - shell: powershell
{% endif %}
like image 157
seshadri_c Avatar answered May 20 '26 18:05

seshadri_c


The problem most likely isn't in the call to powershell.exe, because this is what I get when I run the following from the cmd.exe command prompt:

C:\>powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\DoesntExist\""
False

C:\>powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\""
True
like image 20
Leon Bouquiet Avatar answered May 20 '26 19:05

Leon Bouquiet