Ansible是一种自动化的运维工具,基于Python开发,它集合了众多运维工具(比如puppet、chef、func等)的优点,能够实现批量操作
安装配置
1.安装
系统版本:Cenots7
在管理端Server上安装即可
wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all
yum makecache
yum install -y ansible
ansible --version
2.配置免密
配置管理端到被控端的ssh免密
所有的被控端执行
ssh-keygen
管理端执行
ssh-keygen
ssh-copy-id root@192.168.1.xxx
ssh-copy-id root@192.168.1.xxx
3. 配置被控端主机列表
vi /etc/ansible/hosts
[k8s]
192.168.1.xxx
192.168.1.xxx
192.168.1.xxx
[db]
192.168.1.xxx
测试ansible
ansible all -m ping
ansible k8s -m ping
Ansible使用
1. 执行命令
ansible all -m command -a 'date'
ansible k8s -m shell -a 'ip a | grep 192'
2. 执行shell脚本
先在管理端机器上创建脚本target.sh
vi target.sh
df -h
批量执行
ansible all -m script -a "/root/target.sh"
3.ansible-playbook
使用yaml定义所需执行的tasks,以此达到shell脚本的效果
定义一个playbook的yaml
cat playbook_fetch_file.yml
---
- hosts: k8s
remote_user: root
tasks:
- name: fetch log files
fetch:
src: "/var/log/messages"
dest: /tmp/messages-{{ inventory_hostname }}
flat: yes
# 抓取文件到管理机
执行:ansible-playbook playbook_test01.yml
playbook中内置了一些模块,例如:command,copy,yum,service,user等,这些内置的模块,让yaml比shell写起来更加简便。