SaltStack:如何使用上下文重复其他状态?
SaltStack: how do I repeat other states with context?
我为 API 服务创建了一个复杂的状态,它涉及 git 结帐、python venv、uwsgi、nginx 等。它工作正常。
现在我想把它变成一个模板并在每个 minion 中执行几次,使用 pillar 提供的变量 - 即类似的东西。
{% for apiserver in pillar.apiservers %}
include apiserver_template.sls, locals: apiserver.config
{% endfor %}
其中 apiserver_template 将使用提供给它的上下文,apiserver.config 具有每个 API 实例的所有配置数据。我知道语法是错误的,但希望我能传达这个想法——理想情况下,类似于执行 ruby partials 并提供局部变量。
saltland 是如何正确完成的?
在我看来,Jinja Macro 是您想为此使用的东西。您可以在此处找到有关用法的更多信息:https://docs.saltstack.com/en/2015.8/topics/development/conventions/formulas.html#jinja-macros
简而言之,您的情况可能如下所示:
{% macro api_server(git_repo, python_venv_path, python_venv_requirements) %}
{{python_venv_path}}:
virtualenv.managed:
- system_site_packages: False
- requirements: salt://{{python_venv_requirements}}
{{git_repo}}:
git.latest:
- name: {{git_repo}}
{% endmacro %}
假设你有一个支柱api服务器,其中每个api服务器都有git_repo、python_venv_path和python_venv_requirements值,你可以使用像这样的宏这个:
{% for server in salt.pillar.get('apiservers', []) %}
{{ api_server(server['git_repo'], server['python_venv_path'], server['python_venv_requirements']) }}
{% endfor %}
如果需要 - 您也可以将宏放在单独的状态文件中,然后将宏作为常规 salt 资源导入。
也请注意,我使用 salt.pillar.get('apiservers', []) 而不是 pillar.apiservers。这是从 pillar 获取数据的更安全的方法。如果由于某种原因支柱不可用 - 在第一种情况下,后面的代码将导致空字典而不是失败。
我为 API 服务创建了一个复杂的状态,它涉及 git 结帐、python venv、uwsgi、nginx 等。它工作正常。
现在我想把它变成一个模板并在每个 minion 中执行几次,使用 pillar 提供的变量 - 即类似的东西。
{% for apiserver in pillar.apiservers %}
include apiserver_template.sls, locals: apiserver.config
{% endfor %}
其中 apiserver_template 将使用提供给它的上下文,apiserver.config 具有每个 API 实例的所有配置数据。我知道语法是错误的,但希望我能传达这个想法——理想情况下,类似于执行 ruby partials 并提供局部变量。
saltland 是如何正确完成的?
在我看来,Jinja Macro 是您想为此使用的东西。您可以在此处找到有关用法的更多信息:https://docs.saltstack.com/en/2015.8/topics/development/conventions/formulas.html#jinja-macros
简而言之,您的情况可能如下所示:
{% macro api_server(git_repo, python_venv_path, python_venv_requirements) %}
{{python_venv_path}}:
virtualenv.managed:
- system_site_packages: False
- requirements: salt://{{python_venv_requirements}}
{{git_repo}}:
git.latest:
- name: {{git_repo}}
{% endmacro %}
假设你有一个支柱api服务器,其中每个api服务器都有git_repo、python_venv_path和python_venv_requirements值,你可以使用像这样的宏这个:
{% for server in salt.pillar.get('apiservers', []) %}
{{ api_server(server['git_repo'], server['python_venv_path'], server['python_venv_requirements']) }}
{% endfor %}
如果需要 - 您也可以将宏放在单独的状态文件中,然后将宏作为常规 salt 资源导入。
也请注意,我使用 salt.pillar.get('apiservers', []) 而不是 pillar.apiservers。这是从 pillar 获取数据的更安全的方法。如果由于某种原因支柱不可用 - 在第一种情况下,后面的代码将导致空字典而不是失败。