jebjeb jebjeb - 3 months ago 30
Ruby Question

Setting chef vault variable in template.erb

I have a vault item defined as the following in my recipe

item = ChefVault::Item.load("user","password")


How do i call this this in my
template.erb
? I tried the following which isn't working

ROOTPASSWORD= <%= @node["testcookbook"]["user"]["password"] %>


Thank you Mrigesh- One thing i forgot to mention is my vault item looks like this

knife vault show user password
id: password
pass: xxxxxxxxxx
username: chefuser


How do i revise your first and second suggestion to only reference the "pass" within the vault? I generally do something like this within a recipe
ROOTPASSWORD #{item['pass']}'
however i dont think that would work in within a template. Thank you.

Answer

There are two options to solve that problem though the second one should be preferred as that keeps your sensitive data private.

Save as Node Attribute

First, if you want to set the password on node object and make it visible, then you can do something like below:

In recipe:

node.default["testcookbook"]["user"]["password"] = ChefVault::Item.load("user","password")

template '/tmp/template' do
  source 'template.erb'
  owner 'root'
  group 'root'
  mode '0644'
end

In Template:

ROOTPASSWORD= <%= node["testcookbook"]["user"]["password"] %>

Pass Data to the Template using variables

Second, if you don't want to set the password on node object and let it visible in chef run logs, then you can do something like below:-

template '/tmp/template' do
  source 'template.erb'
  owner 'root'
  group 'root'
  mode '0644'
  sensitive true
  variables( {:password => ChefVault::Item.load("user","password")})
end

In Template:

ROOTPASSWORD= <%= @password %>
Comments