How to set up :datadir: when using Hiera with Puppet and Vagrant

hierapuppetvagrant

I'd like to know how to set up :datadir: in hiera.yaml for optimal usage with Puppet and Vagrant. Currently I'm using vagrant 1.5.0 with virtualbox 4.2 on Ubuntu 13.10 with an Ubuntu 12.04 guest running puppet 3.1.1

I am trying to set up an environment similar to this blog post, Puppet Best Practices: Environment specific configs. Specifically, my Vagrantfile contains:

  config.vm.define "servername" do |servername|
    servername.vm.box = "precise-puppet-3"
    servername.vm.network "private_network", ip: "192.168.213.2",
      virtualbox__intnet: "networkname"

    # Provision with puppet.
    servername.vm.provision :puppet do |puppet|
      puppet.hiera_config_path = "puppet/hiera.yaml"
      puppet.manifests_path = "puppet/manifests"
      puppet.module_path = "puppet/modules"
      puppet.manifest_file  = "servername.pp"
      puppet.facter = {
        "vagrant" => "1",
        "server" => "servername",
      }
    end
  end

I can confirm that the hiera_config_path is correct, because I get an error if I delete hiera.yaml.

puppet/hiera.yaml contains:

---
:backends: yaml
:yaml:
  :datadir: "manifests/configuration"
:hierarchy:
  - "%{::clientcert}"
  - "%{::environment}"
  - "virtual_%{::is_virtual}"
  - common
:logger: console

And, further, puppet/manifests/configuration/common.yaml contains:

---
myvar: "test"

Testing this from the commandline:

$ hiera -c hiera.yaml myvar
test

So far, so good. However, if I try to test this from within a puppet manifest file, the variable cannot be found, and I get an error. Example test:

$myvariable = hiera(myvar)
notice("My variable is: ${myvar}")

The error is:

Error: Could not find data item myvar in any Hiera data file and no default supplied at...

If I ssh into my machine via vagrant ssh, I can see that Vagrant is mounting my manifest directory at /tmp/vagrant-puppet-2. If I edit the hiera.yaml file, and replace :datadir: with the full path /tmp/vagrant-puppet-2/manifests/configuration, then my Puppet manifests can access my Hiera data. Can I do this with a relative path, though?

Best Answer

I found the solution while documenting my question. Change :datadir: to read:

  :datadir: "%{settings::manifestdir}/configuration"

Puppet will provide the path to the manifest directory in $settings::manifestdir. Storing the Hiera data inside the manifest directory is useful because Vagrant will mount this directory explicitly before running Puppet in the guest system, and other directories you might select for this purpose might not be available.