知识点:
ansible的介绍
ansible的安装
ansible的配置
Ad-hoc的使用 (安装mysql)
Inventory功能
一、ansible的介绍
ansible是一个 IT自动化工具,集成丰富的模块,丰富的功能组件,可以通过命令行完成一系列的操作,具有轻量级、易学习的特点。
二、ansible的安装
- Python pip 简单、快速、跨平台
- 软件源 不会出现编译或者依赖问题,不同平台,软件源不同
- Ansible源码
在这里我们选择pip安装,安装前确认我们Python环境为2.7以上。
2.1.安装Python基础包
yum -y install python-devel python-setuptools
2.2.安装pip工具
easy_install pip
2.3.安装ansible
pip install ansible -i https://pypi.tuna.tsinghua.edu.cn/simple/
三、ansible的配置
首先我们准备两台测试Linux主机
主机1:192.168.5.55 centos7
主机2:192.168.5.56 centos7
主机1上已安装上ansible
3.1.编辑Hosts配置
vim /etc/ansible/hosts
添加以下内容:
1 #主机名 端口 IP 连接用户 2 host2 ansible_ssh_port=22 ansible_ssh_host=192.168.5.56 ansible_ssh_user=root 3 4 #分组 5 [test] 6 192.168.5.56 7 host2
3.2.配置免秘钥登陆
ssh-keygen ssh-copy-id -i 192.168.5.56
3.3.测试结果
ansible host2 -m ping --user=root
返回以下信息说明配置成功了
192.168.5.56 | SUCCESS => { "changed": false, "ping": "pong" }
四、Ad-hoc的使用
Ad-hoc可以理解为命令行工具,使用用法可 ansible -h查看
操作例子
eg1.列出目标主机目录
ansible test -m shell -a "ls /root" --user=root
eg2.输入密码形式登陆远程主机,加上参数--ask-pass
ansible test -m shell -a "ls /root" --user=root --ask-pass
eg3. Centos7上安装MySQL
1.打开 https://docs.ansible.com/ansible/latest/modules/yum_module.html?highlight=yum
2.找到需要的模块
3.执行安装命令
ansible host2 -m yum -a "name=mariadb-server state=latest"
4.对MySQL 启动
ansible host2 -m systemd -a "name=mariadb state=started"
注:如果执行命令重复执行且没有变化,打印为绿色,执行成功为橙色。
五、Inventory功能
Inventory是一个文件,用来定义主机关系。
默认路径为/etc/ansible/hosts文件
5.1.划分主机组
192.168.1.1
[组名]
192.168.1.2
192.168.1.3
5.2.主机别名
host2 ansible_ssh_port=22 ansible_ssh_host=192.168.5.56 ansible_ssh_user=root
其他参数
5.3.批量划分主机组
定义成批的机器。
[webservers] www[01:50].example.com [databases] db-[a:f].example.com