In everyday life of a DevOps engineer you will have to create multiple pieces of code. Some of those will be run once, others … well others will live forever. Although it may be compelling to just put all the commands in a text editor, save the result and execute it, one should always consider the “bigger picture”. What will happen if your script is run on another OS, on another Linux distribution, or even on a different version of the same Linux distribution?! Another point of view is to think what will happen if somehow your neat 10-line-script has to be executed on say 500 servers?! Can you be sure that all the commands will run successfully there? Can you even be sure that all the commands will even be present? Usually … No!

Faced with similar problems on a daily basis we started devising simple solutions and practices to address them. One of those is the process of standardizing the way different utilities behave, the way they take arguments and report errors. Upon further investigation it became clear that a pattern can be extracted and synthesized in a series of template, one can use in daily work to keep common behavior between different utilities and components.

Here is the basic template used in shell scripts:

Nothing fancy. Basic framework that does the following:

  1. Lines 3 – 13: Make sure basic documentation, dependency list and example usage patterns are provided with the script itself;
  2. Lines 15 – 16: Define meaningful return codes to allow other utils to identify possible execution problems and react accordingly;
  3. Lines 18 – 27: Basic help/usage() function to provide the user with short guidance on how to use the script;
  4. Lines 29 – 52: Dependency checks to make sure all utilities the script needs are available and executable in the system;
  5. Lines 54 – 77: Argument parsing of everything passed on the command line that supports both short and long argument names;
  6. Lines 79 – 91: Validity checks of the argument values that should make sure arguments are passed contextually correct values;
  7. Lines 95 – N: Actual programming logic to be implemented …

This template is successfully used in a various scenarios: command line utilities, Nagios plugins, startup/shutdown scripts, UserData scripts, daemons implemented in shell script with the help of start-stop-daemon, etc. It is also used to allow deployment on multiple operating systems and distribution versions. Resulting utilities and system components are more resilient, include better documentation and dependency sections, provide the user with similar and intuitive way to get help or pass arguments. Error handling is functional enough to go beyond the simple OK / ERROR state. And all of those are important feature when components must be run in highly heterogenous environments such as most cloud deployments!

Share on LinkedIn0Tweet about this on TwitterShare on Facebook3Share on Google+0Email this to someone