这篇文章上次修改于 423 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

Ansible简介

  • Ansible 是一款 IT 自动化工具。主要应用场景有配置系统、软件部署、持续发布及不停服平滑滚动更新的高级任务编排。非常适用于需要批量处理大量服务器的场景。

环境要求

  • 管理节点运行 Ansible 的服务器必须且只需要安装有 Python 2.7+ 或者 Python 3.5+
  • 受管节点需要和外界正常通信,默认使用 SSH 协议。 默认使用 SFTP 。 如果 SFTP 无法使用,你可以在 ansible.cfg 中将其修改为 SCP . 同样,受管机需要有 Python 2.6+ 或 Python 3.5以上的环境
  • 如果受管机开启了 SELinux,你需要安装 libselinux-python ,不然 copy/file/template 等任何相关联的功能都无法使用

安装命令


sudo yum update sudo yum install ansible libselinux-python
  • 检查是否安装成功

[root@k8s-master ~]# ansible --version ansible 2.9.27 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, Jun 20 2023, 11:36:40) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] [root@k8s-master ~]#

主机清单文件

  • /etc/ansible/hosts 在此文件增加你需要管理机器的ip

vi /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 [k8snode:vars] ansible_user=root #k8snode组的服务器登录用户名 ansible_port=22 #k8snode组的服务器ssh端口 ansible_password=**** #k8snode组的服务器登录用户密码 [k8snode] #设置下面2个ip归属于k8snode组 192.168.1.8 192.168.1.9 [web] 192.168.1.10 ansible_user=root ansible_port=22 ansible_password=*** #单独给一个服务器设置登录信息 192.168.1.11 # 也可以做成ssh免密登录,就不需要设置上面的用户名和密码设置了 [task] 192.168.1.12

ssh 免密登录设置


[root@k8s-master ~]# ssh-copy-id root@192.168.1.12 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@192.168.1.8's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@192.168.1.8'" and check to make sure that only the key(s) you wanted were added.