问题
I am creating a bunch of different Chef providers to deploy different types of applications. Chef's documentation for Extend a Lightweight Provider suggests it is possible but doesn't actually say what to do. That page suggests that perhaps a call to mixin
is needed, but I don't know what structure my code should have in the file under /libraries
or how to actually include that code in something under /providers
.
Here are the examples of what I want to do.
In my base class under /libraries
:
repository "http://my.svn.server/#{deployment[:project]}/branches/#{node[:chef_environment]}/"
user "deploy"
scm_provider Chef::Provider::Subversion
svn_username "svn_user"
svn_password "password"
In my provider for Torquebox Rails app deployments:
deploy_revision "/my/deployment/directory/#{deployment[:project]}" do
# Magically mixin the code from libraries
environment "RAILS_ENV" => node[:chef_environment]
restart_command "rake torquebox:deploy"
end
And then of course other types of providers for different types of applications.
Can anyone point me in the right direction on this? Is there documentation somewhere I'm missing?
回答1:
The Chef will automatically convert the LWRP DSL into a full-blown Ruby class at runtime. This is determined by the name of the cookbook followed by the name of the file (this is the same way the actual resource name is created).
So if you have a cookbook named bacon
and an LWRP in bacon/resources/eat.rb
, the associated LWRP is bacon_eat
. The associated class is the camel-cased, constantized version of that - Chef::Resource::BaconEat
and Chef::Provider::BaconEat
in this case.
There is one exception to this pattern - default
. "Default" is special in Chef land, as it doesn't get prefixed. So if you have a cookbook named bacon
and an LWRP in bacon/resources/default.rb
, the associated LWRP is bacon
(not bacon_default
). The associated class is the camel-cased, constantized version of that - Chef::Resource::Bacon
and Chef::Provider::Bacon
(not "BaconDefault") in this case.
Okay, so why the backstory? In order to extend an LWRP, you want to inherit from the LWRP's class (Rubyism). So in your libraries/
directory, you want to extend your custom resource:
class Chef
class Resource::MyResource < Resource::Bacon # <- this
end
end
So, in your example:
class Chef
class Resource::MyDeployRevision < Resource::DeployRevision
def initialize(name, run_context = nil)
super
# This is what you'll use in the recipe DSL
@resource_name = :my_deploy_revision
# Things like default action and parameters are inherited from the parent
# Set your default options here
@repository = "http://my.svn.server/#{node['deployment']['project']}/branches/#{node.chef_environment}/"
@user = 'deploy'
@scm_provider = Chef::Provider::Subversion
@svn_username = 'svn_user'
@svn_password = 'password'
end
end
end
Then use my_deploy_revision
in your recipes.
来源:https://stackoverflow.com/questions/16114469/how-to-extend-a-lightweight-provider-in-chef