A collection of task oriented solutions in Puppet

 

You want to create a directory tree

Challenge

You want to create a new directory tree

Solution

class directory_tree {

  # create a directory tree, list the directories in order
  # and puppet will 'do the right thing'.
  file { [  '/usr/local/whisper/', '/usr/local/whisper/2.0',
            '/usr/local/whisper/2.0/bin', '/usr/local/whisper/2.0/log' ]:
    ensure => 'directory',
  }

  # or you can assign them to a variable and use them in the resource
  $whisper_dirs = [ '/usr/local/whisper/', '/usr/local/whisper/2.0',
                    '/usr/local/whisper/2.0/bin', '/usr/local/whisper/2.0/log',
                  ]

  file { $whisper_dirs:
    ensure => 'directory',
    owner  => 'root',
    group  => 'wheel',
    mode   => '0750',
  }

  # doesn't work - will fail unless whisper and 2.0 already exist
  file { '/usr/local/whisper/2.0/bin':
    ensure => 'directory',
  }
}

Explanation

Creating a directory tree in puppet is slightly harder than you'd first expect as puppet lacks a native mkdir -p equivalent. Instead you can use an array of directories, each one progressing slightly further down the tree and puppet will create each of them in turn. Starting with puppet 2.7 (File type should auto-require all parents) each directory will auto-require its nearest ancestor directory, which will add another layer of guaranty to this method of creating a directory tree.

You can use a number of the parameters from the file type to control the directories properties, such as the owner, group and mode (permissions). It's also worth reiterating, as this is an often raised "bug", puppet will not create missing parent directories.

See also