Setting file permissions and ownerships with Cfengine 3

One of the most common tasks of a Linux sysadmin (or DevOp) might be setting file permissions and ownerships. In this blog I’ll show you how you can do that in a very simple but effective way with Cfengine 3.

Writing the Cfengine 3 code for setting file permissions and ownerships

body common control {
        version         => "1.0";
        inputs          => { "cfengine_stdlib.cf" };
        bundlesequence  => { "set_file_permissions_and_ownerships" };
}

bundle agent set_file_permissions_and_ownerships {
        files:
         "/etc/xenuser.org"
                create  => "true",
                perms   => mog("1777", "backup", "staff");
}

Let’s check the file for syntax error and run it afterwards:

/var/cfengine/bin/cf-promises -f xenuser_org-017-setting_file_permissions_and_ownerships.cf
/var/cfengine/bin/cf-agent -f xenuser_org-017-setting_file_permissions_and_ownerships.cf

Now check if the file was created and equipped with the correct permissions + ownerships:

ls -lah --color /etc/xenuser.org 
-rwxrwxrwt 1 backup staff 0 2012-10-14 14:19 /etc/xenuser.org

Great! 🙂

Analyzing the Cfengine 3 code snippet
We jump right to the interesting part since you already know what the “body common control” section is about:

bundle agent set_file_permissions_and_ownerships {
        files:
         "/etc/xenuser.org"
                create  => "true",
                perms   => mog("1777", "backup", "staff");
}

The bundle agent contains a promise of the type “files” which at first defines the file to be handled. With the “create => true” statement we ensure that this file really exists while “perms =>…” enforces the correct file permissions and ownerships.

As you can see, the function “perms” works the following way:
mog(“file permissions, e.g. 777”, “user”, “group”);

Furthermore you can set the special permissions (such as the sticky bit) with the first parameter of mog().
If you wonder where “mog” comes from – well, it is part of the Cfengine 3 standard library and stands for “mode owner group”. There is also an “og” statement:

body perms mog(mode,user,group)
{
owners => { "$(user)" };
groups => { "$(group)" };
mode   => "$(mode)";
}

##

body perms og(u,g)
{
owners => { "$(u)" };
groups => { "$(g)" };
}

(Taken from /etc/cfengine3/cfengine_stdlib.cf.)

I hope that this little code snippet is helpful to you. As usual, you can download today’s Cfengine 3 code sample here.