系统管理员常常须要作一些重复的工做,如系统初始化、软件升级、修改配置、部署应用、重启服务、执行命令等。咱们能够经过脚原本完成这些工做,例如使 Fabric。但当系统规模较大时,脚本就显得比较乏力,配置管理工具 SaltStack、Ansible 等的优势显现出来。配置管理的特色是经过配置来管理远程服务器,并非脚本。shell
Ansible 是配置管理和应用部署工具,默认经过 ssh 协议管理服务器,在管理主机上执行命令就能够在各节上执行相应的动做,而 Saltstack、Puppet、Chef 等须要在每一个设备上安装特定的软件。安全
Ansible 的目的:bash
Ansible 的特色:服务器
推荐 pip:ssh
pip install ansible
复制代码
Ansible 的配置文件的查找顺序以下:工具
ANSIBLE_CONFIG
ansible.cfg
~/.ansible.cfg
/etc/ansible/ansible.cfg
Ansible 使用找到的第一个文件,忽略其他的。ui
配置文件是 INI
格式文件的变种,#
和 ;
均可以用做注释符,但注释所在的行有正规的值时,只能使用 ;
云计算
# some basic default values...
inventory = /etc/ansible/hosts ; This points to the file that lists your hosts
复制代码
出于安全的考虑,
ansible.vfg
所在的当前目录是world-writable
的话,Ansible 将不会自动加载文件,解决方法是将此目录的进入权限限定为特定的用户或组。若是系统不能使用chmod
、chown
、chgrp
,最好的解决方法修改文件系统的挂载选项,使目录对运行 ansible 的用户读写,对其余用户关闭。spa
使 ansible-config view
查看配置。命令行
Ansible
远程通讯默认使用原生的 OpenSSH
,可是当管理节点是 Enterprise Linux 6
(如 RHEL
和 CentOS
),Openssh
的版太老,Ansible
会使用 OpenSSH
的 Python
实现:paramiko
。若是您想使用 SSH
的新特性,使用 Fedora
、MacOS
或 Ubuntu
做为控制节点。
可能有些设备不支持
SFTP
,能够在配置文件中切换为SCP
模式。
Ansibe 默认使用 SSH keys 和远程主机通讯,虽然推荐使用 ssh keys,但当提供 --ask-pass
参数时也能够使口令认证。若是想用 sudo
,需提供 --ask-become-pass
(以前的 --ask-sudo-pass
再也不推荐)。
Linux
无密钥登陆:
在管理节点生成密钥对
ssh-keygen -t rsa
复制代码
发送公钥
ssh-copy-id user@host
复制代码
或
ssh-copy-id -i ~/.ssh/id_rsa.pub user@host
复制代码
也能够设置远程主机拒绝密码验证
# vi /etc/ssh/sshd_config
PasswordAuthentication no
复制代码
PubkeyAuthentication yes
若是执行第三步,需重启 sshd
systemctl restart sshd
复制代码
Ansible does not expose a channel to allow communication between the user and the ssh process to accept a password manually to decrypt an ssh key when using the ssh connection plugin (which is the default). The use of ssh-agent is highly recommended.
ssh-agent
是 ssh 的代理程序,能够帮助咱们管理私钥。当遇到以下状况时,咱们会须要 ssh-agent
:
ssh-agent
能够帮助咱们选择对应的密钥进行认证,再也不需手动指定。ssh-agent
能够免去重输入密码的操做。固然,很多系统默认都已经启动,并且生成的密钥也自动加入代理,因此下面的步骤不须要操做。
启动 ssh-agent
:
ssh-agent $SHELL # 会启动一个子shell,运行在子shell中,会随着 ssh 会话的消失而消失,这是一种安全机制
eval `ssh-agent` # 不会启动子shell
复制代码
关闭 ssh-agent
:
ssh-agent -k $SSH_AGENT_PID
复制代码
添加私钥
ssh-add ~/.ssh/id_rsa
复制代码
查看代理中的私钥
ssh-add -l
复制代码
查看代理中的私钥对应的公钥
ssh-add -L
复制代码
删除指定私钥
ssh-add -d /path/key/key_name
复制代码
删除全部代理的私钥
ssh-add -D
复制代码
锁定 ssh 代理
ssh-add -x
复制代码
解锁 ssh 代理
ssh-add -X
复制代码
编辑 ansible.cfg
中的 inventory
指定的文件,默认 /etc/ansible/hosts
:
[test]
10.53.141.252 ansible_user=cec
复制代码
命令行执行命令
$ ansible all -m ping
10.53.141.252 | SUCCESS => {
"changed": false,
"ping": "pong"
}
$ ansible all -a ifconfig
10.53.141.252 | CHANGED | rc=0 >>
enp2s0 Link encap:以太网 硬件地址 8c:ec:4b:51:cc:6d
inet 地址:10.53.141.252 广播:10.53.143.255 掩码:255.255.252.0
。。。。。。
复制代码