前言
ansible是一款自动化运维工具,它基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。
一、命令集
ansible:日常或临时事务使用,为一次性操作。
命令格式:ansible <host-pattern> [options]
ansible-galaxy:类似GitHub或者PIP的功能,用于ansible的Roles上传下载。
命令格式:ansible-galaxy [init|info|install|list|remove] [--help] [options]
ansible-pull:ansible的另一种工作模式(默认使用push模式),通常大批量场景下使用。
命令格式:ansible-pull [options] [playbook.yml]
ansible-doc:ansible的模块文档说明,类似linux的man命令。
命令格式:ansible-doc [options] [module...]
ansible-playbook:ansible的剧本执行命令,可以执行事先编排好的任务集,此命令日常使用率最高。
命令格式:ansible-playbook <playbook.yml>
ansible-vault:主要用于配置文件加密与解密,可以加密编写playbook.yml文件中的敏感信息。
命令格式:ansible-vault [create|decrypt|edit|encrypt|rekey|view] [--help] [options] file_name
ansible-console:ansible提供的交互式工具,可以使用它模拟shell一样使用ansible的内置命令
二、ansible的安装与基本配置
可以使用yum源安装,本例使用了阿里云的yum源安装
root# yum install ansible
1、修改配置文件
# 修改ansible的配置文件
root# vim /etc/ansible/hosts
[web]
192.168.0.10
192.168.0.11 hostname=node1
192.168.0.12 hostname=node2 ansible_ssh_user=root ansible_ssh_pass="123456"
[db]
dbserver1
dbserver2
# 以上的注释
# [web]为主机组的别称,代表一组主机:
如 ansible web -m ping 将会在web中的三台主机中执行ping命令
2、使用ansible命令
执行shell
# 在web组中执行ping命令
root# ansible web -m ping # -m 为ansible默认的模组命令
# 执行所以主机的ping命令
root# ansible all -m ping
# 通过shell来执行ifconfig查看网卡
root# ansible web -m shell -a "ifconfig ens33" # 通过shell将可以使用变量、管道、重定向等功能
# 以raw模块来执行ls命令
root# ansible web -m raw -a "ls"
# 本地脚本传送至远程节点执行
root# ansible test -m script -a create_user.sh
# 使用-m copy拷贝本机文件test.txt到所有主机的/root/路径中
root# ansible all -m copy -a "src=/root/test.txt dest=/root/"
# copy并重命名
root# ansible all -m copy -a "src=/root/test.txt dest=/root/test2.txt"
# copy并设置所属用户与读写权限,backup=yes 如目标存在同名文件且内容不同时将自动备份
root# ansible web -m copy -a "src=/root/1.t dest=/root owner=root group=root mode=644 backup=yes force=yes"
用户管理
# 新增用户
root# ansible web -m user -a "name=gordon"
root# ansible web -m user -a "name=gordon uid=888"
# 删除用户
root# ansible web -m user -a "name=gordon state=absent"
# 创建group
root# ansible web -m group -a "name=admin gid=8888"
# 删除group
root# ansible web -m group -a "name=admin state=absent"
文档管理
# 创建文件
root# ansible web -m file "dest=/root/1.txt mode=660 state=touch"
# 修改文件所属与权限
root# ansible web -m file "dest=/root/1.txt mode=660 owner=root group=root"
# 删除文件
root# ansible web -m file "dest=/root/1.txt state=absent"
# 新建目录
root# ansible web -m file "dest=/root/test mode=750 state=directory"
# 删除目录
root# ansible web -m file "dest=/root/test state=absent"
软件管理
# 使用yum安装httpd
root# ansible web -m yum -a "name=httpd state=lastst"
# 卸载软件
root# ansible web -m yum -a "name=httpd state=absent"
# 设置开机启动
root# ansible web -m service -a "name=httpd enabled=true"
# 开启服务
root# ansible web -m service -a "name=httpd state=started"
# 重启服务
root# ansible web -m service -a "name=httpd state=restarted"
# 停止服务
root# ansible web -m service -a "name=httpd state=stopped"
任务管理
# 配置定时任务
root# ansible test -m cron -a "name='date' minute='0' hour='5,2' job='date > /root/time'"
待续。。。