【Ansible学习笔记01】 批量执行 shell 命令

根据您提供的配置和执行示例,以下是使用 Ansible 批量执行 shell 命令的详细步骤:

1. 准备工作

1.1 目录结构准备

bash 复制代码
# 创建目录
mkdir -p ansible-ssh-trust/inventory
cd ansible-ssh-trust

1.2 编辑 inventory 文件

bash 复制代码
# 编辑主机配置文件
vi ./inventory/hosts.ini

将以下内容写入 hosts.ini

ini 复制代码
# inventory/hosts.ini
[all:vars]
ansible_user=root
# 方法1:使用密码(第一次需要)
ansible_ssh_pass=rootroot
# 方法2:或使用现有密钥
# ansible_ssh_private_key_file=~/.ssh/id_rsa

[cluster]
k8s-master01 ansible_host=172.16.2.101
k8s-master02 ansible_host=172.16.2.102
k8s-master03 ansible_host=172.16.2.103
k8s-node01 ansible_host=172.16.2.104
k8s-node02 ansible_host=172.16.2.105
k8s-node03 ansible_host=172.16.2.106

[application]
# 可以根据需要添加应用服务器组

2. 测试连接

2.1 测试主机连通性

bash 复制代码
# 测试所有主机连通性(使用 ping 模块)
ansible all -i ./inventory/hosts.ini -m ping

# 或测试特定组
ansible cluster -i ./inventory/hosts.ini -m ping

2.2 检查配置是否正确

bash 复制代码
# 查看 inventory 中的所有主机
ansible-inventory -i ./inventory/hosts.ini --list

# 查看特定组的主机
ansible-inventory -i ./inventory/hosts.ini --graph

3. 执行 Shell 命令

3.1 基本语法

bash 复制代码
ansible <主机组或主机> -i <inventory文件> -m <模块> -a "<命令>"

3.2 常用示例

查看系统信息:

bash 复制代码
# 查看内存使用情况(如您的示例)
ansible cluster -i ./inventory/hosts.ini -m shell -a "free -m"

# 查看磁盘空间
ansible cluster -i ./inventory/hosts.ini -m shell -a "df -h"

# 查看 CPU 信息
ansible cluster -i ./inventory/hosts.ini -m shell -a "lscpu"

# 查看系统负载
ansible cluster -i ./inventory/hosts.ini -m shell -a "uptime"

执行系统管理命令:

bash 复制代码
# 重启服务
ansible cluster -i ./inventory/hosts.ini -m shell -a "systemctl restart docker"

# 查看服务状态
ansible cluster -i ./inventory/hosts.ini -m shell -a "systemctl status kubelet"

# 创建目录
ansible cluster -i ./inventory/hosts.ini -m shell -a "mkdir -p /data/logs"

# 查看进程
ansible cluster -i ./inventory/hosts.ini -m shell -a "ps aux | grep kube"

文件操作:

bash 复制代码
# 查看文件内容
ansible cluster -i ./inventory/hosts.ini -m shell -a "cat /etc/hosts"

# 统计文件行数
ansible cluster -i ./inventory/hosts.ini -m shell -a "wc -l /var/log/messages"

# 查找文件
ansible cluster -i ./inventory/hosts.ini -m shell -a "find /etc -name '*.conf'"

4. 高级用法

4.1 使用 Playbook 执行命令

创建 playbook.yml

yaml 复制代码
---
- name: Execute shell commands on cluster
  hosts: cluster
  tasks:
    - name: Check memory usage
      shell: free -m
      register: memory_result
    
    - name: Display memory info
      debug:
        var: memory_result.stdout_lines
    
    - name: Check disk space
      shell: df -h /
      register: disk_result
    
    - name: Display disk info
      debug:
        var: disk_result.stdout

执行 Playbook:

bash 复制代码
ansible-playbook -i ./inventory/hosts.ini playbook.yml

4.2 并行执行和超时设置

bash 复制代码
# 并行执行(默认5个并行)
ansible cluster -i ./inventory/hosts.ini -m shell -a "sleep 10 && echo done" -f 10

# 设置超时时间(秒)
ansible cluster -i ./inventory/hosts.ini -m shell -a "long_running_command" -T 30

4.3 错误处理和输出控制

bash 复制代码
# 忽略错误继续执行
ansible cluster -i ./inventory/hosts.ini -m shell -a "ls /nonexistent" --ignore-errors

# 只显示失败的输出
ansible cluster -i ./inventory/hosts.ini -m shell -a "command" -o

# 详细输出(-v, -vv, -vvv 详细程度递增)
ansible cluster -i ./inventory/hosts.ini -m shell -a "command" -vv

4.4 条件执行

bash 复制代码
# 只在满足条件的主机上执行
ansible cluster -i ./inventory/hosts.ini -m shell -a "reboot" --limit "k8s-master01,k8s-master02"

# 使用模式匹配
ansible "k8s-master*" -i ./inventory/hosts.ini -m shell -a "hostname"

5. 实用脚本示例

5.1 批量执行脚本

bash 复制代码
# 创建要执行的脚本
cat > /tmp/check_system.sh << 'EOF'
#!/bin/bash
echo "Hostname: $(hostname)"
echo "Memory:"
free -m
echo "Disk:"
df -h /
EOF

# 批量分发并执行
ansible cluster -i ./inventory/hosts.ini -m copy -a "src=/tmp/check_system.sh dest=/tmp/check_system.sh mode=0755"
ansible cluster -i ./inventory/hosts.ini -m shell -a "/tmp/check_system.sh"

5.2 收集所有节点信息

bash 复制代码
# 创建一个收集脚本
cat > collect_info.yml << 'EOF'
---
- name: Collect system information
  hosts: cluster
  tasks:
    - name: Get all info
      shell: |
        echo "=== $(hostname) ==="
        echo "Memory: $(free -m | awk 'NR==2{print $3"/"$2"MB"}')"
        echo "Disk: $(df -h / | awk 'NR==2{print $3"/"$2" used:"$5}')"
        echo "Load: $(uptime | awk -F'load average:' '{print $2}')"
      register: info
    
    - name: Display info
      debug:
        var: info.stdout
EOF

# 执行收集
ansible-playbook -i ./inventory/hosts.ini collect_info.yml

6. 注意事项

  1. 安全性:不要在命令中直接传递密码等敏感信息

  2. 权限:确保 ansible_user 有执行命令的权限

  3. 引号处理:复杂命令需要正确处理引号

  4. 环境变量:shell 模块不会加载用户的 profile,如有需要可以指定

    bash 复制代码
    ansible cluster -i ./inventory/hosts.ini -m shell -a "source /etc/profile && your_command"
  5. 返回码:shell 模块会检查命令的返回码,非零值会导致任务失败

通过以上步骤,您可以轻松使用 Ansible 批量管理和执行 shell 命令。

相关推荐
hunter145014 小时前
2026.1.4 html简单制作
java·前端·笔记·html
oMcLin14 小时前
如何在 Red Hat Linux 服务器上使用 Ansible 自动化部署并管理多节点 Hadoop 集群?
linux·服务器·ansible
d111111111d14 小时前
STM32 USART接收中断:如何判断数据接收完成?
stm32·单片机·嵌入式硬件·学习·模块测试
葡萄杨14 小时前
【存算芯片】存算阵列模型和wavedrom
笔记
报错小能手14 小时前
线程池学习(一) 理解操作系统 进程 线程 协程及上下文切换
学习
中屹指纹浏览器14 小时前
2026指纹浏览器技术选型与实践:从单账号到千级矩阵的部署优化
经验分享·笔记
pps-key14 小时前
麻雀AI:一个能自己学习交易的智能体
人工智能·学习
weixin_4374977714 小时前
学习笔记:用于EDA的LLMs专题会议论文
人工智能·笔记·搜索引擎·fpga开发
HXR_plume14 小时前
【Web信息处理与应用课程笔记5】多模态信息检索
人工智能·笔记·计算机网络·信息检索