/
cmd.py
1233 lines (952 loc) · 37.7 KB
/
cmd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files do not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to the cmd state in version 2014.7.0,
and made a global requisite in 3001.
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself do not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
"""
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
import salt.utils.platform
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
"""
Re-interpret the state returned by salt.state.run using our protocol.
"""
ret = state["changes"]
state["changes"] = {}
state["comment"] = ""
out = ret.get("stdout")
if not out:
if ret.get("stderr"):
state["comment"] = ret["stderr"]
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state, "script JSON output must be a JSON object (e.g., {})!"
)
is_json = True
except ValueError:
idx = out.rstrip().rfind("\n")
if idx != -1:
out = out[idx + 1 :]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split("=")
data[key] = val
except ValueError:
state = _failout(
state,
"Failed parsing script output! "
"Stdout must be JSON or a line of name=value pairs.",
)
state["changes"].update(ret)
return state
changed = _is_true(data.get("changed", "no"))
if "comment" in data:
state["comment"] = data["comment"]
del data["comment"]
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data["stdout"] = "" if is_json else data.get("stdout", "")[:idx]
state["changes"] = data
# FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state["comment"] = msg
state["result"] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ("true", "yes", "1"):
return True
elif six.text_type(val).lower() in ("false", "no", "0"):
return False
raise ValueError("Failed parsing boolean value: {0}".format(val))
def wait(
name,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel="debug",
hide_output=False,
use_vt=False,
success_retcodes=None,
**kwargs
):
"""
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files do not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
"""
# Ignoring our arguments is intentional.
return {"name": name, "changes": {}, "result": True, "comment": ""}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, "watch")
def wait_script(
name,
source=None,
template=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel="debug",
hide_output=False,
**kwargs
):
"""
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
"""
# Ignoring our arguments is intentional.
return {"name": name, "changes": {}, "result": True, "comment": ""}
def run(
name,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel="debug",
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
**kwargs
):
"""
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files do not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
"""
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {"name": name, "changes": {}, "result": False, "comment": ""}
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and "test_name" in stateful[0]:
test_name = stateful[0]["test_name"]
if __opts__["test"] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret["comment"] = "Invalidly-formatted 'env' parameter. See " "documentation."
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update(
{
"cwd": cwd,
"root": root,
"runas": runas,
"use_vt": use_vt,
"shell": shell or __grains__["shell"],
"env": env,
"prepend_path": prepend_path,
"umask": umask,
"output_loglevel": output_loglevel,
"hide_output": hide_output,
"success_retcodes": success_retcodes,
}
)
if __opts__["test"] and not test_name:
ret["result"] = None
ret["comment"] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret["comment"] = ('Desired working directory "{0}" ' "is not available").format(
cwd
)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = "cmd.run_all" if not root else "cmd.run_chroot"
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err: # pylint: disable=broad-except
ret["comment"] = six.text_type(err)
return ret
ret["changes"] = cmd_all
ret["result"] = not bool(cmd_all["retcode"])
ret["comment"] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = "Timed out after"
if ret["changes"].get("retcode") == 1 and trigger in ret["changes"].get(
"stdout"
):
ret["changes"]["retcode"] = 0
ret["result"] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__["test"] and cmd_all["retcode"] == 0 and ret["changes"]:
ret["result"] = None
return ret
def script(
name,
source=None,
template=None,
cwd=None,
runas=None,
password=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel="debug",
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
**kwargs
):
"""
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
cwd
The current working directory to execute the command in, defaults to
/root
runas
Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. note::
For Window's users, specifically Server users, it may be necessary
to specify your runas user using the User Logon Name instead of the
legacy logon name. Traditionally, logons would be in the following
format.
``Domain/user``
In the event this causes issues when executing scripts, use the UPN
format which looks like the following.
``user@domain.local``
More information <https://github.com/saltstack/salt/issues/55080>
password
.. versionadded:: 3000
Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files do not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of