In this tutorial we will show how to use CFEngine to manage users, add them to groups, setup their home directory and copy ssh-keys to their .ssh directory as part of creating the user.

1. Create some files and groups that we will use

Create the files id_rsa and id_rsa.pub in /tmp directory

    # touch /tmp/id_rsa /tmp/id_rsa.pub

Create user group security and webadmin (if they don’t already exists)

    # sudo groupadd security 
    # sudo groupadd webadmin

2. Create CFEngine policy called users.cf

Create a file called /tmp/users.cf with the following content:

    # vi /tmp/users.cf
body common control
{
  bundlesequence => { "main" };
  inputs => { "$(sys.libdir)/stdlib.cf" };
}

bundle agent main
{
  vars:
  "users" slist => { "adam", "eva" };
  users:
    "$(users)"
    policy => "present",
    home_dir => "/home/$(users)",
    group_primary => "users",
    groups_secondary => { "security", "webadmin" },
    shell => "/bin/bash/",
    home_bundle => setup_home_dir("$(users)");
}

bundle agent setup_home_dir(user)
{
  vars:
    "keys" slist => { "id_rsa", "id_rsa.pub" };
  files:
    "/home/$(user)/." create => "true";
    "/home/$(user)/.ssh/." create => "true";
    "/home/$(user)/.ssh/$(keys)" copy_from => local_cp("/tmp/$(keys)");
}

3. Test it out, and verify the result

Run CFEngine:

    # /var/cfengine/bin/cf-agent -fK /tmp/users.cf

Verify the result: Have users have been created?

    # cat /etc/passwd

Congratulations! You should now see the users adam and eva listed.

Verify the result: Have users home directory have been created?

    # ls /home

Congratulations! You should now see adam and eva listed.

Verify the result: Have users have been added to the correct groups?

    # sudo cat /etc/group

Congratulations! You should now see adam and eva added to the groups security and webadmin. Nb! CFEngine will not create groups, so you must make sure the groups exists.

Verify the result: Have ssh-keys have been copied from /tmp to user’s ./ssh directory?

    # ls /home/adam/.ssh /home/eva/.ssh

Congratulations! You should now see the files id_rsa and id_rsa.pub.

Ps. If you would like play around with the policy, delete the users after each run with the command

 # deluser -r username

Mission accomplished!






Please help us improve:

19 5

Do you have ideas / feedback to share with us? Send feedback