您当前的位置:首页 > 计算机 > 软件应用 > 资料管理

ansible常用命令介绍

时间:08-05来源:作者:点击数:
城东书院 www.cdsy.xyz
单纯的学习笔记。Ansible 是一个强大的自动化运维工具,提供了大量模块来完成各种任务,平常用来管理大量服务器或者虚拟机还是很方便的。

🧱 1. 基础操作模块

模块 说明 示例
ping 测试连通性 ansible all -m ping
shell 执行 shell 命令(支持管道) ansible all -m shell -a "echo hello“
script 运行本地脚本 ansible all -m script -a “./deploy.sh”
raw 不依赖 Python 环境直接执行命令 ansible all -m raw -a “yum install -y python3”

📂 2. 文件与目录管理

模块 说明 示例
copy 拷贝文件/目录到远程主机 ansible all -m copy -a “src=/root/file.txt dest=/tmp/file.txt”
file 设置文件权限、拥有者、目录状态) ansible all -m file -a “path=/tmp/logs state=directory mode=755”
fetch 从远程主机取回文件 ansible all -m fetch -a “src=/var/log/messages dest=/tmp/logs”
lineinfile 修改文件中的一行 ansible all -m lineinfile -a “path=/etc/hosts line=‘127.0.0.1 test.local’”

📦 3. 软件包管理

模块 说明 示例
yum RHEL/CentOS 安装包 ansible all -m yum -a “name=httpd state=present”
apt Debian/Ubuntu 安装包 ansible all -m apt -a “name=nginx state=present”
package 跨平台统一安装模块 ansible all -m package -a “name=git state=latest”

🖥️ 4. 服务与进程控制

模块 说明 示例
service 管理系统服务 ansible all -m service -a “name=nginx state=restarted”
systemd 更现代的服务管理 ansible all -m systemd -a “name=docker enabled=yes state=started”
cron 管理计划任务 ansible all -m cron -a “name=‘backup’ minute=0 hour=2 job=‘/bin/backup.sh’”

👤 5. 用户与权限

模块 说明 示例
user 管理用户账户 ansible all -m user -a “name=devuser state=present”
group 管理用户组 ansible all -m group -a “name=developers state=present”
authorized_key 设置 SSH 公钥登录 ansible all -m authorized_key -a “user=root key=‘{{ lookup(‘file’, ‘/root/id_rsa.pub’) }}’”

🌐 6. 网络相关

模块 说明 示例
hostname 设置主机名 ansible all -m hostname -a “name=node01”
firewalld 管理 firewalld 防火墙 ansible all -m firewalld -a “port=80/tcp permanent=true state=enabled immediate=yes”
iptables 设置 iptables(用 script/shell 调用较多) ansible all -m shell -a “iptables -A INPUT -p tcp --dport 22 -j DROP”
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐