ansible 执行top命令

在Ansible中执行
top
命令可以通过多种方式实现,这里提供两种常见的方法:
方法1: 使用
command
模块
Ansible的
command
模块可以用来在远程主机上执行任何命令。要执行
top
命令,你可以编写一个Playbook,如下所示:
—
– name: Execute top command
hosts: your_target_hosts
tasks:
– name: Run top command
command: top -b -n 1
register: top_output

– name: Show top output
debug:
msg: “{{ top_output.stdout }}”
这里的
-b
选项表示批处理模式,
-n 1
表示只运行一次
top
命令。
register
关键字用于将命令的输出存储在变量
top_output
中,然后使用
debug
模块打印出来。
方法2: 使用
shell
模块
shell
模块与
command
模块类似,但允许你执行复杂的shell命令。使用
shell
模块执行
top
命令的Playbook如下:
—
– name: Execute top command
hosts: your_target_hosts
tasks:
– name: Run top command
shell: top -b -n 1
register: top_output

– name: Show top output
debug:
msg: “{{ top_output.stdout }}”
注意事项
权限
:确保执行Ansible的账户在目标主机上有足够的权限执行
top
命令。
输出处理
:
top
命令通常用于交互式查看系统资源使用情况,输出可能非常长。在自动化脚本中使用时,通常需要限制输出(如上例中的
-n 1
)。
目标主机
:替换
your_target_hosts
为你想要执行命令的主机或主机组。
这两种方法都可以有效地在远程主机上执行
top
命令,并通过Ansible的Playbook进行管理。