【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 命令。

相关推荐
YCY^v^6 小时前
JeecgBoot 项目运行指南
java·学习
云小逸6 小时前
【nmap源码解析】Nmap OS识别核心模块深度解析:osscan2.cc源码剖析(1)
开发语言·网络·学习·nmap
JustDI-CM7 小时前
AI学习笔记-提示词工程
人工智能·笔记·学习
悟纤7 小时前
学习与专注音乐流派 (Study & Focus Music):AI 音乐创作终极指南 | Suno高级篇 | 第33篇
大数据·人工智能·深度学习·学习·suno·suno api
爱写bug的野原新之助7 小时前
加密摘要算法MD5、SHA、HMAC:学习笔记
笔记·学习
ZH15455891318 小时前
Flutter for OpenHarmony Python学习助手实战:Web开发框架应用的实现
python·学习·flutter
百锦再8 小时前
Vue高阶知识:利用 defineModel 特性开发搜索组件组合
前端·vue.js·学习·flutter·typescript·前端框架
CappuccinoRose8 小时前
JavaScript 学习文档(二)
前端·javascript·学习·数据类型·运算符·箭头函数·变量声明
A9better8 小时前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习
小乔的编程内容分享站8 小时前
C语言笔记之函数
c语言·笔记