示例¶
使用Ansible运行时¶
example.py
"""Sample use of Runtime class."""
from ansible_compat.runtime import Runtime
def test_runtime_example() -> None:
"""Test basic functionality of Runtime class."""
# instantiate the runtime using isolated mode, so installing new
# roles/collections do not pollute the default setup.
runtime = Runtime(isolated=True, max_retries=3)
# Print Ansible core version
_ = runtime.version # 2.9.10 (Version object)
# Get configuration info from runtime
_ = runtime.config.collections_path
# Detect if current project is a collection and install its requirements
runtime.prepare_environment(install_local=True) # will retry 3 times if needed
# Install a new collection (will retry 3 times if needed)
runtime.install_collection("examples/reqs_v2/community-molecule-0.1.0.tar.gz")
# Execute a command
result = runtime.run(["ansible-doc", "--list"])
assert result.returncode == 0
访问Ansible配置¶
您可能不想自己解析ansible-config dump
,您可以使用一个简单的python类来简化对它的访问,使用python数据类型。
"""Sample usage of AnsibleConfig."""
from ansible_compat.config import AnsibleConfig
def test_example_config() -> None:
"""Test basic functionality of AnsibleConfig."""
cfg = AnsibleConfig()
assert isinstance(cfg.ACTION_WARNINGS, bool)
# you can also use lowercase:
assert isinstance(cfg.action_warnings, bool)
# you can also use it as dictionary
assert cfg["action_warnings"] == cfg.action_warnings