如何将Ansible Playbook中的变量传递给Python脚本
Ansible Playbook变量传递给Python脚本的可行方案
Ansible的script模块默认不会将Playbook内定义的变量自动注入外部脚本的运行上下文,以下是三种可直接落地的实现方式:
方法1:命令行参数传递(最简单,适合少量非敏感变量)
修改Playbook中执行脚本的任务,将变量序列化为JSON字符串作为参数传入,避免列表、字典类复杂结构传值失真:
--- - hosts: localhost gather_facts: false vars: numbers: - 1 - 2 tasks: - name: Run Python Script script: pythontest.py "{{ numbers | to_json }}" register: output - debug: var: output
修改Python脚本,通过sys.argv读取传入的参数并反序列化:
#!/usr/bin/python3.6 import sys import json print('hello world') numbers = json.loads(sys.argv[1]) print(numbers)
方法2:环境变量传递(适合敏感变量、不想参数暴露在进程列表的场景)
Playbook中通过environment关键字给脚本挂载自定义环境变量:
- name: Run Python Script script: pythontest.py environment: PY_NUMBERS: "{{ numbers | to_json }}" register: output
Python脚本从环境变量读取值即可:
#!/usr/bin/python3.6 import os import json print('hello world') numbers = json.loads(os.environ['PY_NUMBERS']) print(numbers)
方法3:模板渲染后执行(适合变量多、脚本逻辑复杂的场景)
先将Python脚本存为Jinja2模板文件pythontest.py.j2,直接在模板内引用Ansible变量:
#!/usr/bin/python3.6 print('hello world') numbers = {{ numbers | to_json }} print(numbers)
在Playbook中先渲染模板为可执行脚本,再运行:
tasks: - name: Render Python script from template template: src: pythontest.py.j2 dest: /tmp/pythontest.py mode: '0755' - name: Run rendered Python script command: /tmp/pythontest.py register: output - debug: var: output
注意:传递列表、字典等非字符串类型变量时,必须先通过
to_json过滤器序列化为字符串,否则Python侧拿到的会是Ansible拼接的字符串格式,无法直接解析为原生数据结构。
内容的提问来源于stack exchange,提问作者NB art
相关产品推荐
相关产品推荐

