最近做项目,机器比较多,自己还是沿用shell的for i in {1…20}这样的蠢方法,旁边的大佬用ansible已经爽的飞起。
故决定使用Ansible来提高自己的工作效率,达到摸鱼的目的…
附上一个建议去学习的链接:Ansible学习
建立连接
- 先在部署机器上创建秘钥,用于免认证
ssh-agent bash
ssh-add ~/.ssh/id_rsa
- 编辑文件
/etc/ansible/hosts
,
[sitonholy]
192.168.1.10 ansible_ssh_user=user ansible_ssh_port=22 ansible_ssh_pass=ubuntu ansible_su_pass=ubuntu
- 使用ping测试来连通性
ansible all -m ping
会反馈以下信息回来,pong
192.168.1.10 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
- 测试远程执行命令
ansible scm -a "uname -r"
- 取消公钥认证,如果某台主机的公钥变化,可能会有提示,我们把它关闭掉
编辑文件/etc/ansible/ansible.cfg
[defaults]
host_key_checking = False
做一个小实验,安装Docker
- 配置Ansible_host
/etc/ansible/hosts
192.168.1.10
- 配置国内加速源,拷贝部署机
daemon.json
文件到客户机的/etc/docker/daemon.json
daemon.json
文件内容
{
"registry-mirrors": ["https://z9ok86c7.mirror.aliyuncs.com"],
"insecure-registries": ["192.168.1.20:80"]
}
- 编写ansible-playbook.yml脚本
- hosts: sitonholy
remote_user: user
sudo: yes
sudo_user: root
tasks:
- name: mkdir
shell: mkdir -p /etc/docker
- name: copy daemon.json
template: src=/home/user/daemon.json dest=/etc/docker/daemon.json
- name: install docker
apt: update_cache=yes
apt:
name: "{{item}}"
state: installed
with_items:
- apt-transport-https
- ca-certificates
- curl
- software-properties-common