【问题标题】:Run python scripts multiple times through Ansible playbook with command line arguments使用命令行参数通过 Ansible playbook 多次运行 python 脚本
【发布时间】:2018-06-24 13:29:59
【问题描述】:

我试图通过我的Ansible playbook 多次运行 Python 脚本,使用 with_items 在每次迭代时采用不同的命令行参数,但即使它遍历循环以为生成的文件采用不同的名称,但是文件内容保持不变:即只显示"show version" NX-OS的命令输出内容。

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

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

tasks/main.yml

---
- 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

---
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

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)

【问题讨论】:

    标签: python ansible yaml command-line-arguments


    【解决方案1】:

    你循环错了。当你有...

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

    ...您正在查看 commands 变量。这意味着output 总是指的是同一件事。看看using register in a loop上的文档:

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

    你实际上想循环遍历output.results,例如:

    - 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 指的是你的 first 中的循环值 循环(循环commands 变量)。我在做一些 这里的假设;我实际上不知道每个的结构是什么 output.results 中的项目看起来像因为您没有发布输出 你的debug 任务。我假装属性item.stdout 具有您感兴趣的值,但它可能已命名 别的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      相关资源
      最近更新 更多