How to use OpsWorks App Data Bag (aws_opsworks_app) environment variables in Chef templates?

760 Views Asked by At

Given Chef 12 support from OpsWorks was released very recently - all documents I can find are for the Chef 11. So, here is my current setup: flask + gunicorn + nginx on OpsWorks with Chef 12. I use Upstart to start Gunicorn using a template:

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid <%= node['conf-cookbook']['gunicorn_user'] %>
setgid <%= node['conf-cookbook']['gunicorn_group'] %>

env MAIL_SERVER="email-smtp.us-east-1.amazonaws.com"
env MAIL_USERNAME="[redcacted]"
env MAIL_PASSWORD="[redacted]"

chdir <%= node['conf-cookbook']['app_dir'] %>

exec gunicorn --workers 3 --bind unix:<%= node['conf-cookbook']['gunicorn_socket'] %> -m 007 --log-file <%= node['conf-cookbook']['gunicorn_logfile']%> manage:app

I have to include the sensitive environment variable information in the template. In OpsWorks Chef 12, environment variables can be specified using App Data Bag (aws_opsworks_app) and retrieved using something like in deploy recipe (never tried - is it correct):

app = search(:aws_opsworks_app).first
app['environment']['MAIL_SERVER']

I would like to use the app data bag environment variables to replace the ones I defined in the template file and don't know how. Any one can help?

Thanks!!

1

There are 1 best solutions below

4
On BEST ANSWER

You can pass arbitrary variables data to Chef template resources:

template '/etc/init/myapp.conf' do
  source 'myapp.conf.erb'
  variables node['conf-cookbook'].merge(app)
end

and then make your template look more like this:

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid <%= @gunicorn_user %>
setgid <%= @gunicorn_group %>

<%- @environment.each do |key, value| -%>
env <%= key %>="<%= value %>"
<%- end -%>

chdir <%= @app_dir %>

exec gunicorn --workers 3 --bind unix:<%= @gunicorn_socket %> -m 007 --log-file <%= @gunicorn_logfile %> manage:app

Also check out the poise-service and application_python cookbooks, which have helpers for both writing Upstart config files and Gunicorn services respectively.