0
votes

I am working on this recipe which assigns api key from an encrypted data bag item. To retrieve the data bag item I am using chef attributes in the query. This is what I am doing to assign the attributes

ruby_block "get_my_region" do
  block do
    node.set['aws']['account_number'] = `curl -s http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\\" '{print $4}'`.chop
    node.save
  end
  action :create
end

ruby_block "get_account" do
    block do
      node.set['aws']['region'] = `curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep -oP '(?<="accountId" : ")[^"]*(?=")'`.chop
      node.save
    end
    action :create
end

Once the attributes get assigned I am calling a template to using the assigned attribute to the config file

template '/etc/default/polymur-proxy' do
  source 'polymur-proxy.erb'
  notifies :restart, 'service[polymur-proxy]', :delayed
  variables(
  api_key: (api_keys["#{node['aws']['region']}"]["#{node['aws']['account_number']}"]["key"]).to_s,
  )
end

The problem is the while debugging I can see the attribute got assigned the correct values however while using them in the query they return empty. If any one has any suggestion for this will be helpful

1

1 Answers

0
votes

You are experiencing Chef's two pass execution model, template variables are evaluated before ruby_block resources calls. You can wrap api_keys with lazy block.

However, there is no need to manually call curl on AWS metadata endpoint. Chef's ohai ec2 plugin is extracting them anyway - node["ec2"]["account_id"] and node["ec2"]["availability_zone"] (just drop az id here wit tr or gsub). You can pass this right to the template or even use node directly in your template.