2016-10-04 96 views
0

我正在編寫一個custom state module,目的是在給定位置創建一個文件(部分)可配置的內容。來自狀態模塊內的呼叫狀態模塊

基本上我希望縮短以下SLS(簡化這個問題的目的,在現實中更復雜的)...

/etc/foo/bar: 
    file.managed: 
    - contents: Hello World 

...這樣的:

bar: 
    my_module.foo: 
    - message: World 

由於此功能基本上是file.managed狀態的更專用版本,因此在我的自定義狀態模塊中重新使用file.managed狀態對我非常有用。

有沒有辦法從我自己的狀態模塊調用file.managed狀態模塊?


我已經試過已經(unsuccesfully):

  1. 導入salt.states.file,並呼籲salt.states.file.managed

    import salt.states.file 
    
    def foo(name, message, **kwargs): 
        return salt.states.file.managed(name='/etc/foo/%s' % name, 
                contents='Hello %s' % message, 
                **kwargs) 
    

    這將導致一個錯誤消息:

    File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1626, in call 
        **cdata['kwargs']) 
        File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1492, in wrapper 
        return f(*args, **kwargs) 
        File "/var/cache/salt/minion/extmods/states/my_module.py", line 14, in static_pod 
        contents=yaml.dump(data, default_flow_style=False), **kwargs) 
        File "/usr/lib/python2.7/dist-packages/salt/states/file.py", line 1499, in managed 
        mode = __salt__['config.manage_mode'](mode) 
    NameError: global name '__salt__' is not defined 
    
  2. 使用__salt__['file.managed']

    def foo(name, message, **kwargs): 
        return __salt__['file.managed'](name='/etc/foo/%s' % name, 
                contents='Hello %s' % message, 
                **kwargs) 
    

    這也導致一個(不同的)的錯誤消息(這是不足爲奇的,因爲文檔明確指出__salt__僅包含執行模塊,而不是狀態模塊):

    File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1626, in call 
        **cdata['kwargs']) 
        File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1492, in wrapper 
        return f(*args, **kwargs) 
        File "/var/cache/salt/minion/extmods/states/my_module.py", line 13, in static_pod 
        return __salt__['file.managed'](name='/etc/foo/%s' % name, 
        File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 900, in __getitem__ 
        func = super(LazyLoader, self).__getitem__(item) 
        File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 93, in __getitem__ 
        raise KeyError(key) 
    KeyError: 'file.managed' 
    

回答

0

我發現使用state.single執行模塊的解決方案:

def foo(name, messsage): 
    result = __salt__['state.single'](fun='file.managed', 
             name='/etc/foo/%s' % name, 
             contents='Hello %s' % message, 
             test=__opts__['test']) 
    return result.items()[0][1] 

state.single模塊返回類似如下的數據結構:

{ 
    'file_|-/etc/foo/bar_|-/etc/foo/bar_|-managed': { 
    'comment': 'The file /etc/foo/bar is set to be changed', 
    'name': '/etc/foo/bar', 
    'start_time': '08:24:45.022518', 
    'result': None, 
    'duration': 18.019, 
    '__run_num__': 0, 
    'changes': {'diff': '...'} 
    } 
} 

內部對象(下file_|-/etc/foo/bar_|-/etc/foo/bar_|-managed一切)是什麼file.managed模塊將自動返回,這樣你就可以將此值重新用作自定義狀態的返回值。