一、安装
更新repo源
- 备份(如有配置其他epel源)
mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo.backup
mv /etc/yum.repos.d/epel-testing.repo /etc/yum.repos.d/epel-testing.repo.backup
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
3.安装ansible
yum install ansible -y
-- 查看ansible的版本
# ansible --version
ansible 2.9.6
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
二、 ansible配置文件
# ll /etc/ansible
total 24
-rw-r--r-- 1 root root 19985 2020-03-07 12:43 ansible.cfg
-rw-r--r-- 1 root root 158 2020-04-17 21:48 hosts
drwxr-xr-x 2 root root 6 2020-03-07 12:43 roles
Ansible的配置文件,配置文件可以随意放,但有查找顺序
版本1.5之前的读取顺序如下:
$ANSIBLE_CONFIG #环境变量里找
ansible.cfg #当前目录下面查找
.ansible.cfg #当前用户的家目录下查找
/etc/ansible/ansible.cfg
1. ansible.cgf
# cat /etc/ansible/ansible.cfg
#inventory = /etc/ansible/hosts #主机列表配置文件
#library = /usr/share/my_modules/ #库文件存放目录
#remote_tmp = ~/.ansible/tmp #临时py文件存放在远程主机目录
#local_tmp = ~/.ansible/tmp #本机的临时执行目录
#forks = 5 #默认并发数
#sudo_user = root #默认sudo用户
#ask_sudo_pass = True #每次执行是否询问sudo的ssh密码
#ask_pass = True #每次执行是否询问ssh密码
#remote_port = 22 #远程主机端口
host_key_checking = False #跳过检查主机指纹
log_path = /var/log/ansible.log #ansible日志
[privilege_escalation] #如果是普通用户则需要配置提权
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False
2.主机和组配置
1.基于密码连接
# cat /etc/ansible/hosts
#方式一、主机+端口+密码
[web_group]
192.168.3.209 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='121**'
192.168.3.211 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='121**'
#方式二、主机+端口+密码
[web_group]
web[1:2].test.com ansible_ssh_pass='121**'
#方式三、主机+端口+密码
[web_group]
web[1:2].test.com
[web_group:vars]
ansible_ssh_pass='121**'
2.基于密钥连接。(需要先创建公钥和私钥,并下发公钥至被控端)
# ssh-keygen
# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.3.209
# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.3.211
3.主机变量
ansible_ssh_host #用于指定被管理的主机的真实IP
ansible_ssh_port #用于指定连接到被管理主机的ssh端口号,默认是22
ansible_ssh_user #ssh连接时默认使用的用户名
ansible_ssh_pass #ssh连接时的密码
ansible_sudo_pass #使用sudo连接用户时的密码
ansible_sudo_exec #如果sudo命令不在默认路径,需要指定sudo命令路径
ansible_ssh_private_key_file #秘钥文件路径,秘钥文件如果不想使用ssh-agent管理时可以使用此选项
ansible_shell_type #目标系统的shell的类型,默认sh
ansible_connection #SSH 连接的类型:local , ssh , paramiko,在ansible1.2之前默认是paramiko ,后来智能选择,优先使用基于ControlPersist 的ssh
ansible_python_interpreter #用来指定python解释器的路径,默认为/usr/bin/python 同样可以指定ruby 、perl的路径
ansible__interpreter #其他解释器路径,用法与ansible_python_interpreter类似,这里""可以是ruby或perl等其它语言