ToB企服应用市场:ToB评测及商务社交产业平台

标题: Ansible 数百台批量操作前期预备工作 [打印本页]

作者: 我爱普洱茶    时间: 3 天前
标题: Ansible 数百台批量操作前期预备工作
Ansible 数百台批量操作前期预备工作

配景: 当前有100台服务器在同一个内网,需要统一摆设业务程序并且对主机修改主机名,只提供了一个文档host_user.txt,内容 “ IP   用户   密码 ” 三列。
host_user.txt 内容示例:
10.0.0.11 root xxxx
10.0.0.12 root xxxx
10.0.0.13 root xxxx
技能难点:
1、如何避免一台台服务配置免密等
2、如何避免在ansible配置主机清单中统一添加业务主机
思路: 想根据 host_user.txt 文件的内容自动生成 ansible/hosts 文件,可以通过 Shell 脚本或 Python 脚原来实现。提供两种方法来动态生成 ansible/hosts 文件。
焦点是 ansible_ssh_user 和 ansible_ssh_pass,它允许 Ansible 直接使用用户名和密码举行 SSH 连接,从而跳过手动配置 SSH 免密(key-based authentication)
默认情况下,Ansible 连接远程主机时使用 基于 SSH 密钥(key-based authentication),也就是通过 ssh-keygen 生成密钥并手动拷贝到远程主机 ~/.ssh/authorized_keys 文件中来实现免密登录。
但如果在 hosts 文件中指定了 ansible_ssh_pass,Ansible 就会改用密码认证方式,而不会实验使用 SSH 密钥。这就相当于你手动输入密码举行 SSH 连接一样,因此你不需要提前配置免密。
方法 1:使用 Shell 脚本

可以使用一个简单的 Shell 脚原来读取 user.txt 并格式化成 Ansible 所需的 hosts 文件格式。
Shell 脚本
  1. #!/bin/bash
  2. # 定义输入和输出文件
  3. input_file="user.txt"
  4. output_file="/etc/ansible/hosts"
  5. # 清空 hosts 文件
  6. > "$output_file"
  7. # 写入 Ansible 组名
  8. echo "[All-server]" >> "$output_file"
  9. # 逐行读取 user.txt 并转换格式
  10. while IFS=" " read -r ip user pass; do
  11.     echo "$ip ansible_ssh_port=22 ansible_ssh_user=$user ansible_ssh_pass='$pass'" >> "$output_file"
  12. done < "$input_file"
  13. echo "Ansible hosts 文件已生成:$output_file"
复制代码
使用说明:

这个脚本会根据 user.txt 文件的内容生成一个格式化好的 /etc/ansible/hosts 文件。
shell脚本分析:

while IFS=" " read -r ip user pass; 语句
这个语句用于逐行读取文件或标准输入中的数据,并将每一行的内容按空格分割成不同的字段。具体表明如下:
方法 2:使用 Python 脚本

Python,以下是通过 Python 脚本实现的方式。
Python 脚本
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. # 定义输入和输出文件
  4. input_file = "user.txt"
  5. output_file = "/etc/ansible/hosts"
  6. # 先清空 hosts 文件并写入 Ansible 组名
  7. with open(output_file, 'w') as f:
  8.     f.write("[All-server]\n")
  9. # 读取 user.txt 并格式化内容
  10. with open(input_file, 'r') as infile:
  11.     with open(output_file, 'a') as outfile:
  12.         for line in infile:
  13.             ip, user, password = line.strip().split()
  14.             outfile.write("{ip} ansible_ssh_port=22 ansible_ssh_user={user} ansible_ssh_pass='{password}'\n".format(
  15.                 ip=ip, user=user, password=password
  16.             ))
  17. print("Ansible hosts 文件已生成: {}".format(output_file))
复制代码
使用说明:

脚本工作原理:

最后的运行成果:


可以选择此中一种方式来自动化生成 Ansible 主机清单文件,并直接使用它来管理 100 台服务器,这里我自己推荐使用Shell方便快捷。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4