Ansible传JSON至Python脚本出现JSON解码错误求助
解决Ansible传递JSON到Python脚本的解码错误
问题原因
通过command模块的命令行字符串传递JSON时,Shell会解析字符串中的引号与转义字符,导致Python脚本接收到的JSON格式被破坏。比如Ansible生成的转义双引号\"会被Shell解析为普通双引号,甚至可能导致JSON结构被截断,最终触发JSONDecodeError。
解决方案
方案1:使用argv参数传递(推荐,最可靠)
改用command模块的argv参数传递参数列表,绕过Shell的参数解析,确保每个参数原样传递给Python脚本:
- name: Insert data into DynamoDB for client "{{ client_name }}" command: argv: - python3 - dynamodb_insert_or_update.py - "{{ dynamodb_table_name }}" - "{{ client_name }}" - "{{ applicationID }}" - "{{ new_attributes | to_json }}" - "{{ aws_region }}" - "{{ aws_profile }}" args: chdir: "/mypath/scripts/" register: result loop: "{{ clients }}" loop_control: loop_var: item
方案2:通过环境变量传递JSON
将JSON放入环境变量,避免命令行参数的解析问题:
修改Ansible任务:
- name: Insert data into DynamoDB for client "{{ client_name }}" command: python3 dynamodb_insert_or_update.py "{{ dynamodb_table_name }}" "{{ client_name }}" "{{ applicationID }}" "{{ aws_region }}" "{{ aws_profile }}" args: chdir: "/mypath/scripts/" environment: NEW_ATTRIBUTES: "{{ new_attributes | to_json }}" register: result loop: "{{ clients }}" loop_control: loop_var: item
修改Python脚本:
替换原有的new_attributes = sys.argv[4]部分:
import os # 从环境变量读取JSON new_attributes = os.environ.get('NEW_ATTRIBUTES') if not new_attributes: print("Error: NEW_ATTRIBUTES environment variable not set") sys.exit(1)
方案3:使用quote过滤器转义(不推荐,易出错)
如果坚持使用命令行字符串拼接,用Ansible的quote过滤器对JSON进行额外转义,避免Shell解析破坏结构:
- name: Insert data into DynamoDB for client "{{ client_name }}" shell: > python3 dynamodb_insert_or_update.py "{{ dynamodb_table_name }}" "{{ client_name }}" "{{ applicationID }}" {{ new_attributes | to_json | quote }} "{{ aws_region }}" "{{ aws_profile }}" args: chdir: "/mypath/scripts/" register: result loop: "{{ clients }}" loop_control: loop_var: item
验证方法
可以在Python脚本的json.loads之前添加打印语句,确认接收到的内容是否正确:
print(f"Received raw new_attributes: {repr(new_attributes)}") try: new_attributes = json.loads(new_attributes) except json.JSONDecodeError as e: print(f"Error decoding JSON: {e}") sys.exit(1)
内容的提问来源于stack exchange,提问作者Talktomegoose
相关产品推荐
相关产品推荐

