Creating new symlinks with Cfengine 3

Sometimes it is necessary to create new symlinks. The following code snippet shows you how to do that with Cfengine 3. Please note that there are several ways of achieving our goal, but the following one should be the most efficient one when you only want to set one symlink.

Writing the Cfengine 3 code for creating a new symlink

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

bundle agent create_symlink {
  files:
        "/etc/im_a_symlink"
          comment       => "Creating the symlink /etc/im_a_symlink",
          link_from     => ln_s("/etc/aliases");
}

Check the code snippet for errors. If no warning or error message occurs you should be safe running the script:

/var/cfengine/bin/cf-promises -f /etc/cfengine3/xenuser_org-014-creating_symlinks.cf
/var/cfengine/bin/cf-agent -vvvvf /etc/cfengine3/xenuser_org-014-creating_symlinks.cf

Now have a look at your /etc/ directory:

ls -laht --color /etc/ |head
total 1,3M
drwxr-xr-x   3 root     root     4,0K 2012-09-01 21:54 cfengine3
drwxr-xr-x 154 root     root      12K 2012-09-01 21:46 .
lrwxrwxrwx   1 root     root       12 2012-09-01 21:46 im_a_symlink -> /etc/aliases

(Sorry for the screwed arrow in the output above.)

Yay! Cfengine 3 just created our symlink.

Analyzing the Cfengine 3 code snippet
Since the first part “body common control” should be already familiar to you, we will jump right to the interesting part:

bundle agent create_symlink {
  files:
        "/etc/im_a_symlink"
          comment       => "Creating the symlink /etc/im_a_symlink",
          link_from     => ln_s("/etc/aliases");
}

The bundle agent “create_symlink” above contains a file promise with the name of the symlink to be created. The attribute “link_from” gives Cfengine 3 the order to create a new symlink which points to the file provided in “ln_s()”.

This is a very easy and efficient method of creating symlinks. I hope that this code snippet might help in some way! 🙂

As usual, you can download today’s Cfengine 3 code snippet here.