最近做項目,機器比較多,自己還是沿用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