Changing kernel parameters in the
/etc/sysctl.conf file is part of system optimization and security hardening. You should use a CM tool to make and maintain any changes to this file. I will explain how to do this using Ansible. It took some trial and error out so I thought I would share it.
In this example I will walk through how to enable ExecShield; a setting the security guides recommend. I use CentOS and have not tested this on other flavors of Linux.
Write the Test First
Following test first development process, the first thing you always do is to create a test for the kernel parameter. What do you want the server to look like when you are done? How do you know the change was successful? I use serverspec for this purpose.
I use the more verbose “expect” syntax because it is self documenting. If you prefer the “should” syntax that the serverspec examples use then it would look like this:
This tests using the
sysctl command rather than checking the
sysctl.conf file contents. This is because the contents of the file may not have been applied hence the change hasn’t truly been implemented.
Now Make the Change
Changing this parameter in Ansible requires two steps: change the file and then load the changes. If the change works, the test will pass. First add this line to your base Ansible role
This handles three cases: makes no change if it is already enabled, adds it if the line is missing, and changes the parameter if it was set to a different value (e.g., ‘0’).
This changes the file but it still needs to be applied. The
notify action does that. Add the following to your
If you have many parameter changes Ansible will only run this one time at the end. This is one of many great design features in Ansible.
Test Your Change
Now run your play and then run your serverspec test. It should pass. If it doesn’t then either you or I have made a mistake. If it’s me then please post a comment below describing the problem so I can improve my script and share it with the world.