Skip to content

Instantly share code, notes, and snippets.

@kucerarichard
Forked from vernondcole/restart_your_minion.sls
Created September 5, 2018 15:58
Show Gist options
  • Save kucerarichard/8e50ddf0f2da62e3f7be9e6798e3ccb9 to your computer and use it in GitHub Desktop.
Save kucerarichard/8e50ddf0f2da62e3f7be9e6798e3ccb9 to your computer and use it in GitHub Desktop.
SaltStack state to restart a minion (using the minion you are restarting)
---
# salt state file for restarting a minion under its own control
{% set delay = salt['config.get']('minion_restart_in_seconds', 5) %}
restart-the-minion:
file.managed:
- name: /tmp/run_command_later.py
- source: salt://run_command_later.py
- mode: 775
cmd.run:
- require:
- file: restart-the-minion
- order: last
- name: "/tmp/run_command_later.py {{ delay }} systemctl restart salt-minion"
- bg: true {# do not wait for completion of this command #}
...
#!/usr/bin/env python3
#
# Execute a shell command after a delay time.
# arg[1] is delay time in seconds
#
import sys, subprocess, time
CHEAP_LOG_FILE = '/tmp/' + __file__ + '.log'
args = sys.argv
if not sys.stdout.isatty():
sys.stdout = open(CHEAP_LOG_FILE, 'w') # cheap log output
sys.stderr = sys.stdout
cmd = args.pop(0)
try:
delay = float(args.pop(0))
if not args: # only an empty list remaining?
raise ValueError
except (ValueError, IndexError):
print('Usage: {} seconds_to_delay command and args to run'.format(cmd))
sys.exit(1)
print('sleeping {} seconds...'.format(delay))
time.sleep(delay)
print(time.asctime())
print('Running command: {}'.format(' '.join(args)))
print('- - - - - - - - - - - - - - -')
sys.stdout.flush()
try:
subprocess.run(' '.join(args), shell=True, check=True, stdout=sys.stdout, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment