Cron Jobs

Preconditions

  • Scripts should not run as root uid
  • Oc commands and API calls should not be performed as user system:admin or cluster:admin or similar rights

Setup

For convenience the cron script should run on the master. But for an authentication token is used, it might as well run on a dedicated node, with oc installed (if necessary)

  1. Create a linux user, named like your namespace(project): useradd <namespace>
  2. Create a folder in /usr/local/bin/cronscripts/<namespace>: mkdir -p /usr/local/bin/cronscripts/<namespace>
  3. chown <namespace>:<namespace>  /usr/local/bin/cronscripts/<namespace>
  4. Create two scripts: set-env.sh and run_cron.sh in the folder
    1. set-env.sh contains environment settings
    2. run_cron.sh is the cron script. It calls “source set-env.sh”
  5. Use the default service account of your project or another dedicated service account as user for oc commands or API calls
    1. See https://docs.openshift.com/enterprise/3.1/dev_guide/service_accounts.html#using-a-service-account-s-credentials-externally how to get the authentication token of the service account
    2. Using authentication token of a service account and command line parameters for the cluster master, this command doesn’t need a ~/.kube/config
    3. The token of a service account never expires
  6. set-env.sh should look like this
    export NAMESPACE=<namespace>
    export TOKEN=<authentication token of service account>
    export MASTER_URL=<HTTPS URL of master server)
    export OC="/usr/bin/oc --certificate-authority=/etc/openshift/master/ca.crt --server=$MASTER_URL --namespace=$NAMESPACE --token=$TOKEN"
  7. If your service account has to query certain Openshift objects, e.g. like deployment configs it also needs at least the “view” role on your project
  8. Prepare run_cron.sh so that it uses $OC for oc commands. E.G. $OC process -f … | $OC create -f –
  9. Check cron installation, see https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-Automating_System_Tasks.html
  10. Create the crontab entry for the user <namespace>
  11. Create a folder log: mkdir -p /usr/local/bin/cronscripts/<namespace>/log && chown <namespace>:<namespace>  /usr/local/bin/cronscripts/<namespace>/log
  12. It is recommended to print the results of the script execution into this folder using a log file for every cron job.
    1. You might considering adding a timestamp to you logfiles, e.g. foo_`date +”%Y%m%d_%H%M%S”`.log -> foo_20160426_135943.log