如何在库中使用Chef资源

时间:2014-12-30 16:49:39

标签: ruby oop resources chef

如何在库中包含Chef Directory资源?执行下面的配方时,会分配变量,但不会创建目录。我没有收到任何错误消息。

这是一个简化的例子。尝试通过将目录名称传递给库来创建多个目录。

# create directories  
#  /var/www/domain  
#  /var/www/domain/production  
#  /var/www/domain/staging  

图书馆

# directory library  
class DirectoryStructure
  attr_accessor :domain, :production, :staging

  def initialize(domain)
    @domain = "/var/www/#{domain}"
    @staging = "#@domain/staging"
    @production = "#@domain/production"
  end

  def create(dir_type,directory_path,username,group)
    dir = Chef::Resource::Directory.new(:create)
    dir.name(directory_path)
    dir.owner(username)
    dir.group(group)
    dir.mode(2750)
    dir
  end
end

食谱

web_dirs = DirectoryStructure.new(domain)  
site_dirs.create(web_dirs.domain,username,deploy_group)  
site_dirs.create(web_dirs.production,username,deploy_group)  
site_dirs.create(web_dirs.staging,username,deploy_group)  

我试图使用这个例子,但我显然遗漏了一些东西 enter link description here https://docs.chef.io/lwrp_custom_resource_library.html

1 个答案:

答案 0 :(得分:3)

看起来你应该创建一个资源,无论是LWRP还是普通的Ruby类。在大多数情况下,LWRP会更简单,在这种情况下可能就是你想要的。

cookbooks/mycook/resources/directory_structure.rb

default_action :create
attribute :domain, name_attribute: true
attribute :owner
attribute :group

cookbooks/mycook/providers/directory_structure.rb

action :create do
  directory "/var/www/#{@new_resource.domain}" do
    owner new_resource.owner
    group new_resource.group
  end
  directory "/var/www/#{@new_resource.domain}/production" do
    owner new_resource.owner
    group new_resource.group
  end

  directory "/var/www/#{@new_resource.domain}/staging" do
    owner new_resource.owner
    group new_resource.group
  end
end

cookbooks/mycook/providers/directory_structure.rb

mycook_directory_structure 'example.com' do
  owner 'me'
  group 'mygroup'
end