我使用Ansible中的Netapp模块收集数据,然后使用Python Inline Code对该列表应用操作,使用该Python操作尝试在列表中查找特定的字符串值,使用command
模块内联执行Python代码。
---
- hosts: exec-node
collections:
- netapp.ontap
vars_files:
- secretvars.yaml
tasks:
- name: Gather volume info
tags: vol
netapp.ontap.na_ontap_rest_info:
gather_subset:
- storage/volumes
hostname: "nas3.test.com"
username: "{{ username }}"
password: "{{ password }}"
https: true
validate_certs: false
register: result
- debug: var=result['ontap_info']['storage/volumes']['records']
tags: vol
- name: create volume list
tags: vol
set_fact:
volume_list: "{{ volume_list|default([]) + [item.name] }}"
loop: "{{result['ontap_info']['storage/volumes']['records']}}"
- debug: var=volume_list
tags: vol
- name: Python inline code
command: python3
args:
stdin: |
finallist="{{ volume_list }}"
finallist1=[]
for i in finallist:
if i[0:2]=='yz':
finallist1.append(i)
print(finallist1)
register: results
- set_fact:
x: "{{ results.stdout }}"
我期待一个列表(finallist1
)我所需的数据如下。
['yz16', 'yz18', 'yz11', 'yz13', 'yz14', 'yz17', 'yz15', 'yz32']
我的原始列表(finallist
)如下所示:
['yz16', 'yz18', 'yz11', 'yz13', 'yz14', 'yz17', 'yz15', 'yz32', 'test', 'test1']
1条答案
按热度按时间brccelvz1#
只是一些注解和注意事项...不建议使用Python内联代码,除非有强有力和有效的理由。此外,我喜欢建议命名您的变量,如
list_in
或inList
和list_out
或outList
,以便更容易理解它们的用途。finallist
)如下所示:['yz16', 'yz18', 'yz11', 'yz13', 'yz14', 'yz17', 'yz15', 'yz32', 'test', 'test1']
*根据最小的例子,以便调试内部发生的情况
这导致输出
你输入的是字符串而不是列表。
所以,有些假设是不正确的,
if i[0:2] == 'yz'
不可能是true
,这就是为什么你得到一个空列表。至少您需要先强制类型转换
导致输出
要进一步调试,您可以查看
或
类似的Python问答
因此,对于快速原型化、调试和学习目的,这种编码可能是可以的,但它可能会导致易于出错的实现和非幂等行为,难以读取和维护等,并且不应进入生产环境。