Can you access node attributes from within a Chef custom resource definition?
E.g., is this allowed:
action :run do
if node['foo']
<do_stuff>
end
end
My resource that does that appears to always be evaluating node['foo']
to “false,” making me wonder if the node object is even accessible within the resource definition.
The Chef.io page Custom Resources doesn’t show any examples of referring to a node attribute in the manner shown above. It does show references to a construct node.run_state['foo']
, but I’m not clear on whether that’s the syntax we are supposed to use to reference node attributes from with a custom resource definition.
Thank you!
So the intent is if there is a variable necessary in your custom resource, you should pass it through as a resource property. The goal being that the one and only way to control your resource is through its properties, not via node attributes.
In short, instead of using node['foo']
directly, pass foo in through a resource property and reference the new_resource value.
Thanks for your fast response, Tom. Now I know:
You cannot access node attributes from within a Chef custom resource definition. If your custom resource needs access to variable values, you must pass them in as resource properties.
I appreciate your help!
You can do it, it just isn’t recommended. It mostly comes up for using the value of an attribute as the default value for a property, which isn’t the worst thing in the world sometimes. For that just use a lazy definition: property(:foo, default: lazy { node["whatever"] })
Original Quoted context has been removed as per policy
Ah! Thanks, Noah. My new understanding is:
You can access node attributes from within a Chef custom resource definition -- but you shouldn't! It's not recommended. If your custom resource needs access to variable values, you should pass them in as resource properties.