user_dev
user_dev

Reputation: 1431

How to pass an attribute from a packer build to a chef coobook?

I am trying to pre-set a chef-attribute from a packer build but I can't seem to get it work:

    "provisioners": [
    {
      "chef_environment": "test_cookbook",

      "environments_path": "environments",
      "execute_command": "{{if .Sudo}}sudo {{end}}chef-solo --no-color --legacy-mode -c {{.ConfigPath}} -j {{.JsonPath}}",
      "json": {
          "test_cookbook": {
            "my_attr": "test"
          }
      },
      "run_list": [
        "test_cookbook"
      ],
      "type": "chef-solo",
    }
  ]

It is always getting passed as a nil value

output="#{Chef::Log.info(node['my_attr'])}"
log output
file "/tmp/#{node['my_attr']}" do
  content output
end

I already referred this Using attributes in Chef Solo JSON already.

Upvotes: 3

Views: 408

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

When using the json key for the Chef provisioner for Packer, the attributes passed to Chef will be key-value pairs starting with the key nested inside the json key. Therefore, you can access your attributes from within the test_cookbook key like:

output="#{Chef::Log.info(node['test_cookbook']['my_attr'])}"
log output
file "/tmp/#{node['test_cookbook']['my_attr']}" do
  content output
end

and this should assign the String test to the local variable output and place it as content within your temporary file. This is due to mapping you set up within the json key as:

"test_cookbook": {
  "my_attr": "test"
}

Upvotes: 3

Related Questions