How can you use a Chef recipe to set an environmen

2019-01-11 02:59发布

How can you use a Chef recipe to set an environment variable?

I need to set an environment variable using a Chef recipe. Can you provide an example of how to accomplish this?

3条回答
We Are One
2楼-- · 2019-01-11 03:10

If you want to set it at the system level in /etc/environment, you can do so directly per the following example without adding an additional recipe (this adds two env variables for Java):

sys_env_file = Chef::Util::FileEdit.new('/etc/environment')
{
  'JAVA_HOME' => '/usr/lib/jvm/java-1.7.0-openjdk-amd64',
  'LD_LIBRARY_PATH' => '/usr/lib/jvm/java-1.7.0-openjdk-amd64/lib'
}.each do |name, val|
  sys_env_file.insert_line_if_no_match /^#{name}\=/, "#{name}=\"#{val}\""
  sys_env_file.write_file
end
查看更多
爷、活的狠高调
3楼-- · 2019-01-11 03:22

If you want to set it on the system with Chef, checkout the magic_shell cookbook.

magic_shell_environment 'RAILS_ENV' do
  value 'production'
end
查看更多
The star\"
4楼-- · 2019-01-11 03:25

If you need an env var set strictly within the Chef process, you can use ENV['foo'] = 'bar' since it's a ruby process.

If you need to set one for an execute provider, Chef exposes an environment hash:

execute 'Bootstrap the database' do 
  cwd "#{app_dir}/current"
  command "#{env_cmd} rake db:drop db:create db:schema:load RAILS_ENV=#{rails_env}"
  environment 'HOME' => "/home/#{app_user}"
  user app_user
  action :run
  not_if %[psql -U postgres -c "\\l" | grep #{db_name}]
end

If you're looking to set a persistent environment variable then you may want to have Chef edit /etc/profile.d/chef.sh, /etc/environment, a users' profile, etc.

查看更多
登录 后发表回答