如何 运行 在 python 中使用 ansible 和 ansible-playbook

How to run ansible and ansible-playbook in python

我正在使用 python 3.4 和 ansible 2.0, 我所有的 ansible 任务都可以从命令行正常工作

这里我正在执行一个简单的任务:

- hosts: all
  tasks:
  - name: Install bind
    yum: state=latest name=bind

我的主机文件是:

S1 ansible_host=server1.jackson.com ansible_user=root ansible_private_key_file=/home/jackson/Documents/ansible/virt_server.pem
S2 ansible_host=server2.jackson.com ansible_user=root ansible_private_key_file=/home/jackson/Documents/ansible/virt_server.pem

我在 youtube 博客和所有地方都进行了搜索,但没有找到关于 ansible 的教程 2.X 在使用 **ansible.runner** 的教程中无处不在,但在 ansible 2.0 中它不可用。

我只想要一个示例来教我如何定义主机、ansible 配置、任务、变量以及如何执行任务。

此外,我还想知道如何使用 JSON 而不是 .yml 文件,以便我可以从数据库或用户输入中获取配置变量,在一个动态 [= 中对所有内容进行排序28=]脚本。

Ansible Docs 为使用 Python API 2.0 和 pre-2.0 提供了一个很好的文档。参见 http://docs.ansible.com/ansible/developing_api.html#python-api-2-0

我确实在使用正确版本的 python 将正确版本的 ansible 设置为 运行 时遇到问题,但您可以使用 virtualenv 创建虚拟环境并安装 ansible 使用从该环境中获取 pip,然后尝试导入 ansible 以确保其正常工作。

有些情况下可以使用 JSON,但更简单的解决方案是使用脚本将 YAML 更改为 JSON。

来自http://yamltojson.com/#python

import yaml
import json

yml = """
---
  foo: bar
"""
data = yaml.load(yml)
json = json.dumps(data)

print(json)