How to call other state in custom state code?
Hi, I'm writing a custom state in /srv/salt/_states/git_refresh.py, and I just want to call file.managed state in this py.
What should I do?? Thanks.
Hi,
I've never tried it, but I believe you should be able to call the function salt'file.managed' from within your custom state with the appropriate args and it should run that state and return a dict as per the usual state output (return data).
cheers, Tim
oops, that should be
__salt__['file.managed'](...)
ok last try before I give up and have a beer
__salt__['file.managed'](...)
That actually won't work -- __salt__ is only loaded with the execution module functions, not the state module functions.
We don't currently provide a mechanism by which you can call states from other states -- states are designed to be fairly standalone, and the modules those states use to implement their behavior are available.
That said, this could be useful, so perhaps we should add a mechanism by which this could be accomplished. I'll have to think on it.
There is a very hacky way to do it, we need to add states into the loader cross caller. The hacky way is CRAZY HACKY, I don't remember exactly how to do it, but you use sys.modules to look it up off the python stack. We should open this as a feature request
Done.
i use the salt.loader
import salt.loader
def present(name, infoblox_host_record=None, inventory_mfcf_record=None):
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
__state__ = salt.loader.states(__opts__, __salt__)
# STATE: infoblox_host_record
# ----------------------------------------------
if infoblox_host_record:
sub_ret = __state__['infoblox_host_record.present'](name=name, data=infoblox_host_record)
if sub_ret['result'] == False or sub_ret['result'] == None:
return sub_ret
if sub_ret['changes']:
ret['changes'].update({'1- infoblox_host_record.present': sub_ret['changes']})
steverweber, thanks for posting that workaround. When using it I have a problem that some states rely on the global dictionary env being defined, but it isn't available in the state dictionary loaded through salt.loader.states. Any idea how I might use salt.loader.states in such a way that the env dictionary is available?
edit: I figured out that I could do something like this:
__states__ = salt.loader.states(__opts__, __salt__)
__states__['file.managed'].func_globals['__env__'] = __env__
It's very hacky, but it seems to work.
thanks for the edit. I was about to look into it :)
This would be intensly useful, a lot of custom states are wrappers around some very common states like file.managed, which at the moment is around 250 lines of code. Being able to re-use this instead of writing it yourself is an enormous gain and actually makes it feasible to implement custom states for a lot of stuff, which currently isn't an option because of the amount of code needed.
The workaround by steverweber and tensorproduct works like a charm until something there's built-in support for this.
Edit: After a little more testing, the above method does work in isolation, but it causes other stuff to fail in weird ways, like pkgrepo.present failing with KeyErrors due to 'os_family' not being present in grains and similar. However, the following method seems to work without side-effects:
from salt.states.file import managed as file_managed
def my_state(name):
for dunder_dict in 'env salt opts grains pillar'.split():
dunder = '__%s__' % dunder_dict
file_managed.func_globals[dunder] = globals()[dunder]
ret = file_managed(...)
@basepi @thatch45 Solution by @thusoy looks great and it seems to work. Do you think this is the way to go until SaltStack officially supports calling states from other states?
Thanks - this is a very useful feature hope you implement it in core SaltStack.
I'm currently doing something gross like @thusoy solution. There's also some discussion in #3513, which also adds some bits about the grains, @thusoy you might be interested to give it a try maybe?
Refs #23927
This will be a little weird to make, as it will make somewhat of a circular dep. Right now the loader builds on top of the layers (basically) grains -> modules -> states (where states can be replaced with almost all module types). If we want to add states to modules, then we'll have to figure out how to get a reference to that exact dict -- which i just circular references :/
The alternative is to optimize the state.* functions- such that you can cross call to the state module which will do all the state magic on its own-- the key will be to not re-load the state module's highstate object on each call-- since that is slow :)
@jacksontj I think the desire is more towards re-using states in other states, than states in modules (if I understood your point correctly). Are there any downsides to the approach listed above? Here's the same approach, but refactored into a context manager and with some more error checking:
import sys
import contextlib
import importlib
@contextlib.contextmanager
def salt_state(qualified_state, _globals):
try:
module_name, func_name = qualified_state.split('.', 1)
except ValueError:
message = ("Argument to salt_state needs to be of the form "
"'<module>.<function>' (was '{}')".format(qualified_state))
_, _, traceback = sys.exc_info()
raise ValueError(message), None, traceback
try:
module = importlib.import_module('salt.states.{}'.format(module_name))
except ImportError:
message = "No state with the name '{}'".format(module_name)
_, _, traceback = sys.exc_info()
raise ValueError(message), None, traceback
func = getattr(module, func_name, None)
if func is None:
raise ValueError("'{}' state does not have a function '{}'".format(
module_name, func_name))
for dunder_dict in 'env salt opts grains pillar instance_id'.split():
dunder_name = '__%s__' % dunder_dict
dunder = _globals.get(dunder_name)
# instance_id is not on older salt versions, thus the check
if dunder is not None:
func.func_globals[dunder_name] = dunder
yield func
You could then use it like this:
def my_custom_state(name):
with salt_state('file.managed', globals()) as file_managed:
file_ret = file_managed(name)
<..>
Shall I make a PR out of this or is there some better way? I tried to get rid of having to pass globals() as an argument to the context manager, since it's a bit ugly. I tried by using a decorator instead, thinking I could fetch the dunder dicts from the decorated function when called, and inject the state with the globals applied into its scope, but the decorated got some of the dunders applied to itself, so it got a bit hacky, and I think it messed with the decorated function. Anyway, the one above works and is the least hacky alternative I managed when trying to put the function outside the custom state.
Oh, if the ask is soely to cross call state modules from other states this is actually trivial. We'd just need to add a pack (in the loader) which referenced the rest of the states-- maybe something like __states__. Then in your state you could do something like:
def custom_state(name):
__states__['file.managed'](name)
# insert your stuff here
Does that cover what you were thinking?
@jacksontj That would be brilliant, would cover all of my use cases at least.
That would cover my use case as well. Thanks.
Rajul Vora - typos by Android On Jun 21, 2015 12:25 AM, "Tarjei Husøy" [email protected] wrote:
@jacksontj https://github.com/jacksontj That would be brilliant, would cover all of my use cases at least.
— Reply to this email directly or view it on GitHub https://github.com/saltstack/salt/issues/21214#issuecomment-113870767.
I'll crank that out Monday morning then :) On Jun 21, 2015 11:12 AM, "Rajul Vora" [email protected] wrote:
That would cover my use case as well. Thanks.
Rajul Vora - typos by Android On Jun 21, 2015 12:25 AM, "Tarjei Husøy" [email protected] wrote:
@jacksontj https://github.com/jacksontj That would be brilliant, would cover all of my use cases at least.
— Reply to this email directly or view it on GitHub https://github.com/saltstack/salt/issues/21214#issuecomment-113870767.
— Reply to this email directly or view it on GitHub https://github.com/saltstack/salt/issues/21214#issuecomment-113937468.
PR opened (#24865). I added a test and some simple documentation.