我无法通过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)
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('')
我的Ansible脚本是
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'] }}
我必须使用2.3版本的ansible,目前我使用的是2.7版本的py
答案 0 :(得分:0)
Q:“从Py脚本向Ansible传递变量”
A:可以使用查找,管道,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 }}]"
给予
ok: [localhost] =>
my_var:
AppName: my_AppName
Host: my_Host
SealID: my_SealID
ok: [localhost] =>
msg: AppName [my_AppName]
Q:“ Ansible 2.3没有
lookup
插件。替代方法是什么?”
A:可以注册脚本的输出,并 combine 字典 with_items 。例如,下面的播放给出相同的结果
- 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 }}]"
注释
没有变量modules
。这可能是错误
- debug:
msg: "{{ result.stdout_lines }}"
with_items: "{{ modules }}"
注册的输出应该简单地打印
- debug:
msg: "{{ result.stdout_lines }}"