使用cli_command模块通过 ansible 在特定交换机端口接口上发送关闭命令



这是我的_main.yml _


---
- name: run show version on switch
cli_command:
command: show version
register: show
- name: print command output
debug: var=show.stdout_lines[0]
- name: Shutdown TOR-A port
cli_command:
command: "{{ item }}"
register: command_output
with_items:
- "config"
- "interface Tengigabitethernet 0/35"
- "shutdown"
- name: Debug command output
debug:
msg: "{{ command_output }}"

如何访问同一交换机上的端口 36、7、8 等,并按顺序关闭上述交换机端口?

我必须对另一个交换机 TOR-B 重复相同的活动,任务应该是相同的。但是,我不确定如何在一个yaml文件中动态实现目标。任何帮助将不胜感激!

交换机凭据保存在主机文件中

以下内容基本上应该可以完成这项工作(注意:我没有任何与cli兼容的开关进行测试(。

创建包含以下内容的shutdown_ports.yml文件。此文件可以位于 playbook 的同一级别,也可以位于角色tasks文件夹中(如果从那里包含它(。

---
- name: "shutdown port"
cli_command:
command: "{{ item }}"
with_items:
- "interface Tengigabitethernet 0/{{ port }}"
- "shutdown"

将该文件用作循环中的包含,如以下剧本示例所示

---
- name: shutdown same ports on all switches
hosts: group_containing_my_switches
vars:
shutdown_ports:
- 35
- 36
- 7
- 8
tasks:
- name: switch to config mode
cli_command:
command: config
- name: shutdown all referenced ports
include_tasks: shutdown_ports.yml
loop: "{{ shutdown_ports }}"
loop_control:
loop_var: port

另一种可能的解决方案是动态创建一个数组,其中包含所有命令,以在循环中发送和播放所有这些命令。再次示例剧本

---
- name: shutdown same ports on all switches
hosts: group_containing_my_switches
vars:
shutdown_ports:
- 35
- 36
- 7
- 8

tasks:
- name: Add config mode as first command
set_fact:
cli_switch_commands:
- config
- name: Add commands for each port shutdown
vars:
current_port_command: "interface Tengigabitethernet 0/{{ item }}"
set_fact:
cli_switch_commands: "{{ cli_switch_commands + [current_port_command, 'shutdown'] }}"
loop: "{{ shutdown_ports }}"
- name: Send all commands to switch
cli_command:
command: "{{ item }}"
loop: "{{ cli_switch_commands }}"

最新更新