Often there is a need to add new users after deploying a new Linux box. In my case, I often have to add an user which takes care of the monitoring stuff (e.g. owning the Nagios plugins and executing them). The following little Cfengine 3 code snippet should help you to determine if a specific user exists.
Writing the Cfengine 3 code for determing if an user exists
body common control { version => "1.0"; inputs => { "cfengine_stdlib.cf" }; bundlesequence => { "check_user" }; } bundle agent check_user { classes: "userNagiosExists" expression => userexists("nagios"); reports: !userNagiosExists:: "User nagios does not exist! You have to create it or write a Cfengine 3 script which does that for you."; }
Let’s put the code above in a new file and check it for errors. Afterwards it can be executed:
/var/cfengine/bin/cf-promises -f /etc/cfengine3/xenuser_org-015-check_if_user_exists.cf /var/cfengine/bin/cf-agent -f /etc/cfengine3/xenuser_org-015-check_if_user_exists.cf
If the user “nagios” doesn’t exist on your machine, the syslog now should contain a proper warning:
mintbox xenuser_org-educational_examples # tail -f /var/log/syslog Sep 30 17:25:10 mintbox cf3[6101]: R: User nagios does not exist! You have to create it or write a Cfengine 3 script which does that for you.
It is now up to you if you create the user manually or write a Cfengine 3 snippet for that task. Who knows, maybe there will be one in the next blog post?
Analyzing the Cfengine 3 code snippet
Let’s jump right to the interesting part:
bundle agent check_user { classes: "userNagiosExists" expression => userexists("nagios"); reports: !userNagiosExists:: "User nagios does not exist! You have to create it or write a Cfengine 3 script which does that for you."; }
We created a new class which can be set to true or false with the help of an expression (“userexists”). If being set to false, the class can be used to report a warning in the reports promise.
Remember that you can either let Cfengine 3 directly mail you such reports or you could use tools (such as logcheck) to watch your log files.
As usual, you can download todays’s Cfengine 3 code snippet here.