簡體   English   中英

在同一 ansible 輸出中將 json 字符串傳遞給 python 劇本

[英]pass json string from ansible ouput to python in the same ansible playbook

我有 2 個腳本a.pyb.py

我有一個運行a.pyb.py的 ansible 劇本。 這是a.py的腳本Output提供給b.py 問題是a.pya.py是一個可以被索引的列表,但是每當我將 yaml 的stdout作為命令行參數傳遞給b.py時,它都采用str object 並且它可以像以前一樣被索引,即像a.py的.

腳本 a.py

a = [{
        "name": "jack",
        "date": "Jan-06-2021",
        "age": "24",
    },
    {
        "name": "jack1",
        "date": "Jan-07-2021",
        "age": "25",
    },
]
print(a)

b.py 腳本

import sys
import json
random_variable = sys.argv[1] 
print(json.loads(random_variable)) # tried this no use

我想解析a的值,就像random_variab.e[0]random_variable[1]
random_variable[0]可能像:

{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}
- name: testing
  gather_facts: True
  hosts: localhost
  tasks:

    - name: run python script
      command: python3 /test-repo/test_python/a.py
      register: result
    - set_fact:
        var1: "{{result.stdout}}"
    - debug: 
        msg: "{{var1}}"
    
    - name: run python script2
      command: python3 /test-repo/test_python/b.py {{var1}}
      register: result
    - debug: 
        msg: "{{result}}"

我現在遇到的錯誤

["Traceback (most recent call last):", "  File \"/test-repo/test_python/b.py\", line 4, in <module>", "    print(json.loads(a))", "  File \"/usr/lib64/python3.6/json/__init__.py\", line 354, in loads", "    return _default_decoder.decode(s)", " 
 File \"/usr/lib64/python3.6/json/decoder.py\", line 339, in decode", "    obj, end = self.raw_decode(s, idx=_w(s, 0).end())", "  File 
\"/usr/lib64/python3.6/json/decoder.py\", line 355, in raw_decode", "    obj, end = self.scan_once(s, idx)", "json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)"]

打印時預期 output

random_variable = sys.argv[1]
print(random_variable[0])

Output 我需要

{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}

您的問題並非來自b.py ,就像您認為的那樣。

實際上是因為a.py沒有打印 JSON,而是打印 python 字典,因此,您不能將其作為 Z0ECD11C1D7A287401D148A23BBD7A2F8 重新加載到b.py中。

在 playbook 中調試a.py的結果會給你:

[{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}, {'name': 'jack1', 'date': 'Jan-07-2021', 'age': '25'}]

但這不是有效的 JSON 數組,因為正如錯誤消息向您提示的那樣,JSON 中的字符串和屬性必須用雙引號而不是簡單的引號括起來。

因此,您至少應該做兩件事:

  1. 調整a.py並使其讀取
    import json a = [{ "name": "jack", "date": "Jan-06-2021", "age": "24", }, { "name": "jack1", "date": "Jan-07-2021", "age": "25", }, ] print(json.dumps(a))
  2. 調整您的劇本並將您的 JSON 字符串用簡單的引號引起來,以免破壞 shell:
     - command: python3 /test-repo/test_python/b.py '{{ var1 }}'

這就是說,我也會進行這種調整:在您的 Python 腳本中使用適當的shebang ,因此您不必再在command任務上指定解釋器。

所以a.py變成:

#!/usr/bin/env python3
import json
a = [{
        "name": "jack",
        "date": "Jan-06-2021",
        "age": "24",
    },
    {
        "name": "jack1",
        "date": "Jan-07-2021",
        "age": "25",
    },
]
print(json.dumps(a))

b.py變成:

#!/usr/bin/env python3
import sys
import json
print(json.loads(sys.argv[1])[0])

你的劇本變成:

- hosts: all
  gather_facts: yes

  tasks:
    - command: /test-repo/test_python/a.py
      register: result

    - debug: 
        var: result.stdout
    
    - command: /test-repo/test_python/b.py '{{ result.stdout }}'
      register: result

    - debug: 
        var: result.stdout

所有這些都產生了回顧:

PLAY [all] **********************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]

TASK [command] ******************************************************************************************************
changed: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => {
    "result.stdout": [
        {
            "age": "24",
            "date": "Jan-06-2021",
            "name": "jack"
        },
        {
            "age": "25",
            "date": "Jan-07-2021",
            "name": "jack1"
        }
    ]
}

TASK [command] ******************************************************************************************************
changed: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => {
    "result.stdout": {
        "age": "24",
        "date": "Jan-06-2021",
        "name": "jack"
    }
}

PLAY RECAP **********************************************************************************************************
localhost                  : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

暫無
暫無

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

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