我正在从 python 脚本运行剧本。我正在关注this code
以下命令完美运行。
ansible -i path/to/inventory.yml host_name -m command -a"a2ensite site_name"
但是当我尝试通过从 python 脚本执行剧本来执行相同操作时。它说该网站不存在。以下是剧本。
playbook = dict(
name = "Enable Site",
hosts = ['token_server'],
gather_facts = 'no',
tasks = [
dict(action=dict(module='command', args="a2ensite " + site_name), register='shell_out'),
dict(action=dict(module='service', args="name='apache2' state='reloaded'"), register='shell_out'),
]
)
它给出了以下错误。
fatal: [token_server]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "cmd": "a2ensite token_server", "delta": "0:00:00.054682", "end": "2019-12-11 01:03:10.546478", "msg": "non-zero return code", "rc": 1, "start": "2019-12-11 01:03:10.491796", "stderr": "ERROR: Site token_server does not exist!", "stderr_lines": ["ERROR: Site token_server does not exist!"], "stdout": "", "stdout_lines": []}
更新 我尝试运行这个剧本。此剧本显示“/etc/apache2/sites-available”目录的内容。
playbook = dict(
name = "Enable Site",
hosts = ['token_server'],
gather_facts = 'yes',
tasks = [
dict(action=dict(module='shell', args='ls /etc/apache2/sites-available'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
它显示了我本地的/etc/apache2/sites-available 目录的内容。 这意味着该命令实际上是在我的本地执行的,而不是在远程服务器上。
这是我的“主机 list 文件”。
all:
hosts:
policy_server:
ansible_host: 155.138.130.72
ansible_password: XXXXXXXXXX
ansible_ssh_common_args: -o StrictHostKeyChecking=no
ansible_user: root
token_server:
ansible_host: 155.138.150.239
ansible_password: XXXXXXXXXX
ansible_ssh_common_args: -o StrictHostKeyChecking=no
ansible_user: root
最佳答案
最可能的解释是您过于严格地遵循该示例。文档提供的示例具有以下行:
context.CLIARGS = ImmutableDict(connection='local',
module_path=['/to/mymodules'],
forks=10, become=None, become_method=None, become_user=None,
check=False, diff=False)
该行包含 connection='local'
,它指示 ansible 始终连接到本地主机,无论指定的主机如何。尝试从 CLIARGS 中删除它,您的连接应该可以正常工作。祝你好运!
关于python - 使用 Ansible 启用 Apache 站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274380/