Ansible Shell 模块详解
作者:火苗实验室
时间:2026-08-13
转载
介绍 在本实验中,你将学习如何使用 Ansible 的 Shell 模块在远程主机上执行 shell 命令。当现有的 Ansible 模块无法满足你的需求,或者你希望对命令执行过程拥有更高的灵活性和控制时,Shell 模块会非常实用。 执行一个简单的 Shell 命令 在这一步中,你将使
## 介绍
在本实验中,你将学习如何使用 Ansible 的 Shell 模块在远程主机上执行 shell 命令。当现有的 Ansible 模块无法满足你的需求,或者你希望对命令执行过程拥有更高的灵活性和控制时,Shell 模块会非常实用。
## 执行一个简单的 Shell 命令
在这一步中,你将使用 Ansible 的 Shell 模块在远程主机上执行一个简单的 shell 命令。
首先,完成 `/home/labex/project/simple_shell_command.yml` 文件。
在 playbook 文件中添加以下内容:
```yaml
- name: Execute a Simple Shell Command
hosts: localhost
gather_facts: false
tasks:
- name: Execute ls -l command
shell: ls -l
register: command_output
- name: Display command output
debug:
var: command_output.stdout_lines
```
- `hosts: localhost`:表示该 Ansible playbook 的执行目标是 `localhost`。
- `gather_facts: false`:禁用主机事实信息收集。
- `shell: ls -l`:指定要执行的 shell 命令。
总的来说,这个 playbook 的作用是在本地主机上执行 `ls -l` 命令,并将命令输出显示出来。
然后,在 Ansible playbook 中查看命令输出。
```bash
ansible-playbook /home/labex/project/simple_shell_command.yml
```
示例输出:
```bash
[WARNING]: No inventory was parsed, only implicit localhost is a vailable
[WARNING]: provided hosts list is empty, only localhost is a vailable. Note that
the implicit localhost does not match 'all'
PLAY [Execute a Simple Shell Command] ******************************************
TASK [Execute ls -l command] ***************************************************
changed: [localhost]
TASK [Display command output] **************************************************
ok: [localhost] => {
"command_output.stdout_lines": [
"total 16",
"-rwxrwxrwx 1 labex root 285 Mar 8 13:33 complex_shell_commands.yml",
"-rwxrwxrwx 1 labex root 221 Mar 8 13:33 handle_command_failure.yml",
"-rwxrwxrwx 1 labex root 222 Mar 8 13:33 pass_variables.yml",
"-rwxrwxrwx 1 labex root 266 Mar 8 13:36 simple_shell_command.yml"
]
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
这里的 `"command_output.stdout_lines":[...]` 是目标主机上 `ls -l` 命令的输出。
## 向 Shell 命令传递变量
在这一步中,你将学习如何在 Ansible playbook 中向通过 Shell 模块执行的 shell 命令传递变量。
首先,完成 `/home/labex/project/pass_variables.yml` 文件。
在 playbook 文件中加入以下内容:
```yaml
- name: Pass Variables to Shell Commands
hosts: localhost
gather_facts: false
vars:
directory_path: /home/labex
tasks:
- name: Execute ls command with a variable
shell: ls "{{ directory_path }}"
register: variable_command_output
- name: Display variable command output
debug:
var: variable_command_output.stdout_lines
```
- `hosts: localhost`:表示该 Ansible playbook 的目标主机是 `localhost`。
- `vars`:定义了一个名为 `directory_path` 的变量,其值为 `/home/labex`。
- `shell: ls "{{ directory_path }}"`:执行 `ls` 命令,并输出由 `directory_path` 变量指定的目录内容。
总的来说,这个 playbook 会在本地主机上使用表示目录路径的变量(`/home/labex`)执行 `ls` 命令,并显示命令输出。
然后,在 Ansible playbook 中查看命令输出。
```bash
ansible-playbook /home/labex/project/pass_variables.yml
```
示例输出:
```bash
[WARNING]: No inventory was parsed, only implicit localhost is a vailable
[WARNING]: provided hosts list is empty, only localhost is a vailable. Note that
the implicit localhost does not match 'all'
PLAY [Pass Variables to Shell Commands] ****************************************
TASK [Execute ls command with a variable] **************************************
changed: [localhost]
TASK [Display variable command output] *****************************************
ok: [localhost] => {
"variable_command_output.stdout_lines": [
"Code",
"Desktop",
"golang",
"project"
]
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
这里的 `"variable_command_output.stdout_lines":[...]` 是目标主机上 `ls /home/labex` 命令的输出。
## 处理命令失败
在这一步中,你将学习如何在使用 Shell 模块执行 shell 命令时处理命令失败的情况。你将处理 shell 命令返回非零退出状态(表示失败)的情况。
首先,完成 `/home/labex/project/handle_command_failure.yml` 文件。
在 playbook 文件中添加以下内容:
```yaml
- name: Handle Command Failure
hosts: localhost
gather_facts: false
tasks:
- name: Execute a failing command
shell: failing-command
register: failing_command_output
ignore_errors: yes
- name: Handle command failure
debug:
msg: "The command failed. Performing fallback action."
when: failing_command_output.failed
```
- `hosts: localhost`:表示执行此 Ansible playbook 的目标主机是 `localhost`。
- `shell: failing-command`:使用 shell 模块执行 `failing-command` 命令,并将输出保存到 `failing_command_output` 变量中。由于 `failing-command` 不存在,因此该命令会失败。
- `ignore_errors: yes`:指示 Ansible 忽略执行 `failing-command` 时产生的错误,使 playbook 在命令失败后仍可继续运行。
- `debug`:使用 debug 模块输出消息 `"The command failed. Performing fallback action."`。该消息仅在 `failing_command_output.failed` 为真时显示,用于表明前一个命令执行失败。
总的来说,这个 playbook 会先尝试执行一个预期会失败的命令,忽略执行过程中的错误,然后根据命令是否失败显示提示信息,说明已执行回退操作。
然后,在 Ansible playbook 中查看命令输出。
```bash
ansible-playbook /home/labex/project/handle_command_failure.yml
```
示例输出:
```bash
[WARNING]: No inventory was parsed, only implicit localhost is a vailable
[WARNING]: provided hosts list is empty, only localhost is a vailable. Note that
the implicit localhost does not match 'all'
PLAY [Handle Command Failure] **************************************************
TASK [Execute a failing command] ***********************************************
fatal: [localhost]: FAILED! => {"changed": true, "cmd": "failing-command", "delta": "0:00:00.009169", "end": "2024-03-08 13:46:22.701946", "msg": "non-zero return code", "rc": 127, "start": "2024-03-08 13:46:22.692777", "stderr": "/bin/sh: line 1: failing-command: command not found", "stderr_lines": ["/bin/sh: line 1: failing-command: command not found"], "stdout": "", "stdout_lines": []}
...ignoring
TASK [Handle command failure] **************************************************
ok: [localhost] => {
"msg": "The command failed. Performing fallback action."
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
```
`"msg": "The command failed. Performing fallback action."` 的存在表明 `failing-command` 执行失败。
## 执行复杂的 Shell 命令
在这一步中,你将使用 Shell 模块执行更复杂的 shell 命令。你将了解命令重定向、管道以及复杂命令结构的用法。
首先,完成 `/home/labex/project/complex_shell_commands.yml` 文件。
在 playbook 文件中添加以下内容:
```yaml
- name: Execute Complex Shell Commands
hosts: localhost
gather_facts: false
tasks:
- name: Execute complex command
shell: ls -l /home/labex | grep 'project' > /home/labex/output.txt
register: complex_command_output
- name: Display complex command output
debug:
var: complex_command_output.stdout_lines
```
- `hosts: localhost`:表示执行此 Ansible playbook 的目标主机是 `localhost`。
- `shell`:将 `ls -l /home/labex` 的输出重定向到 `/home/labex/output.txt` 文件,并使用 `grep` 过滤与 `project` 相关的内容。
总的来说,这个 playbook 会在本地主机上执行一个复杂的 shell 命令,对输出进行过滤并重定向到文件,然后显示命令执行结果。
然后,执行 Ansible playbook 命令。
```bash
ansible-playbook /home/labex/project/complex_shell_commands.yml
```
示例输出:
```bash
[WARNING]: No inventory was parsed, only implicit localhost is a vailable
[WARNING]: provided hosts list is empty, only localhost is a vailable. Note that
the implicit localhost does not match 'all'
PLAY [Execute Complex Shell Commands] ******************************************
TASK [Execute complex command] *************************************************
changed: [localhost]
TASK [Display complex command output] ******************************************
ok: [localhost] => {
"complex_command_output.stdout_lines": []
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
最后,查看 `/home/labex/output.txt` 文件内容:
```bash
cat /home/labex/output.txt
```
示例输出:
```bash
drwxr-xr-x 1 labex labex 4096 Mar 8 13:49 project
```
## 总结
恭喜!你已经成功完成了 Ansible Shell 模块实验。你学会了如何使用 Shell 模块在远程主机上执行 shell 命令、向命令传递变量、处理命令失败以及执行复杂的 shell 命令。
Shell 模块为你在 Ansible playbook 中执行 shell 命令提供了极高的灵活性和控制力。不过,使用时也要格外谨慎,因为执行任意 shell 命令可能带来安全风险。请务必确认命令来源可靠,并对任何用户输入进行清理。
现在你已经对 Shell 模块有了较好的理解,可以利用它来完成各种自动化任务,并高效管理远程主机。祝你编写 Ansible 脚本愉快!
游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。
Win10专业版U盘安装教程:制作启动盘与完整安装步骤
本文提供Win10专业版U盘安装完整流程:准备8GB以上U盘与官方镜像,制作启动盘并核对盘符;通过F12 F11 Esc等快捷键或BIOS设置U盘为第一启动项;安装时选择专业版并谨慎分区;完成后在“设置—系统—关于”验证版本与激活状态。操作前务必备份数据。
Windows10系统字体太小怎么调大
Windows10系统字体太小怎么调大?只需两步:首先打开设置中的显示选项,将缩放比例调整为125%或150%;随后运行ClearType文本调谐器优化字体清晰度。此方法适用于高分屏及普通屏幕,无需修改注册表即可解决界面拥挤问题。
Win10磁盘占用100%基础排查:从监控到清理的完整步骤
Windows 10系统出现磁盘占用100%会导致电脑卡顿、程序响应缓慢。本文提供基础排查方案:首先通过任务管理器确认是否为磁盘高负载,随后进入系统存储页面分析C盘占用类别,最后针对性清理临时文件。遵循此流程可有效缓解磁盘压力,避免盲目重装系统。
Windows10系统怎么显示此电脑和控制面板
Windows10默认可能不显示桌面图标,导致找不到“此电脑”和“控制面板”。只需进入个性化设置,在“桌面图标设置”中勾选对应选项即可恢复。本文提供详细图文步骤,帮助快速找回系统入口。