Ansible Command 模块
发布于2026-08-13 阅读(0)
{"position":0,"title":"介绍","layout":"doc-fullscreen","text":"## 介绍nn在本实验中,你将探索 Ansible 的 Command 模块,这是一个用于在远程主机上执行命令的强大工具。Command 模块允许你直接从 Ansible playbook 和任务中与命令行进行交互,为管理远程系统提供了一种多功能的方式。在本实验中,你将学习如何使用 Ansible Command 模块执行各种命令、处理变量和参数,并捕获命令输出。n","need_verify":false,"has_solution":false},{"position":1,"title":"创建一个简单的 Ansible Playbook","layout":"doc-workbench-split","text":"## 创建一个简单的 Ansible Playbooknn在这一步中,你将使用 Command 模块创建你的第一个 Ansible playbook,以执行一个简单的命令。nn首先,导航到项目目录:nn```bashncd ~/projectn```nn接下来,使用你选择的文本编辑器创建一个名为 `simple_command.yml` 的新文件。例如,你可以使用 `nano` 编辑器:nn```bashnnano simple_command.ymln```nn将以下内容添加到文件中:nn```ymln---n- name: Execute a simple commandn hosts: localhostn tasks:n - name: Run 'ls' commandn command: ls -ln```nn让我们分解一下这个 playbook:nn- `hosts: localhost` 行指定 playbook 将在本地机器上运行。n- `tasks` 部分包含要执行的任务列表。n- `command: ls -l` 行使用 Command 模块运行 `ls -l` 命令,该命令以长格式列出文件和目录。nn保存文件并退出编辑器(在 nano 中,按 Ctrl+X,然后按 Y,最后按 Enter)。nn现在,使用以下命令运行 playbook:nn```bashnansible-playbook simple_command.ymln```nn你应该会看到类似以下的输出:nn```nPLAY [Execute a simple command] ************************************************nnTASK [Gathering Facts] *********************************************************nok: [localhost]nnTASK [Run 'ls' command] ********************************************************nchanged: [localhost]nnPLAY RECAP *********************************************************************nlocalhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0n```nn此输出表明 playbook 成功运行,并在你的本地机器上执行了 `ls -l` 命令。n","need_verify":true,"has_solution":false},{"position":2,"title":"在 Command 模块中使用变量","layout":"doc-workbench-split","text":"## 在 Command 模块中使用变量nn在这一步中,你将学习如何在 Ansible Command 模块中使用变量。变量可以让你的 playbook 更加灵活和可重用。nn创建一个名为 `variable_command.yml` 的新文件:nn```bashnnano variable_command.ymln```nn将以下内容添加到文件中:nn```ymln---n- name: Use variables with the Command modulen hosts: localhostn vars:n file_path: /etc/passwdn line_count: 5n tasks:n - name: Display the last few lines of a filen command: "tail -n {{ line_count }} {{ file_path }}"n register: command_outputnn - name: Show the command outputn debug:n var: command_output.stdout_linesn```nn这个 playbook 引入了几个新概念:nn- `vars` 部分定义了可以在整个 playbook 中使用的变量。n- 我们使用 `{{ variable_name }}` 语法在命令中引用变量。n- `register` 关键字将命令的输出保存到名为 `command_output` 的变量中。n- `debug` 模块用于显示 `command_output` 变量的内容。nn保存文件并退出编辑器。nn现在,运行 playbook:nn```bashnansible-playbook variable_command.ymln```nn你应该会看到类似以下的输出:nn```nPLAY [Use variables with the Command module] ***********************************nnTASK [Gathering Facts] *********************************************************nok: [localhost]nnTASK [Display the last few lines of a file] ************************************nchanged: [localhost]nnTASK [Show the command output] *************************************************nok: [localhost] => {n "command_output.stdout_lines": [n "games:x:5:60:games:/usr/games:/usr/sbin/nologin",n "man:x:6:12:man:/var/cache/man:/usr/sbin/nologin",n "lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin",n "mail:x:8:8:mail:/var/mail:/usr/sbin/nologin",n "news:x:9:9:news:/var/spool/news:/usr/sbin/nologin"n ]n}nnPLAY RECAP *********************************************************************nlocalhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0n```nn此输出显示了 `/etc/passwd` 文件的最后 5 行,展示了如何在 Command 模块中使用变量。n","need_verify":true,"has_solution":false},{"position":3,"title":"捕获并处理命令输出","layout":"doc-workbench-split","text":"## 捕获并处理命令输出nn在这一步中,你将学习如何捕获命令的输出并使用 Ansible 进一步处理它。nn创建一个名为 `process_output.yml` 的新文件:nn```bashnnano process_output.ymln```nn将以下内容添加到文件中:nn```ymln---n- name: Capture and process command outputn hosts: localhostn tasks:n - name: Get disk usage informationn command: df -hn register: df_outputnn - name: Display all partitionsn debug:n msg: "{{ df_output.stdout_lines }}"nn - name: Find root partitionn set_fact:n root_partition: "{{ df_output.stdout_lines | select('match', '\\s+/$') | first | default('') }}"nn - name: Display root partition informationn debug:n msg: "Root partition: {{ root_partition }}"n when: root_partition != ''nn - name: Extract usage percentagen set_fact:n root_usage: "{{ root_partition.split()[-2].rstrip('%') | int }}"n when: root_partition != ''nn - name: Display root partition usagen debug:n msg: "Root partition is {{ root_usage }}% full"n when: root_partition != ''nn - name: Check if root partition is over 80% fulln fail:n msg: "Warning: Root partition is over 80% full!"n when: root_partition != '' and root_usage > 80nn - name: Display message if root partition not foundn debug:n msg: "Root partition (/) not found in df output"n when: root_partition == ''n```nn这个 playbook 更加健壮,能够处理根分区可能不易检测到的情况:nn- 我们显示所有分区以查看可用的内容。n- 我们使用更灵活的模式来查找根分区。n- 我们添加了检查以处理未找到根分区的情况。n- 我们使用 `default('')` 过滤器来避免在未找到根分区时出现错误。nn保存文件并退出编辑器。nn现在,运行 playbook:nn```bashnansible-playbook process_output.ymln```nn你应该会看到类似以下的输出:nn```nPLAY [Capture and process command output] ************************************************nnTASK [Gathering Facts] *******************************************************************nok: [localhost]nnTASK [Get disk usage information] ********************************************************nchanged: [localhost]nnTASK [Display all partitions] ************************************************************nok: [localhost] => {n "msg": [n "Filesystem Size Used A vail Use% Mounted on",n "overlay 20G 618M 20G 4% /",n "tmpfs 64M 0 64M 0% /dev",n "tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup",n "shm 64M 128K 64M 1% /dev/shm",n "/dev/vdb 100G 17G 84G 17% /etc/hosts"n ]n}nnTASK [Find root partition] ***************************************************************nok: [localhost]nnTASK [Display root partition information] ************************************************nskipping: [localhost]nnTASK [Extract usage percentage] **********************************************************nskipping: [localhost]nnTASK [Display root partition usage] ******************************************************nskipping: [localhost]nnTASK [Check if root partition is over 80% full] ******************************************nskipping: [localhost]nnTASK [Display message if root partition not found] ***************************************nok: [localhost] => {n "msg": "Root partition (/) not found in df output"n}nnPLAY RECAP *******************************************************************************nlocalhost : ok=7 changed=1 unreachable=0 failed=1 skipped=1 rescued=0 ignored=0n```nn此输出显示了所有分区,识别了根分区,并检查了其使用情况。实际值可能因你的系统而异。n","need_verify":true,"has_solution":false},{"position":4,"title":"使用 Command 模块选项","layout":"doc-workbench-split","text":"## 使用 Command 模块选项nn在这一步中,你将探索 Ansible Command 模块的一些可用选项,以控制其行为。nn创建一个名为 `command_options.yml` 的新文件:nn```bashnnano command_options.ymln```nn将以下内容添加到文件中:nn```ymln---n- name: Explore Command module optionsn hosts: localhostn tasks:n - name: Run a command with a specific working directoryn command: pwdn args:n chdir: /tmpnn - name: Run a command with environment variablesn command: echo $MY_VARn environment:n MY_VAR: "Hello from Ansible"nn - name: Run a command and ignore errorsn command: ls /nonexistent_directoryn ignore_errors: yesnn - name: Run a command with a timeoutn command: sleep 2n async: 5n poll: 0n register: sleep_resultnn - name: Check sleep command statusn async_status:n jid: "{{ sleep_result.ansible_job_id }}"n register: job_resultn until: job_result.finishedn retries: 5n delay: 1n```nn这个 playbook 展示了 Command 模块的各种选项:nn- `chdir`:在执行命令之前更改工作目录。n- `environment`:为命令设置环境变量。n- `ignore_errors`:即使命令失败,也继续执行 playbook。n- `async` 和 `poll`:以异步方式运行命令并设置超时。nn保存文件并退出编辑器。nn现在,运行 playbook:nn```bashnansible-playbook command_options.ymln```nn你应该会看到类似以下的输出:nn```nPPLAY [Explore Command module options]nnTASK [Gathering Facts]nok: [localhost]nnTASK [Run a command with a specific working directory]nchanged: [localhost]nnTASK [Run a command with environment variables]nchanged: [localhost]nnTASK [Run a command and ignore errors]nfatal: [localhost]: FAILED! => {"changed": true, "cmd": ["ls", "/nonexistent_directory"], "delta": "0:00:00.006113", "end": "2024-09-06 09:40:43.373350", "msg": "non-zero return code", "rc": 2, "start": "2024-09-06 09:40:43.367237", "stderr": "ls: cannot access '/nonexistent_directory': No such file or directory", "stderr_lines": ["ls: cannot access '/nonexistent_directory': No such file or directory"], "stdout": "", "stdout_lines": []}n...ignoringnnTASK [Run a command with a timeout]nchanged: [localhost]nnTASK [Check sleep command status]nFAILED - RETRYING: Check sleep command status (10 retries left).nFAILED - RETRYING: Check sleep command status (9 retries left).nFAILED - RETRYING: Check sleep command status (8 retries left).nFAILED - RETRYING: Check sleep command status (7 retries left).nFAILED - RETRYING: Check sleep command status (6 retries left).nFAILED - RETRYING: Check sleep command status (5 retries left).nFAILED - RETRYING: Check sleep command status (4 retries left).nFAILED - RETRYING: Check sleep command status (3 retries left).nFAILED - RETRYING: Check sleep command status (2 retries left).nFAILED - RETRYING: Check sleep command status (1 retries left).nfatal: [localhost]: FAILED! => {"ansible_job_id": "5877920468.2517", "attempts": 10, "changed": false, "finished": 0, "started": 1}nnPLAY RECAPn```nn此输出展示了我们探索的 Command 模块选项的不同行为。n","need_verify":true,"has_solution":false},{"position":5,"title":"在 Docker 友好场景中使用 Command 模块","layout":"doc-workbench-split","text":"## 在 Docker 友好场景中使用 Command 模块nn在这最后一步中,你将在一个更贴近实际的 Docker 友好场景中使用 Ansible Command 模块:检查 SSH 服务的状态并在必要时管理它。nn创建一个名为 `check_service_docker.yml` 的新文件:nn```bashnnano check_service_docker.ymln```nn将以下内容添加到文件中:nn```ymln---n- name: Check and manage SSH service in Dockern hosts: localhostn become: yes ## 这允许 Ansible 使用 sudon tasks:
- name: Check SSH service status
command: service ssh status
register: ssh_status
ignore_errors: yes
- name: Display SSH service status
debug:
msg: "SSH service status: {{ ssh_status.stdout }}"
- name: Start SSH service if not running
command: service ssh start
when: ssh_status.rc != 0
- name: Verify SSH service is running
command: service ssh status
register: ssh_status_after
- name: Display final SSH service status
debug:
msg: "SSH service status is now: {{ ssh_status_after.stdout }}"
- name: Check if SSH port is listening
command: netstat -tuln | grep :22
register: ssh_port_check
ignore_errors: yes
- name: Display SSH port status
debug:
msg: "SSH port 22 is {{ 'open' if ssh_port_check.rc == 0 else 'closed' }}"。
这个 playbook 主要做了下面几件事:
1. 通过 `service` 命令检查 SSH 服务当前的状态。
2. 把服务的当前状态输出出来,方便直接查看。
3. 如果发现服务没有运行,就自动把它启动起来。
4. 在可能完成启动之后,再次确认服务状态。
5. 输出 SSH 服务的最终状态。
6. 检查 SSH 的 22 端口是否处于监听状态。
7. 显示 22 端口的检查结果。
保存文件后退出编辑器。
接下来,用 sudo 权限执行这个 playbook:
```bash
sudo ansible-playbook check_service_docker.yml
```
正常情况下,你会看到类似下面这样的输出:
```n
PLAY [Check and manage SSH service in Docker] *****************************************
TASK [Gathering Facts] *****************************************************************
ok: [localhost]
TASK [Check SSH service status] *******************************************************
changed: [localhost]
TASK [Display SSH service status] *****************************************************
ok: [localhost] => {
"msg": "SSH service status: * sshd is running"n}nnTASK [Start SSH service if not running] ***********************************************nskipping: [localhost]nnTASK [Verify SSH service is running] **************************************************nchanged: [localhost]nnTASK [Display final SSH service status] ***********************************************nok: [localhost] => {n "msg": "SSH service status is now: * sshd is running"n}nnTASK [Check if SSH port is listening] *************************************************nchanged: [localhost]nnTASK [Display SSH port status] ********************************************************nok: [localhost] => {n "msg": "SSH port 22 is open"n}nnPLAY RECAP ****************************************************************************nlocalhost : ok=6 changed=3 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0n```nn此输出显示 SSH 服务已经在运行,因此不需要启动。playbook 成功检查并验证了服务状态,并确认 SSH 端口是开放的。n","need_verify":true,"has_solution":false},{"position":6,"title":"总结","layout":"doc-fullscreen","text":"## 总结nn在本实验中,你探索了 Ansible Command 模块的多功能性和强大功能。你已经学会了如何:nn1. 使用 Command 模块创建简单的 Ansible playbook 来执行基本命令。n2. 在 Command 模块中使用变量,使你的 playbook 更加灵活和可重用。n3. 捕获并处理命令输出,使你能够根据命令结果做出决策。n4. 使用各种 Command 模块选项来控制其行为,例如更改目录、设置环境变量和处理错误。n5. 通过检查和管理系统服务,将 Command 模块应用于实际场景。nn这些技能为你使用 Ansible 自动化系统管理任务和高效管理远程主机奠定了坚实的基础。随着你继续使用 Ansible,你会发现 Command 模块是自动化工具包中的一个多功能工具。nn请记住,虽然 Command 模块功能强大,但在有可用的情况下,通常最好使用专门的 Ansible 模块(例如用于管理服务的 `service` 模块)。这些专门的模块提供了更好的幂等性,并且可以开箱即用地处理更复杂的场景。nn继续练习和探索 Ansible 的功能,以进一步提升你的自动化技能并简化你的 IT 运维工作。n","need_verify":false,"has_solution":false}
本文转载于:https://labex.io/zh/tutorials/ansible-ansible-command-module-290161 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。