Home > front end >  remove cron jobs along with their comment, environment which were created by Puppet by awk/sed
remove cron jobs along with their comment, environment which were created by Puppet by awk/sed

Time:09-17

Is there a way to remove/delete cron jobs created by Puppet by using awk/sed? I know that we can edit by crontab -e command manually, but this is a question for scripting. Example root cron is a file in /var/spool/cron/crontabs/root. I want to remove lines below.

# Puppet Name: cron1
[email protected],admin@localhost
* * * * * /bin/true
# Puppet Name: cron test
PATH="/usr/local/bin"
[email protected]
2-57 * * * * echo "test"
# Puppet Name: thank you
* * * * * echo "Thank you!"
....

Puppet cron has patterns:

  1. Begin with # Puppet Name:
  2. It can contain Cron Environment or not. This can be multiple lines

If anyone knows how to do it, please help. Thank you!

CodePudding user response:

You would be well advised to use Puppet to remove the crontab entries that were created by Puppet.

If you have to do it via a manual-ish shell command, however, then you can do it via this sed command:

sed -nie '/^# Puppet Name:/!{p;d};:p;n;/^[ \t]*\(\|#.*\|[A-Za-z_][A-Za-z_0-9]*[ \t]*=.*\)$/ b p' \
  /var/spool/cron/crontabs/root

Explanation

The command assumes that each group of lines to delete starts with a "Puppet Name:" comment and continues up to and including the next line that is neither blank (but for whitespace), nor a comment, nor an environment variable assignment. It modifies the specified file in place (-i), with auto-printing disabled (-n). The expression (-e) does the following:

  • If the next line read does not start with the text "# Puppet Name:" then print that line and start the next cycle ({p;d}). Otherwise,
  • this point in the expression is labelled "p" (:p);
  • silently (because auto-print is disabled) read the next line of input (n);
  • if the current line is blank, is a comment, or is an environment setting then branch to label p (b p);
  • else the end of the expression is reached. Silently (because auto-print is disabled) start the next cycle.
  • Related