簡體   English   中英

如何將字典列表從Python腳本導入Ansible劇本?

[英]How do I import List of dictionaries from Python script into Ansible playbook?

我有一個在單獨的python腳本中定義的python變量,其格式如下:

site_list = [   {'name': "MyTestSite",
                 'alias': 'site1',
                 'website_url':  ['website1.test.com' ,'website1.othertest.com'],
                 'projectname':'Testsite',
                 'id':'12345678'},

                {'name': '"OtherTestSite"',
                 'alias': 'foobar',
                 'website_url':  ['foobar.test.com' ,'foobar2.test.com'],
                 'projectname':'foobar',
                 'id':'98765432'},

                 ... (lots of other entries)

我正在嘗試將變量放入Ansible並在其中使用它,但是似乎我必須將變量重寫為.yml格式(基於https://docs.ansible.com/ansible/latest /modules/include_vars_module.html ),而不是只能導入python腳本並從那里使用它。

是否可以按原樣導入python變量,而不是使用yml重寫並將其放入Ansible目錄中的group_vars中?

我能看到的唯一的其他方法是將該變量打印到Python腳本內,從Ansible調用Python腳本,然后將輸出存儲為變量(但是這種解決方案在我看來有點笨拙)。

謝謝。

我建議使用將變量轉儲到json的查找插件管道和python文件:

Python文件vars.py:


import json

initial = [{'name': "MyTestSite",
                 'alias': 'site1',
                 'website_url':  ['website1.test.com' ,'website1.othertest.com'],
                 'projectname':'Testsite',
                 'id':'12345678'},

                {'name': '"OtherTestSite"',
                 'alias': 'foobar',
                 'website_url':  ['foobar.test.com' ,'foobar2.test.com'],
                 'projectname':'foobar',
                 'id':'98765432'}]


print(json.dumps(initial))

和劇本代碼:

---
- name: Test command
  hosts: localhost
  tasks:
  - name: Load variable to fact
    set_fact:
      the_var: "{{ lookup('pipe', 'python vars.py') | from_json }}"
  - name: Test command
    debug:
      msg: "{{ item }}"
    with_list: "{{ the_var }}"

使用文件之前,請不要忘記將文件上傳到節點。

經過ansible 2.7.6測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM