0

如何将剧本从 dict 而不是本地 yaml 文件传递​​给 ansible-runner 以与 ansible 交互。

我将剧本转换为字典,我想使用它。而不是在单独的 yaml 文件中使用剧本。

但是执行脚本时出现错误。

import os


activate_this_file = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                  "..", "venv/bin/activate_this.py"))

execfile(activate_this_file, dict(__file__=activate_this_file))

import ansible_runner

hosts = ['vm']
inv = {'all': {'hosts': hosts}}

print(json.dumps(inv, indent=2))

play_src={
   "gather_facts": False,
   "tasks": [
   {
         "ping": None,
         "name": "ping"
   }
   ],
   "hosts": "all",
   "become": True
}


r = ansible_runner.run(private_data_dir='.', inventory=inv, playbook=play_src)

我得到的错误是:

Traceback (most recent call last):
  File "./test_runner.py", line 35, in <module>
    r = ansible_runner.run(private_data_dir='.', inventory=inv, playbook=play_src)
  File "/usr/home/secops_ansible/venv/lib/python2.7/site-packages/ansible_runner/interface.py", line 178, in run
    r.run()
  File "/usr/home/secops_ansible/venv/lib/python2.7/site-packages/ansible_runner/runner.py", line 112, in run
    command = [a.decode('utf-8') for a in self.config.command]
AttributeError: 'dict' object has no attribute 'decode

我怎么能模仿 yaml 文件的传递。ansible 在内部将 yaml 文件转换为 dict...,如 python api 文档中所示。

我通过使用它在我的代码中得到了 dict,这就是 ansible 解析 yaml 文件的方式:

#!/usr/bin/python

import json
from ansible import context
from ansible import constants as C
from ansible.playbook import Playbook
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager

loader=DataLoader()
variable_manager = VariableManager(loader=loader)


pb = Playbook.load('pb2.yml', variable_manager=variable_manager, loader=loader)
print(json.dumps(pb._loader.__dict__['_FILE_CACHE']['/usr/home/secops_ansible/ansible/pb2.yml'][0], indent=2))

谢谢

4

0 回答 0