Python 从Py脚本向Ansible传递变量
我无法在ansible中传递变量 这是我的python脚本Python 从Py脚本向Ansible传递变量,python,json,python-2.7,variables,ansible,Python,Json,Python 2.7,Variables,Ansible,我无法在ansible中传递变量 这是我的python脚本 import csv import json data= file = 'splunkapps.csv' json_file = 'output_file_name.json' def read_CSV(file, json_file): csv_rows = [] with open(file) as csvfile: reader = csv.DictReader(csvfile)
import csv
import json
data=
file = 'splunkapps.csv'
json_file = 'output_file_name.json'
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
convert_write_json(csv_rows, json_file)
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')))
read_CSV(file,json_file)
with open('output_file_name.json') as json_file:
data = json.load(json_file)
for p in data:
print('AppName: ' + p['AppName'])
print('Host: ' + p['Host'])
print('SealID: ' + p['SealID'])
print('')
我的脚本是
Yaml文件:
---
- name: Onboard app
hosts: localhost
gather_facts: false
tasks:
- name:
script: spl.py
register: result
- debug:
msg: "{{ result.stdout_lines }}"
with_items: "{{ modules }}"
- name: print user name and password
shell: |
echo {{ modules['AppName'] }}
echo {{ modules['Host'] }}
我必须使用ansible的2.3版本,目前我正在使用py的2.7版本
Q:“从Py脚本向Ansible传递变量”
答:可以使用lookup、pipe、from_yaml并将脚本的输出分配给变量。例如脚本
$ cat my_script
#!/bin/sh
printf 'AppName: my_AppName\n'
printf 'Host: my_Host\n'
printf 'SealID: my_SealID\n'
剧本
- hosts: localhost
vars:
my_var: "{{ lookup('pipe', 'my_script')|from_yaml }}"
tasks:
- debug:
var: my_var
- debug:
msg: "AppName [{{ my_var.AppName }}]"
给予
问:“Ansible 2.3没有
查找
插件。有什么替代方法?”
答:可以注册脚本的输出,并将字典与_项相结合。例如,下面的剧本给出了相同的结果
- hosts: localhost
tasks:
- script: my_script
register: result
- set_fact:
my_var: "{{ my_var|default({})|combine(item|from_yaml) }}"
with_items: "{{ result.stdout_lines }}"
- debug:
var: my_var
- debug:
msg: "AppName [{{ my_var.AppName }}]"
注释 没有变量
模块
。这可能就是错误所在
- debug:
msg: "{{ result.stdout_lines }}"
with_items: "{{ modules }}"
注册输出应简单打印
- debug:
msg: "{{ result.stdout_lines }}"
我仍在尝试,2.3没有查找插件这将是什么替代方法?如果不是脚本,则直接从远程服务器中的json、csv或txt传递变量。我有10-30个应用程序名,所以我很难完成这项任务。可以“合并”已注册的行。我已更新了答案。致命:[localhost]:失败!=>{“failed”:true,“msg”:“在可用的查找插件中查找名为{{result.stdout_lines}}}的查找时发生意外故障”。此错误可能导致Ansible 2.5中引入的
循环
指令。我已将其更改为带有\u项的。仅供参考,Ansible的政策是支持最后3个版本。目前是2.9、2.8和2.7。非常感谢!!我在这件事上耽搁了好几天。它在本地主机上运行得非常好。但是当我在远程主机上做同样的操作时,为什么会出现错误,有什么想法吗?我可以从远程服务器获取我的_脚本并传递变量吗?
- debug:
msg: "{{ result.stdout_lines }}"