ansible安装与初步使用教程

目录

机器准备

服务器ip主机名系统版本
192.168.1.108masterCentos6.5
192.168.1.109slave1Centos6.5
192.168.1.110slave2Centos6.5
192.168.1.111slave3Centos6.5

安装方法介绍

说明:只需要在控制节点安装ansible批量分发工具,其他被控制节点不需要任何操作。

第一种安装ansible方法
yum install epel-release -y #配置 EPEL源
yum install ansible -y 
第二种安装ansible方法
yum install epel-release -y   #配置 EPEL源
yum  install python-pip  -y
pip install ansible -y
pip install -upgrade pip -y

安装ansible(我这里采用第一种安装方式)

  1. 首先,检查控制节点是否已经安装ansible
rpm -qa ansible
find / -name ansible
  1. 如果未安装ansible(这里采用第一种安装方式)
yum install epel-release -y #配置 EPEL源
yum install ansible -y 
  1. 检查ansible是否安装成功
[root@master ~]# rpm -qa  ansible
ansible-2.6.13-1.el6.noarch

[root@master ~]# ansible --version
ansible 2.6.13
  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.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]

[root@master ~]# find / -name ansible
/etc/ansible
/usr/lib/python2.6/site-packages/ansible
/usr/bin/ansible
  1. 根据找到的安装路径查看ansible的各配置文件
注意:
ansible读取变量的顺序是这样子的:
1.先查找环境变量 ANSIBLE_CONFIG 有没有值,如果没有转2 
2.当前目录中的./ansible.cfg 没有转3 
3.当前用户家目录中的~/ansible.cfg 
4.最后才找/etc/ansible/ansible.cfg

[root@master ~]# find / -name ansible
/etc/ansible
/usr/lib/python2.6/site-packages/ansible
/usr/bin/ansible

[root@master~]# ll /etc/ansible
总用量 32
-rw-r--r-- 1 root root 19557 3月  14 11:35 ansible.cfg   #ansible.cfg文件用于配置ansible系统运行参数
-rw-r--r-- 1 root root  1198 3月  14 14:24 hosts
drwxr-xr-x 2 root root  4096 2月   9 01:50 roles

[root@master ~]# egrep -v "^#|^$" /etc/ansible/ansible.cfg
[defaults]
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]

### 常用配置详解 ###
hostfile    = /etc/ansible/hosts   #hosts文件的位置
library      = /usr/share/ansible #ansible默认搜寻模块的位置
pattern     = *  #如果没有提供hosts节点,这是playbook要通信的默认主机组.默认值是对所有主机通信
remote_tmp  = $HOME/.ansible/tmp   #Ansible通过远程传输模块到远程主机,然后远程执行,执行后在清理现场.在有些场景下,你也许想使用默认路径希望像更换补丁一样使用
forks   = 5    #在与主机通信时的默认并行进程数 ,默认是5d
poll_interval  = 15  #当具体的poll interval 没有定义时,多少时间回查一下这些任务的状态, 默认值是5秒                                                      
sudo_user  = root   #sudo使用的默认用户 ,默认是root
#ask_sudo_pass = True   #用来控制Ansible playbook 在执行sudo之前是否询问sudo密码.默认为no
#ask_pass    = True    #控制Ansible playbook 是否会自动默认弹出密码
transport   = smart   #通信机制.默认 值为’smart’。如果本地系统支持 ControlPersist技术的话,将会使用(基于OpenSSH)‘ssh’,如果不支持将使用‘paramiko’.其他传输选项‘local’,‘chroot’,’jail’等等
#remote_port  = 22    #远程SSH端口。 默认是22
module_lang   = C   #模块和系统之间通信的计算机语言,默认是C语言
#host_key_checking = False    #检查主机密钥
timeout = 10    #SSH超时时间
#log_path = /var/log/ansible.log     #日志文件存放路径
#module_name = command     #ansible命令执行默认的模块
#private_key_file = /path/to/file     #私钥文件存储位置

关闭ansible的认证公钥

/etc/ansible/ansible.cfg文件用于配置ansible系统运行参数。
Ansible1.2.1及其之后版本都会默认启用公钥认证配置如下:

# uncomment this to disable SSH key host checking
# host_key_checking = False

以上默认是不关闭公钥认证,这样在初次认证的时候会进行对key信息的确认提示。
如果你想禁用此项行为有两种方法:

  1. 编辑/etc/ansible/ansible.cfg 或者编辑 ~/.ansible.cfg来实现:
# uncomment this to disable SSH key host checking
host_key_checking = False
  1. 你也可以通过编辑/etc/profile 文件中添加设置环境变量来实现(推荐):
export ANSIBLE_HOST_KEY_CHECKING=False

SSH配置免密互信(配置控制节点到各节点SSH免密访问 )

Ansible是用来处理大批量重复性操作的工具,只需要在一台机器上就可以远程控制所有机器,通过读取主机清单/etc/ansible/hosts连接到多个远程主机上执行任务,但前提是必须保证保证控制节点到每台被控制机器之间SSH可以相互免密登录。

注: 有关Ansible的所有操作只需在第一台机器上(控制节点)修改和执行,其它机器只需知道IP地址,主机名等即可。

/etc/ansible/hosts 文件基本格式
# 使用[]来对主机进行分类,可按照功能,机房,系统,业务等内容进行分类,方便对同一类型的主机进行批量操作。

[webserver]
localhost-2.63 			#主机名 (默认ssh端口,省略不写)
192.168.2.61 			#主机IP地址 (默认ssh端口,省略不写)
192.168.2.[70:100] 		#指定主机IP地址的范围
192.168.2.66:5505  		#主机IP地址 +(自定义ssh端口)
test ansible_ssh_host=192.168.2.57 ansible_ssh_port=5504  #test主机别名+主机IP地址+(自定义ssh端口)


#可以为主机指定连接类型和连接用户
[tomcatserver]
localhost 		ansible_connection=local
192.168.2.70 	ansible_connection=ssh ansible_ssh_user=root

#hosts文件可以使用的指令
ansible_ssh_host     	#指定主机别名对应的真实 IP
ansible_ssh_port      	#指定连接到这个主机的 ssh 端口,默认 22
ansible_ssh_user     	#指定连接到该主机上的用户
ansible_sudo_pass      	#sudo 密码
ansible_sudo_exe       	#sudo 命令路径
ansible_connection   	#连接类型,可以是 local、ssh 或paramiko,ansible1.2 之前默认为 paramiko
ansible_shell_type      #目标系统的 shell 类型,默认为sh
ansible_ssh_private_key_file      #私钥文件路径

编辑 /etc/ansible/hosts 文件

将所有需要与被控制节点免密互信的主机加入进去,并带上被控制节点的ssh端口号(非默认端口时填写),以及ssh远程登录的密码(免密成功之后需要将此处的密码去掉)

[ssh]
192.168.1.109 	ansible_ssh_user=root ansible_ssh_pass=123456
192.168.1.110   	ansible_ssh_user=root ansible_ssh_pass=123456
192.168.1.111		 ansible_ssh_user=root ansible_ssh_pass=123456
编写ansible-playbook 剧本文件
  1. 控制节点登录到被控制节点实现免密
cat  /home/script/ansible-yml/sshKeyBossToOthers.yml
- hosts: ssh
  gather_facts: no 

  tasks: 
  - name: give the pub_keys of the boss_host to the remote hosts to let the boss_host can login the remote hosts without password.
    authorized_key: 
      user: root
      key: "{{lookup('file','/root/.ssh/id_rsa.pub')}}"
      state: present
  1. 被控制节点登录到控制节点实现免密
cat  /home/script/ansible-yml/sshKeyOthersToBoss.yml
- hosts: ssh
  gather_facts: no 

  tasks: 

  - name: install expect #因为下面的任务需要依靠expect,所以确保被控制节点已经安装了expect软件。
    yum: name=expect state=installed

  - name: give the pub_keys of the controled hosts to the boss_hosts to let the  other hosts can login the boss_host  without password.
    shell: sh /home/script/sh/sshKeyOthersToBoss.sh   #执行此脚本

/home/script/sh/sshKeyOthersToBoss.sh 脚本内容如下:

#!/bin/sh
source /etc/profile
. /etc/init.d/functions

#功能:其他机器指定用户到中转机指定用户到实现免密
#define varibales  

user=`whoami`
ssh_dir=`echo ~/.ssh`
public_file=`echo ~/.ssh/id_rsa.pub`
private_file=`echo ~/.ssh/id_rsa`
remote_port="10000"
remote_ip="10.199.41.100"
remote_host_passwd="h7ERp0iG"

#确保本机已经生成了公钥、秘钥以及know_hosts列表
if [ ! -d ${ssh_dir} ];then

expect -c "
	set timeout 5
	spawn ssh-keygen -t rsa;
	expect \"Enter file in which to save the key (${public_file}):\";
	send \"\n\";
	expect \"Enter passphrase (empty for no passphrase):\"; 
	send \"\n\";
	expect \"Enter same passphrase again:\";
	send \"\n\";
	expect \"The key's randomart image is:\";  
	send \"\n\";
expect eof" >/dev/null 2>&1



	else
	
	if [ ! -f ${public_file} -o ! -f ${private_file} ];then
		

		expect -c "
			set timeout 5
			spawn ssh-keygen -t rsa;
			expect \"Enter file in which to save the key (${public_file}):\";
			send \"\n\";
			expect \"Enter passphrase (empty for no passphrase):\"; 
			send \"\n\";
			expect \"Enter same passphrase again:\";
			send \"\n\";
			expect \"The key's randomart image is:\";  
			send \"\n\";
		expect eof" >/dev/null 2>&1

	else 
	
	
		expect -c "
			set timeout 5
			spawn ssh-keygen -t rsa;
			expect \"Enter file in which to save the key (${public_file}):\";
			send \"\n\";
			expect \"Overwrite (y/n)\?\";
			send \"y\n\";
			expect \"Enter passphrase (empty for no passphrase):\"; 
			send \"\n\";
			expect \"Enter same passphrase again:\";
			send \"\n\";
			expect \"The key's randomart image is:\";  
			send \"\n\";
		expect eof" >/dev/null 2>&1

	
	
	fi
		

fi

# close ssh check and change "StrictHostKeyChecking ask" to "StrictHostKeyChecking no" in the file /etc/ssh/ssh_config #关闭初次访问提示询问

 sed -i "s/^.*StrictHostKeyChecking.*$/StrictHostKeyChecking ask/g" /etc/ssh/ssh_config


#开始分发公钥

echo "开始分发公钥:"
expect -c "
	set timeout 5
	spawn ssh-copy-id  -i ${public_file}  -p ${remote_port} ${user}@${remote_ip};
	# expect \"Are you sure you want to continue connecting (yes/no)?\";
	# send \"yes\n\";
	expect \"${user}@${remote_ip}'s password:\"; 
	send \"${remote_host_passwd}\n\";
	expect \"Number of key(s) added: 1\";
	send \"\n\";
expect eof" >/dev/null 2>&1


if [ $? -eq 0 ];then
	action "${remote_ip} send id_dsa is successful" /bin/true
	else
	action "${remote_ip} send id_dsa is failed copied" /bin/false
fi


执行免密互信剧本

ansible-playbook --syntax-check  /home/script/ansible-yml/sshKeyBossToOthers.yml   #检查剧本语法
ansible-playbook --syntax-check  /home/script/ansible-yml/sshKeyOthersToBoss.yml   #检查剧本语法

----------------------------------------------------------------------------------------------------------------------
ansible-playbook  /home/script/ansible-yml/sshKeyBossToOthers.yml   #执行剧本
ansible-playbook  /home/script/ansible-yml/sshKeyOthersToBoss.yml   #执行剧本

测试免密互信是否成功

远程登录,详细步骤省略

再次修改/etc/ansible/ansible.cfg

[root@master ~]$ vi  /etc/ansible/ansible.cfg
[defaults]
sudo_user=root
remote_user=root
#remote_port = 22
#private_key_file =  /var/lib/ansible/.ssh/id_rsa

再次修改/etc/ansible/hosts (去掉主机密码等敏感信息并进行主机分组)

[root@master ~]$ vi /etc/ansible/hosts
[test-hosts]
192.168.1.109

[web-hosts]
192.168.1.110
192.168.1.111

使用ansible批量管理

使用ping模块对被控制节点的测试组主机进行ping操作
[root@master ~]$ ansible 192.168.1.109 -m ping
192.168.1.109 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@master ~]$ ansible test-hosts -m ping
192.168.1.109 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
#待被控制节点的测试组主机测试结果无误后再到生产环境进行操作
使用ping模块对被控制节点的web组主机进行ping操作
[root@master ~]$ ansible web-hosts -m ping
192.168.1.110 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.111 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
使用command模块对所有被控制节点进行操作
[root@master ~]$ ansible all -m command -a "date"
192.168.1.109  | SUCCESS | rc=0 >>
Tue Mar 26 10:24:15 CST 2019

192.168.1.110  | SUCCESS | rc=0 >>
Tue Mar 26 10:24:15 CST 2019

192.168.1.111  | SUCCESS | rc=0 >>
Tue Mar 26 10:24:15 CST 2019

ansible拓展

ansible实用参数
ansible-doc -s 模块名    #查看ansible模块用法参数等帮助
ansible-doc -l  		#列出此版本的ansible支持哪些模块

ansible-playbook  --syntax-chek 		xxx.yml     #检查语法
ansible-playbook  --list-hosts 			xxx.yml 	#列出被影响节点
当指定的被控制节点上的普通用户没有操作权限时用sudo

前提是被控制节点上的普通用户已经被授权可以用sudo命令

[root@master ~]$ ansible 192.168.1.109  -m shell -a "sudo ls -l /root/anaconda-ks.cfg "  
[DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. 
This feature will be removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
 [WARNING]: Consider using 'become', 'become_method', and 'become_user' rather than running sudo

 192.168.1.109 | CHANGED | rc=0 >>
-rw-------. 1 root root 1029 5月   6 14:06 /root/anaconda-ks.cfg
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值