red888 red888 - 3 months ago 10x
Ruby Question

How do I use vault items in templates?

I'm learning chef.

I have this recipe:

chef_gem 'chef-vault' do
compile_time true if respond_to?(:compile_time)

require 'chef-vault'

vault = ChefVault::Item.load("vault01", "vaultitem1")

log 'DEBUG' do
message vault['myuser']
level :info

directory 'c:/blah'

template 'c:/blah/template.txt' do
source 'template.txt.erb'

You can see I'm getting the value out of the vault in the recipe.

How should I insert these values into my template file?

Is there a way I can get the vault vaules from inside of my template.txt.erb?


Use the variables property. You pass it a hash and then those keys are available as variables in your template:

template 'c:/blah/template.txt' do
  source 'template.txt.erb'
  variables vault: ChefVault::Item.load("vault01", "vaultitem1")

# and then in the template
<%= @vault['foo'] %>

Also check out the chef-vault cookbook (distinct from the chef-vault gem) which has a nice chef_vault_item() helper to make testing easier.