使用动态变量创建模板

使用动态变量创建模板

本文介绍了Chef-使用动态变量创建模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在厨师食谱方面遇到了一些挑战。

I'm having a bit of a challenge on a Chef recipe. I'm new to Chef, so please bear with me.

第1步:我的厨师食谱安装了Ruby Passenger,然后编译了Passenger Nginx模块和Nginx。

Step 1: My chef recipe installs Ruby Passenger, then compiles the Passenger nginx module along with Nginx.

# Install passenger and nginx module
bash "Install Passenger" do
  code <<-EOF
  source /usr/local/rvm/scripts/rvm
  gem install passenger
  EOF
  user "root"
  not_if { `gem list`.lines.grep(/^passenger \(.*\)/).count > 0 }
end

# Install passenger
# Note that we have to explicitly include the RVM script otherwise it won't setup the environment correctly
bash "Install passenger nginx module and nginx from source" do
  code <<-EOF
  source /usr/local/rvm/scripts/rvm
  passenger-install-nginx-module --auto --prefix=/opt/nginx --auto-download
  EOF
  user "root"
  not_if { File.directory? "/opt/nginx" }
end

步骤2:之后,我创建了使用模板的nginx配置文件。此配置需要乘客的位置,具体取决于步骤1的完成。

Step 2: After that, I create the nginx config file using a template. This configuration requires the location of Passenger, which is dependent on step 1 completing.

template "/opt/nginx/conf/nginx.conf" do
  source "nginx.conf.erb"
  action :create
  variables(
    deploy_user: deploy_user,
    passenger_root: `bash -c "source /usr/local/rvm/scripts/rvm; passenger-config --root"`.chomp,
    passenger_ruby: `bash -c "source /usr/local/rvm/scripts/rvm; which ruby"`.chomp,
    passenger: node[:passenger]
  )
end



Problem: Chef appears to compile templates at th ebeginning of the run. So what ends up happening is that Step 2 is actually compiled before Step 1 is run. This means that the passenger_root variable is blank. It needs Step 1 to complete before being able to get the passenger_root, then run the template.

我尝试将步骤2的代码包装在 ruby​​_block中,但不起作用:未定义的方法模板',用于Chef :: Resource :: RubyBlock`。

I tried wrapping the step 2 code in a ruby_block but that doesn't work: undefined methodtemplate' for Chef::Resource::RubyBlock`.

不确定在这里做什么,或者厨师对这样的最佳做法是什么?

Not sure what to do here, or what is the best practice for Chef for something like this?

预先感谢,

伦纳德

推荐答案

一种更清洁,推荐的方法是使用。

A cleaner and recommended way is to use Lazy Attribute Evaluation.

template "/opt/nginx/conf/nginx.conf" do
  source "nginx.conf.erb"
  action :create
  variables lazy {
    {
      deploy_user: deploy_user,
      passenger_root: `bash -c "source /usr/local/rvm/scripts/rvm; passenger-config --root"`.strip,
      passenger_ruby: `bash -c "source /usr/local/rvm/scripts/rvm; which ruby"`.strip,
      passenger: node[:passenger]
    }
  }
end

我也是d建议使用条带代替 chomp [感谢Draco]。

Also, I'd suggest using strip instead of chomp [thanks Draco].

这篇关于Chef-使用动态变量创建模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:35