Script to automate prepping a new CentOS 6 and 7 instance

Posted by paul on 2017.07.11

Script to automate prepping a new CentOS 6/7 instance

I will discuss a shell script I use for prepping a newly provisioned CentOS box for my personal use. I got started on this because I got tired of having to update a newly provisioned CentOS server by manually copying in ssh key, installing vim/curl/tmux, updating ~/.vimrc, install Ansible client, etc. So I created a simple shell script to automate prepping a brand new CentOS 6 and 7 instances. It works in multiple environments including AWS, Vagrant, other VPS, or physical boxes, as long as it has internet access to install rpms. In AWS and Vagrant, you can configure the script to run automatically once as soon as the OS is provisioned. Let's call the shell script

Code on Github

If you are comfortable with shell scripts and would like to jump straight into the script, here is the link:

Some of the characteristics of the script

  1. It is idempotent, meaning you can rerun the shell script repeatedly on the server and nothing should break. It's not foolproof but in most cases only the changes you intended will be made.
  2. Script is mainly tested on CentOS 7 but should work on CentOS 6 also. Please test the script on non-production servers first.
  3. Hide trivial error messages to reduce white noise.
  4. Script executes without prompting for any input. I wanted to use the script with provisioning tools provided by AWS and Vagrant, which does not allow the user to provide any input when the script is being executed.
  5. The script can delete itself when executed within the same folder. Let's say the script is kept in /root/bin/
  6. ex 1: ./    ### script will delete itself
    ex 2: /root/bin/   ### script will not delete itself.
  7. Although the script has nearly 300 lines of code, updating it is very simple because functions are used for all tasks. You will not need to invest exponentially longer dev/qa time whenever the script is modified.
  8. To add a new feature, I create a new function, add needed code in the new function, comment out other functions, and run to test. If that is successful, I uncomment other fucntions and test with all of the functions enabled. Because of granularity made possible by functions, this process is fairly quick.
  9. Another benefit of using functions for everything is being able to quickly modify that handles over 10 different changes into a smaller script that handles only 1 task, such as changing system time or add Ansible client. You can adapt to handle only 1 or 2 tasks by simply commenting out some function names at the end of the script.