Using environment variables in Cfengine 3

Every Cfengine 2 script of my company contains environment variables. They are essential for configuring most of the services running on the different servers.

For porting those scripts to Cfengine 3 one day I wanted to know how to make use of environment variables in the latest version of the configuration management tool. Well, the code snippet below is the result of my research…

Writing the Cfengine 3 script

# Cfengine code snippet by Valentin Hoebel (valentin@xenuser.org)
# Created on August 10th 2012; Simple example for making use of environment variables
# You are free to use and share this code snippet in any way you want.

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

bundle agent demonstrate_env_variable_usage {
  vars:
        "current_dir" string    => getenv("PWD", "50");

  files:
        "/etc/motd"
          comment       => "Ensure that /etc/motd contains nonsense",
          edit_line     => insert_lines("Greetings from $(current_dir)!");
}

Now save the file with an editor of your choice (I used “example9.cf”) and make sure that it is located in the right directory (e.g. /etc/cfengine3).

Let’s see if the syntax is correct:

/var/cfengine/bin/cf-promises -f /etc/cfengine3/example9.cf

If there is no error message we can run our Cfengine script then:

/var/cfengine/bin/cf-promises -f /etc/cfengine3/example9.cf

Now have a look at the /etc/motd file for verification:

mintbox cfengine3 # cat /etc/motd
Welcome to Linux Mint 12 Lisa (GNU/Linux 3.0.0-12-generic i686)

Welcome to Linux Mint
 * Documentation:  http://www.linuxmint.com

Greetings from /etc/cfengine3!

Looks great, doesn’t it?

Analyzing the Cfengine 3 code snippet
Assuming you are already familiar with the meaning of the first section of the code snippet (“body common control”) we just have a quick look at the most important part:

bundle agent demonstrate_env_variable_usage {
  vars:
        "current_dir" string    => getenv("PWD", "50");

  files:
        "/etc/motd"
          comment       => "Ensure that /etc/motd contains nonsense",
          edit_line     => insert_lines("Greetings from $(current_dir)!");
}

At first we define a bundle agent called “demonstrate_env_variable_usage” with the two promises “vars:” and “files:”.
The promise “vars” contains a variable definition. With the help of “getenv()” we are able to receive the value of the environment variable $PWD and store it in current_dir.
The promise “files” defines the file to be edited (“/etc/motd”). With the method “edit_line” we can ensure that the “insert_line” statement writes the text string “Greetings from !” and the content of the environment variable into the text file.

I hope this simple example is useful to you! As usual you can download today’s Cfengine 3 code snippet here.