首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过带有命令行参数的Ansible剧本多次运行python脚本

通过带有命令行参数的Ansible剧本多次运行python脚本
EN

Stack Overflow用户
提问于 2018-06-24 13:29:59
回答 1查看 3.4K关注 0票数 1

我尝试在Ansible剧本中多次运行Python,使用with_items在每次迭代中使用不同的命令行参数,但是即使它在循环中迭代生成的文件的名称不同,但是文件的内容保持不变:也就是说,它只显示"show version" NX-OS命令输出的内容。

我如何迭代来自上一个任务的{{ output }}

上下文: Cisco Nexus 3k交换机上的NX-OS CLI命令

tasks/main.yml

代码语言:javascript
复制
---
- name: Run basic CLI commands on nexus 3k switch
  nxos_command: 
      provider: "{{ nxos_provider }}"
      commands: "{{ item.cmd1 }}"
  with_items: "{{ commands }}"
  register: output
- debug: var=output

- name: Run python script and store command output
  command: python /users/aastha/play/script.py  {{ item.name1 }}  {{ output }}
  with_items: "{{ commands }}"

vars/main.yml

代码语言:javascript
复制
---
nxos_provider:
   host: "{{ inventory_hostname }}"
   username: "{{ un }}"
   password: "{{ pwd }}"
   transport: nxapi
   timeout: 500

commands:
   - cmd1: show version
     name1: pre-show-version

   - cmd1: show interface brief
     name1: pre-interface

script.py

代码语言:javascript
复制
import json
import sys

arg = sys.argv[2:]
print(arg)
aas='\n'.join(map(str, arg))
print aas
with open(sys.argv[1], 'w') as outfile:
     outfile.write(aas)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-24 14:00:29

你在重复错误的事情。当你有..。

代码语言:javascript
复制
- name: Run python script and store command output
  command: python /users/aastha/play/script.py  {{ item.name1 }}  {{ output }}
  with_items: "{{ commands }}"

.你在检查commands变量这意味着output总是指同样的东西。看一下关于 in a loop的文档

在使用带循环的寄存器之后,放置在变量中的数据结构将包含一个结果属性,它是来自模块的所有响应的列表。

实际上,您希望在output.results上循环,例如:

代码语言:javascript
复制
- name: Run python script and store command output
  command: python /users/aastha/play/script.py  {{ item.item.name1 }}  {{ item.stdout }}
  with_items: "{{ output.results }}"

在上面的代码中,item.item引用了第一个循环中的循环值(在commands变量上的循环)。我在这里做了一些假设;实际上我不知道output.results中每个项目的结构是什么样子的,因为您没有发布debug任务的输出。我假装属性item.stdout具有您感兴趣的值,但是它可能被命名为其他东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51010392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档