jayhendren
jayhendren

Reputation: 4518

When two different resources from two cookbooks have the same name, how can I specify which one to call?

I have a recipe that calls a custom resource called sysctl_param:

sysctl_param 'net.ipv4.tcp_syncookies' do
  value 1
end

However, as of Chef 14, sysctl_param is a built-in resource. So when I tested my recipe against Chef 14, it used the Chef-built-in sysctl_param resource instead of my custom one. This is breaking some of my tests because the built-in resource has slightly different behavior than the custom one.

How can I force Chef to use the custom sysctl_param resource instead of the built-in one? Please assume that "rename the custom resource" is not an option - even if renaming is an option, I would strictly like to know the answer to the question "how can I choose which resource to run when there are resource naming conflicts?".

Upvotes: 0

Views: 409

Answers (2)

jayhendren
jayhendren

Reputation: 4518

This is probably a giant footgun, but it works (at least in Chef 12.x and 14.2; I haven't yet tested with other versions).

Chef has a "priority map" and a "handler map" that are used to resolve resource method names (e.g. sysctl_param) into resource class names (e.g. Chef::Resource::Sysctl). You can use these tools to set which resource class responds to a given resource method.

For instance:

Chef.resource_priority_map.priority(:sysctl_param, [MyCookbook::SysctlParamResource])

sysctl_param 'net.ipv4.tcp_syncookies' do
  value 1
end

This will cause the custom resource (MyCookbook::SysctlParamResource) to be prioritized over the built-in resource. You should be able to use the same approach regardless of the source of the resources: two cookbooks, one cookbook and one built-in, etc.

You can get the list of classes that can respond to a particular method with Chef.resource_handler_map.list(node, :my_resource_name). You can verify how resources are resolved to classes by calling Chef::ResourceResolver.resolve(:my_resource_name).

Upvotes: 1

coderanger
coderanger

Reputation: 54249

We're in the process of improving this with the preview resources system in 14.3, but short version: you can't fix it, sorry. In 14.3 and onwards, new resources are being added in preview mode, which means the cookbook version will "win" until Chef 15.0.

Upvotes: 0

Related Questions