Ansible部署和使用(sshpass)
简介
Ansible默认通过 SSH 协议管理机器。
安装Ansible之后,不需要启动或运行一个后台进程,或是添加一个数据库。只要在一台电脑(可以是一台笔记本)上安装好,就可以通过这台电脑管理一组远程的机器。在远程被管理的机器上,不需要安装运行任何软件,因此升级Ansible版本不会有太多问题。
部署
管理节点需求
目前,只要机器上安装了 Python 2.6 或 Python 2.7 (windows系统不可以做控制主机,都可以运行Ansible。
主机的系统可以是 Red Hat, Debian, CentOS, OS X, BSD的各种版本,等等。
自2.0版本开始,ansible使用了更多句柄来管理它的子进程,,对于OS X系统,你需要增加ulimit值才能使用15个以上子进程,方法 sudo launchctl limit maxfiles 1024 2048,否则你可能会看见”Too many open file”的错误提示。
托管节点需求
通常我们使用 ssh 与托管节点通信,默认使用 sftp。如果 sftp 不可用,可在 ansible.cfg 配置文件中配置成 scp 的方式。在托管节点上也需要安装 Python 2.4 或以上的版本。如果版本低于 Python 2.5 ,还需要额外安装一个模块:
python-simplejson
通过APT安装最近版本
apt install ansible -y
使用
配置远程主机
编辑hosts文件
# vim /etc/hosts 127.0.0.1 localhost 127.0.1.1 prometheus.localdomain prometheus 192.168.245.132 k8s1 192.168.245.133 k8s2 192.168.245.134 k8s3 # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters
编辑主机配置文件
# vim /etc/ansible/hosts # This is the default ansible 'hosts' file. # # It should live in /etc/ansible/hosts # # - Comments begin with the '#' character # - Blank lines are ignored # - Groups of hosts are delimited by [header] elements # - You can enter hostnames or ip addresses # - A hostname/ip can be a member of multiple groups # Ex 1: Ungrouped hosts, specify before any group headers. #green.example.com #blue.example.com #192.168.100.1 #192.168.100.10 # Ex 2: A collection of hosts belonging to the 'webservers' group #[webservers] #alpha.example.org #beta.example.org #192.168.1.100 #192.168.1.110 # If you have multiple hosts following a pattern you can specify # them like this: #www[001:006].example.com # Ex 3: A collection of database servers in the 'dbservers' group #[dbservers] # #db01.intranet.mydomain.net #db02.intranet.mydomain.net #10.25.1.56 #10.25.1.57 # Here's another example of host ranges, this time there are no # leading 0s: #db-[99:101]-node.example.com
在配置文件中添加我们的机器
[k8s] k8s1 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wasd960319 k8s2 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wasd960319 k8s3 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wasd960319
注:为了防止由于免密导致的服务器之间病毒感染,此处使用密码登陆而非密钥
修改ansible配置
由于我们要使用密码登陆而非密钥,所以需要修改ansible的配置
# vim /etc/ansible/ansible.cfg # 由于配置文件过长,此处不再完整贴出 # uncomment this to disable SSH key host checking #host_key_checking = False
我们需要将上面的注释取消
# uncomment this to disable SSH key host checking host_key_checking = False
测试
ansible k8s -m ping
可以看到我们的ping 报错,是因为为安装sshpass(ssh非交互式输入命令需要使用到sshpass)
安装sshpass
apt install sshpass
再次测试
ansible k8s -m ping
此时可以看到已经安装成功。
注意:第一次连接时要将被控制机器添加到控制机的know_host
playbook
执行方法
ansible-playbook test.yml
脚本内容
--- - hosts: k8s remote_user: root tasks: - name: update apt: update_cache=yes - name: upgrade apt: upgrade=dist