一、基本部署
安装Ansible
# yum -y install epel-release
# yum list all *ansible*
# yum info ansible
# yum -y install ansible
Ansible配置文件
/etc/ansible/ansible.cfg 主配置文件
/etc/ansible/hosts Inventory
/usr/bin/ansible-doc 帮助文件
/usr/bin/ansible-playbook 指定运行任务文件
定义Inventory
# cd /etc/ansible/
# cp hosts{,.bak}
# > hosts
# cat hosts
[webserver]
127.0.0.1
192.168.10.149
[dbserver]
192.168.10.113
使用秘钥方式连接
# ssh-keygen -t rsa
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.10.149
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.10.113
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@127.0.0.1
使用帮助
# ansible-doc -l 列出ansible所有的模块
# ansible-doc -s MODULE_NAME 查看指定模块具体适用
Ansible命令应用基础
语法:ansible <host-pattern> [-f forks] [-m module_name] [-a args]
<host-pattern> 这次命令对哪些主机生效的
inventory group name
ip
all
-f forks 一次处理多少个主机
-m module_name 要使用的模块
-a args 模块特有的参数
# ansible 192.168.10.113 -m command -a 'date'
# ansible webserver -m command -a 'date'
# ansible all -m command -a 'date'
二、常见模块
command 命令模块(默认模块)用于在远程主机执行命令;不能使用变量,管道等
# ansible all -a 'date'
cron 计划任务
month 指定月份
minute 指定分钟
job 指定任务
day 表示那一天
hour 指定小时
weekday 表示周几
state 表示是添加还是删除
present:安装
absent:移除
# ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job"' #不写默认都是*,每个任务都必须有一个名字
# ansible webserver -a 'crontab -l'
# ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state=absent' #移除任务
user 用户账号管理
name 用户名
uid uid
state 状态
group 属于哪个组
groups 附加组
home 家目录
createhome 是否创建家目录
comment 注释信息
system 是否是系统用户
# ansible all -m user -a 'name="user1"'
# ansible all -m user -a 'name="user1" state=absent'
group 组管理
gid gid
name 组名
state 状态
system 是否是系统组
# ansible webserver -m group -a 'name=mysql gid=306 system=yes'
# ansible webserver -m user -a 'name=mysql uid=306 system=yes group=mysql'
copy 复制文件(复制本地文件到远程主机的指定位置)
src 定义本地源文件路径
dest 定义远程目录文件路径(绝对路径)
owner 属主
group 属组
mode 权限
content 取代src=,表示直接用此处的信息生成为文件内容
# yum -y install libselinux-python
# ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'
# ansible all -m copy -a 'content="hello ansible
Hi ansible" dest=/tmp/test.ansible'
file 设置文件的属性
path|dest|name 对那个文件做设定
创建文件的符号链接:
src: 指定源文件
path: 指明符号链接文件路径
# ansible all -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.ansible'
# ansible all -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ansible state=link'
ping 测试指定主机是否能连接
# ansible all -m ping
service 管理服务运行状态
enabled 是否开机自动启动
name 指定服务名
state 指定服务状态
started 启动服务
stoped 停止服务
restarted 重启服务
arguments 服务的参数
# ansible webserver -m service -a 'enabled=true name=httpd state=started'
shell 在远程主机上运行命令
尤其是用到管道变量等功能的复杂命令
# ansible all -m shell -a 'echo devopsman | passwd --stdin user1'
script 将本地脚本复制到远程主机并运行之
# ansible all -m script -a '/tmp/test.sh'
yum 安装程序包
name 程序包名称(不指定版本就安装最新的版本latest)
state present,latest表示安装,absent表示卸载
# ansible webserver -m yum -a 'name=httpd'