csi
csi

Reputation: 9338

How do I use a Chef Resource in a Library

How do I include a Chef Directory resource in a library? When executing the recipe below, the variables are assigned but the directories aren't created. I don't receive any error messages.

This is a simplified example. Trying to create multiple directories by passing the directory name to a library.

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

The library

# 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

The recipe

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)  

I have tried to use this example but I am obviously missing something.
enter link description herehttps://docs.chef.io/lwrp_custom_resource_library.html

Upvotes: 1

Views: 581

Answers (1)

coderanger
coderanger

Reputation: 54267

This looks like you should be creating a resource, either an LWRP or a normal Ruby class. In most cases the LWRP will be simpler and is probably what you want in this case.

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

Upvotes: 3

Related Questions