簡(jiǎn)介
ansible是新出現(xiàn)的自動(dòng)化運(yùn)維工具,急于python開發(fā)。實(shí)現(xiàn)了批量系統(tǒng)配置,批量程序部署,批量運(yùn)行命令等,
特性:部署簡(jiǎn)單:基于python和ssh,安全基于:OpenSSH,模塊化:調(diào)用特定的模塊 完成特定的任務(wù)。冪等性:一個(gè)任務(wù)執(zhí)行1遍和執(zhí)行n遍效果一樣。等
怎么運(yùn)行
主控端的服務(wù)器用ssh連接上被控端上,被控端服務(wù)器要預(yù)裝python2.5或更新的版本。ansible就可以批量管理被控端服務(wù)器。
如圖:

安裝
因?yàn)槭腔趐ython開發(fā),ansible是python的一個(gè)包,用pip安裝就可。
先安裝 pyenv
基于mac 環(huán)境已經(jīng)安裝了 zsh. 參考:github pyenv
1.Check out pyenv
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
2.Define environment variable
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
3.Add pyenv init to your shell
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.zshrc
4.Restart your shell so the path changes take effect.
exec "$SHELL"
5.安裝python環(huán)境依賴
brew install openssl readline sqlite3 xz zlib
6.使用參考 pyenv使用文檔
用pipenv來(lái)安裝指定項(xiàng)目的ansible
1.vim Pipfile
[[source]]
verify_ssl = true
url = "https://mirrors.aliyun.com/pypi/simple"
name = "pypi"
[requires]
python_version = "3.7"
[dev-packages]
[packages]
ansible = "*"
2.安裝
pipenv install
安裝ansible
1.安裝
pip list
pip install ansible
ansible --version
2.ansible 配置 用pip安裝的ansible沒(méi)有ansible.cfg,需要我們自行的創(chuàng)建配置文件。
獲取最新的官方配置 官方ansible.cfg文件
中文指南-配置文件
例如:簡(jiǎn)單的ansible.cfg
[defaults]
inventory = inventory/hosts
# Host key checking is enabled by default
host_key_checking = False
roles_path = roles
# Default user to use for playbooks if user is not specified
# Uses the connection plugin's default, normally the user currently executing Ansible,
# unless a different user is specified here.
#
#remote_user = root
使用戶可以查看所有可用的配置設(shè)置
ansible-config view
3.ansible.cfg 我們放在哪里
ansible會(huì)按照如下的位置和順序來(lái)查找 ansible.cfg文件.找到之后就不向下面找
- ./ansible.cfg
- ~/.ansible.cfg
- /etc/ansible/ansible.cfg
我們一般會(huì)把 配置文件和ansible項(xiàng)目放在一個(gè)目錄里面。當(dāng)我們執(zhí)行palybook時(shí)候會(huì)讀取當(dāng)前的項(xiàng)目配置。保證了各自的項(xiàng)目是隔離的。
ansible 訪問(wèn)被控主機(jī)
1.密碼明文訪問(wèn)主機(jī),不安全
vim inventory/hosts
192.168.1.100 ansible_port=22 ansible_user=root ansible_ssh_pass=redhat
ansible_port 是客戶端sshd服務(wù)的端口
ansible_user 是客戶端用戶
ansible_ssh_pass 是客戶端用戶密碼
2.測(cè)試
##查看被控的主機(jī)
ansible all --list-host
## ping
ansible all -m ping
2。設(shè)置主機(jī)別名訪問(wèn)主機(jī)
vim inventory/hosts
service1 ansible_host=192.168.1.101 ansible_port=22 ansible_user=root ansible_ssh_pass=redhat
3.免密訪問(wèn)主機(jī)
首先先建立雙方的ssh免密碼安全鏈接
#把本地的ssh公鑰文件安裝到遠(yuǎn)程主機(jī)對(duì)應(yīng)的賬戶下
ssh-copy-id user@server
ssh-copy-id -i ~/.ssh/id_rsa.pub user@server
vim inventory/hosts
service2 ansible_host=192.168.1.102