使用Ansible自动化配置Kubernetes集群节点的完整流程与常见问题排查指南

引言:为什么选择Ansible管理Kubernetes部署
在现代云原生架构中,Kubernetes已经成为容器编排的标准。然而,手动配置Kubernetes集群节点是一项复杂且容易出错的任务。Ansible作为一款强大的自动化工具,通过声明式的YAML语法和无代理(Agentless)架构,为Kubernetes集群的部署和管理提供了理想的解决方案。
使用Ansible自动化配置Kubernetes集群节点的主要优势包括:
一致性
:确保所有节点的配置完全相同,避免”配置漂移”
可重复性
:一次编写,多次执行,保证部署结果可预测
幂等性
:多次执行不会对已配置的系统产生副作用
文档化
:Playbook本身就是部署文档,便于团队协作和知识传承
环境准备与基础配置
1. 确认系统要求
在开始之前,确保你的环境满足以下要求:
Ansible版本
:2.9或更高版本(推荐2.10+)
操作系统
:所有节点运行相同的Linux发行版(推荐Ubuntu 20.04 LTS或CentOS 7/8)
网络配置
:所有节点之间网络互通,特别是控制平面和工作节点之间
硬件要求
:
控制节点:至少2核CPU,4GB内存
工作节点:根据工作负载需求,通常至少2核CPU,4GB内存
2. 准备Ansible控制节点
在你的管理机上安装Ansible:
# Ubuntu/Debian
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository –yes –update ppa:ansible/ansible
sudo apt install ansible

# CentOS/RHEL
sudo yum install epel-release
sudo yum install ansible

# 验证安装
ansible –version
3. 配置SSH免密登录
Ansible通过SSH连接到目标节点,配置免密登录可以简化流程:
# 在Ansible控制节点上生成SSH密钥(如果还没有)
ssh-keygen -t rsa -b 4096 -C “ansible@k8s-deploy”

# 将公钥复制到所有Kubernetes节点
ssh-copy-id user@master-node-ip
ssh-copy-id user@worker-node-1-ip
ssh-copy-id user@worker-node-2-ip

# 测试连接
ansible all -i inventory.ini -m ping
Ansible项目结构设计
一个良好的项目结构是成功部署的关键。推荐以下目录结构:
kubernetes-ansible/
├── inventory/
│ ├── production.ini # 生产环境清单
│ └── staging.ini # 测试环境清单
├── group_vars/
│ ├── all.yml # 所有主机的通用变量
│ ├── masters.yml # 控制节点特定变量
│ └── workers.yml # 工作节点特定变量
├── roles/
│ ├── common/ # 通用配置角色
│ ├── docker/ # 容器运行时配置
│ ├── kubernetes/ # Kubernetes组件安装
│ ├── master/ # 控制节点配置
│ └── worker/ # 工作节点配置
├── playbooks/
│ ├── site.yml # 主Playbook
│ ├── deploy-master.yml # 部署控制节点
│ └── deploy-worker.yml # 部署工作节点
├── templates/ # 配置文件模板
└── files/ # 静态文件
创建库存文件(inventory.ini)
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa

[masters]
master1 ansible_host=192.168.1.100
master2 ansible_host=192.168.1.101
master3 ansible_host=192.168.1.102

[workers]
worker1 ansible_host=192.168.1.200
worker2 ansible_host=192.168.1.201
worker3 ansible_host=192.168.1.202

[k8s_cluster:children]
masters
workers
定义组变量(group_vars/all.yml)
# Kubernetes集群通用配置
k8s_version: “1.28.2”
container_runtime: “docker” # 或 “containerd”
pod_network_cidr: “10.244.0.0/16”
service_cidr: “10.96.0.0/12”

# Docker配置
docker_version: “5:24.0.6-1~ubuntu.20.04~focal”

# 网络插件
cni_plugin: “flannel” # 或 “calico”, “cilium”

# 系统配置
swap_off: true
hostname_override: “{{ inventory_hostname }}”
核心角色开发
1. 通用配置角色(roles/common)
这个角色负责所有节点都需要的基础配置。
tasks/main.yml
:
—
– name: 更新apt缓存(Ubuntu/Debian)
apt:
update_cache: yes
when: ansible_os_family == “Debian”
changed_when: false

– name: 禁用swap(如果需要)
shell: |
swapoff -a
sed -i ‘/ swap / s/^\(.*\)$/#\1/g’ /etc/fstab
when: swap_off
changed_when: true

– name: 设置主机名
hostname:
name: “{{ hostname_override }}”

– name: 配置内核参数
sysctl:
name: “{{ item.name }}”
value: “{{ item.value }}”
state: present
reload: yes
loop:
– { name: ‘net.bridge.bridge-nf-call-iptables’, value: ‘1’ }
– { name: ‘net.bridge.bridge-nf-call-ip6tables’, value: ‘1’ }
– { name: ‘net.ipv4.ip_forward’, value: ‘1’ }

– name: 加载br_netfilter模块
modprobe:
name: br_netfilter
state: present

– name: 配置hosts文件
lineinfile:
path: /etc/hosts
line: “{{ item }}”
state: present
loop: “{{ k8s_hosts_entries }}”
when: k8s_hosts_entries is defined
2. Docker容器运行时角色(roles/docker)
tasks/main.yml
:
—
– name: 安装Docker依赖包
apt:
name:
– apt-transport-https
– ca-certificates
– curl
– gnupg
– lsb-release
state: present
when: ansible_os_family == “Debian”

– name: 添加Docker官方GPG密钥
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
state: present
when: ansible_os_family == “Debian”

– name: 添加Docker仓库
apt_repository:
repo: “deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable”
state: present
when: ansible_os_family == “Debian”

– name: 安装Docker
apt:
name: “docker-ce={{ docker_version }}”
state: present
update_cache: yes

– name: 创建Docker配置目录
file:
path: /etc/docker
state: directory
mode: ‘0755’

– name: 配置Docker守护进程
copy:
dest: /etc/docker/daemon.json
content: |
{
“exec-opts”: [“native.cgroupdriver=systemd”],
“log-driver”: “json-file”,
“log-opts”: {
“max-size”: “100m”
},
“storage-driver”: “overlay2”
}

– name: 启动并启用Docker服务
systemd:
name: docker
state: started
enabled: yes
daemon_reload: yes
3. Kubernetes组件角色(roles/kubernetes)
tasks/main.yml
:
—
– name: 安装Kubernetes APT密钥
apt_key:
url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
state: present

– name: 添加Kubernetes仓库
apt_repository:
repo: “deb https://apt.kubernetes.io/ kubernetes-xenial main”
state: present
filename: kubernetes

– name: 安装Kubernetes组件
apt:
name:
– kubelet={{ k8s_version }}-00
– kubeadm={{ k8s_version }}-00
– kubectl={{ k8s_version }}-00
state: present
update_cache: yes

– name: 锁定Kubernetes版本(防止意外升级)
dpkg_selections:
name: “{{ item }}”
selection: hold
loop:
– kubelet
– kubeadm
– kubectl

– name: 启动kubelet服务
systemd:
name: kubelet
state: started
enabled: yes
4. 控制节点角色(roles/master)
tasks/main.yml
:
—
– name: 初始化Kubernetes集群(仅在第一个控制节点)
shell: |
kubeadm init \
–pod-network-cidr={{ pod_network_cidr }} \
–service-cidr={{ service_cidr }} \
–control-plane-endpoint=”{{ k8s_control_plane_endpoint }}” \
–upload-certs \
–kubernetes-version=v{{ k8s_version }}
register: init_result
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: “inventory_hostname == groups[‘masters’][0]”

– name: 提取加入命令
set_fact:
join_command: “{{ init_result.stdout | regex_search(‘kubeadm join .*’) }}”
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: init_result is defined

– name: 创建.kube目录
file:
path: /home/{{ ansible_user }}/.kube
state: directory
owner: “{{ ansible_user }}”
group: “{{ ansible_user }}”
mode: ‘0755’

– name: 复制admin.conf
copy:
src: /etc/kubernetes/admin.conf
dest: /home/{{ ansible_user }}/.kube/config
remote_src: yes
owner: “{{ ansible_user }}”
group: “{{ ansible_user }}”
mode: ‘0600’
when: “inventory_hostname == groups[‘masters’][0]”

– name: 安装网络插件(Flannel示例)
shell: |
kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
args:
chdir: /home/{{ ansible_user }}
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: “inventory_hostname == groups[‘masters’][0] and cni_plugin == ‘flannel’”

– name: 等待控制节点就绪
shell: kubectl get nodes {{ inventory_hostname }} -o jsonpath='{.status.conditions[?(@.type==”Ready”)].status}’
register: node_status
until: node_status.stdout == “True”
retries: 30
delay: 10
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
when: “inventory_hostname == groups[‘masters’][0]”
5. 工作节点角色(roles/worker)
tasks/main.yml
:
—
– name: 获取加入命令
set_fact:
join_command: “{{ hostvars[groups[‘masters’][0]].join_command }}”
when: hostvars[groups[‘masters’][0]].join_command is defined

– name: 加入集群
shell: “{{ join_command }}”
register: join_result
until: join_result.rc == 0
retries: 5
delay: 15

– name: 等待节点就绪
shell: kubectl get nodes {{ inventory_hostname }} -o jsonpath='{.status.conditions[?(@.type==”Ready”)].status}’
register: node_status
until: node_status.stdout == “True”
retries: 30
delay: 10
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
delegate_to: “{{ groups[‘masters’][0] }}”
主Playbook编排
playbooks/site.yml
—
– name: 配置所有Kubernetes节点
hosts: k8s_cluster
become: yes
roles:
– common
– docker
– kubernetes

– name: 配置控制节点
hosts: masters
become: yes
roles:
– master

– name: 配置工作节点
hosts: workers
become: yes
roles:
– worker
vars:
# 确保工作节点在控制节点之后执行
ansible_run_tags: [‘always’]
执行部署流程
1. 语法检查
ansible-playbook -i inventory/production.ini –syntax-check playbooks/site.yml
2. 空运行(Dry Run)
ansible-playbook -i inventory/production.ini –check playbooks/site.yml
3. 正式执行
# 使用详细输出
ansible-playbook -i inventory/production.ini playbooks/site.yml -v

# 并行执行(加快速度)
ansible-playbook -i inventory/production.ini playbooks/site.yml -f 10

# 限制只执行特定角色
ansible-playbook -i inventory/production.ini playbooks/site.yml –tags “docker”
常见问题排查指南
问题1:SSH连接失败
症状
:
msg: “Failed to connect to the host via ssh: Permission denied (publickey,password).”
排查步骤
:
验证SSH密钥路径正确
检查目标节点的SSH服务状态:
systemctl status sshd
确认
/etc/ssh/sshd_config
中
PasswordAuthentication
或
PubkeyAuthentication
设置正确
测试手动SSH连接:
ssh -i ~/.ssh/id_rsa user@host
解决方案
:
# 重新复制密钥
ssh-copy-id -i ~/.ssh/id_rsa.pub user@host

# 或在Ansible命令中指定密码(临时方案)
ansible-playbook -i inventory.ini playbooks/site.yml –ask-pass –ask-become-pass
问题2:kubeadm初始化失败
症状
:
[init] Using Kubernetes version: v1.28.2
[preflight] Running pre-flight checks
error execution phase preflight: [preflight] Some fatal errors occurred:
[ERROR FileContent–proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1
排查步骤
:
检查内核参数是否加载:
cat /proc/sys/net/bridge/bridge-nf-call-iptables
lsmod | grep br_netfilter
验证sysctl配置:
sysctl -a | grep bridge-nf-call-iptables
解决方案
:
# 临时设置
sudo sysctl -w net.bridge.bridge-nf-call-iptables=1
sudo modprobe br_netfilter

# 永久设置(Ansible角色中已包含)
echo ‘net.bridge.bridge-nf-call-iptables=1’ | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
问题3:节点加入集群失败
症状
:
error execution phase preflight: [preflight] Running pre-flight checks
[preflight] Some fatal errors occurred:
[ERROR FileContent–proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1
排查步骤
:
检查控制节点的API Server是否可达:
curl -k https://:6443/healthz
验证时间同步:
date
timedatectl status
检查防火墙规则:
sudo ufw status
sudo iptables -L -n
解决方案
:
# 确保时间同步
sudo apt install chrony
sudo systemctl enable –now chrony

# 开放必要端口
sudo ufw allow 6443/tcp
sudo ufw allow 2379-2380/tcp
sudo ufw allow 10250/tcp
sudo ufw allow 10257/tcp
sudo ufw allow 10259/tcp
问题4:Pod网络不通
症状
:
Pod无法解析DNS
Pod之间无法通信
kubectl get pods
显示Pending状态
排查步骤
:
检查CNI插件是否正确安装:
kubectl get pods -n kube-system | grep flannel
验证网络插件Pod状态:
kubectl describe pod -n kube-system
检查节点路由:
ip route
解决方案
:
# 重新应用网络插件
kubectl delete -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml

# 如果使用Calico
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/calico.yaml
问题5:kubelet服务启动失败
症状
:
Job for kubelet.service failed because the control process exited with error code.
排查步骤
:
查看kubelet日志:
journalctl -u kubelet -f
检查容器运行时:
docker ps # 或 crictl ps
验证cgroup驱动:
docker info | grep Cgroup
解决方案
:
# 确保Docker使用systemd驱动
cat > /etc/docker/daemon.json < .vault_pass
chmod 600 .vault_pass

# 加密变量文件
ansible-vault encrypt group_vars/secrets.yml

# 在Playbook中引用
vars_files:
– group_vars/secrets.yml

# 运行时提供密码
ansible-playbook –vault-password-file .vault_pass site.yml
2. 高可用集群配置
对于高可用集群,修改控制节点配置:
# group_vars/masters.yml
k8s_control_plane_endpoint: “k8s-api.example.com:6443”
k8s_apiserver_extra_args:
– –apiserver-cert-extra-sans=k8s-api.example.com
– –control-plane-endpoint=k8s-api.example.com:6443
3. 使用标签选择性执行
# 在Playbook中添加标签
– name: 配置控制节点
hosts: masters
become: yes
roles:
– master
tags:
– master
– control-plane

# 执行时使用标签
ansible-playbook -i inventory.ini site.yml –tags “master”
4. 集成CI/CD
在GitLab CI中使用:
# .gitlab-ci.yml
deploy_k8s:
stage: deploy
script:
– ansible-playbook -i inventory/production.ini playbooks/site.yml –vault-password-file $VAULT_PASS
only:
– main
environment: production
总结
通过Ansible自动化配置Kubernetes集群,我们实现了:
标准化部署
:消除手动配置差异
快速恢复
:灾难恢复时间从小时级降至分钟级
版本控制
:所有配置都在Git中管理
团队协作
:降低对特定人员的依赖
记住,成功的自动化部署依赖于:
详细的前期规划和测试
完善的监控和日志
定期更新和维护Playbook
文档化所有变更
遇到问题时,始终从日志入手,逐步缩小问题范围,利用Ansible的
-v
(详细模式)和
–check
(dry-run)功能来诊断问题。
# 使用Ansible自动化配置Kubernetes集群节点的完整流程与常见问题排查指南
引言:为什么选择Ansible管理Kubernetes部署
在现代云原生架构中,Kubernetes已经成为容器编排的标准。然而,手动配置Kubernetes集群节点是一项复杂且容易出错的任务。Ansible作为一款强大的自动化工具,通过声明式的YAML语法和无代理(Agentless)架构,为Kubernetes集群的部署和管理提供了理想的解决方案。
使用Ansible自动化配置Kubernetes集群节点的主要优势包括:
一致性
:确保所有节点的配置完全相同,避免”配置漂移”
可重复性
:一次编写,多次执行,保证部署结果可预测
幂等性
:多次执行不会对已配置的系统产生副作用
文档化
:Playbook本身就是部署文档,便于团队协作和知识传承
环境准备与基础配置
1. 确认系统要求
在开始之前,确保你的环境满足以下要求:
Ansible版本
:2.9或更高版本(推荐2.10+)
操作系统
:所有节点运行相同的Linux发行版(推荐Ubuntu 20.04 LTS或CentOS 7/8)
网络配置
:所有节点之间网络互通,特别是控制平面和工作节点之间
硬件要求
:
控制节点:至少2核CPU,4GB内存
工作节点:根据工作负载需求,通常至少2核CPU,4GB内存
2. 准备Ansible控制节点
在你的管理机上安装Ansible:
# Ubuntu/Debian
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository –yes –update ppa:ansible/ansible
sudo apt install ansible

# CentOS/RHEL
sudo yum install epel-release
sudo yum install ansible

# 验证安装
ansible –version
3. 配置SSH免密登录
Ansible通过SSH连接到目标节点,配置免密登录可以简化流程:
# 在Ansible控制节点上生成SSH密钥(如果还没有)
ssh-keygen -t rsa -b 4096 -C “ansible@k8s-deploy”

# 将公钥复制到所有Kubernetes节点
ssh-copy-id user@master-node-ip
ssh-copy-id user@worker-node-1-ip
ssh-copy-id user@worker-node-2-ip

# 测试连接
ansible all -i inventory.ini -m ping
Ansible项目结构设计
一个良好的项目结构是成功部署的关键。推荐以下目录结构:
kubernetes-ansible/
├── inventory/
│ ├── production.ini # 生产环境清单
│ └── staging.ini # 测试环境清单
├── group_vars/
│ ├── all.yml # 所有主机的通用变量
│ ├── masters.yml # 控制节点特定变量
│ └── workers.yml # 工作节点特定变量
├── roles/
│ ├── common/ # 通用配置角色
│ ├── docker/ # 容器运行时配置
│ ├── kubernetes/ # Kubernetes组件安装
│ ├── master/ # 控制节点配置
│ └── worker/ # 工作节点配置
├── playbooks/
│ ├── site.yml # 主Playbook
│ ├── deploy-master.yml # 部署控制节点
│ └── deploy-worker.yml # 部署工作节点
├── templates/ # 配置文件模板
└── files/ # 静态文件
创建库存文件(inventory.ini)
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa

[masters]
master1 ansible_host=192.168.1.100
master2 ansible_host=192.168.1.101
master3 ansible_host=192.168.1.102

[workers]
worker1 ansible_host=192.168.1.200
worker2 ansible_host=192.168.1.201
worker3 ansible_host=192.168.1.202

[k8s_cluster:children]
masters
workers
定义组变量(group_vars/all.yml)
# Kubernetes集群通用配置
k8s_version: “1.28.2”
container_runtime: “docker” # 或 “containerd”
pod_network_cidr: “10.244.0.0/16”
service_cidr: “10.96.0.0/12”

# Docker配置
docker_version: “5:24.0.6-1~ubuntu.20.04~focal”

# 网络插件
cni_plugin: “flannel” # 或 “calico”, “cilium”

# 系统配置
swap_off: true
hostname_override: “{{ inventory_hostname }}”
核心角色开发
1. 通用配置角色(roles/common)
这个角色负责所有节点都需要的基础配置。
tasks/main.yml
:
—
– name: 更新apt缓存(Ubuntu/Debian)
apt:
update_cache: yes
when: ansible_os_family == “Debian”
changed_when: false

– name: 禁用swap(如果需要)
shell: |
swapoff -a
sed -i ‘/ swap / s/^\(.*\)$/#\1/g’ /etc/fstab
when: swap_off
changed_when: true

– name: 设置主机名
hostname:
name: “{{ hostname_override }}”

– name: 配置内核参数
sysctl:
name: “{{ item.name }}”
value: “{{ item.value }}”
state: present
reload: yes
loop:
– { name: ‘net.bridge.bridge-nf-call-iptables’, value: ‘1’ }
– { name: ‘net.bridge.bridge-nf-call-ip6tables’, value: ‘1’ }
– { name: ‘net.ipv4.ip_forward’, value: ‘1’ }

– name: 加载br_netfilter模块
modprobe:
name: br_netfilter
state: present

– name: 配置hosts文件
lineinfile:
path: /etc/hosts
line: “{{ item }}”
state: present
loop: “{{ k8s_hosts_entries }}”
when: k8s_hosts_entries is defined
2. Docker容器运行时角色(roles/docker)
tasks/main.yml
:
—
– name: 安装Docker依赖包
apt:
name:
– apt-transport-https
– ca-certificates
– curl
– gnupg
– lsb-release
state: present
when: ansible_os_family == “Debian”

– name: 添加Docker官方GPG密钥
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
state: present
when: ansible_os_family == “Debian”

– name: 添加Docker仓库
apt_repository:
repo: “deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable”
state: present
when: ansible_os_family == “Debian”

– name: 安装Docker
apt:
name: “docker-ce={{ docker_version }}”
state: present
update_cache: yes

– name: 创建Docker配置目录
file:
path: /etc/docker
state: directory
mode: ‘0755’

– name: 配置Docker守护进程
copy:
dest: /etc/docker/daemon.json
content: |
{
“exec-opts”: [“native.cgroupdriver=systemd”],
“log-driver”: “json-file”,
“log-opts”: {
“max-size”: “100m”
},
“storage-driver”: “overlay2”
}

– name: 启动并启用Docker服务
systemd:
name: docker
state: started
enabled: yes
daemon_reload: yes
3. Kubernetes组件角色(roles/kubernetes)
tasks/main.yml
:
—
– name: 安装Kubernetes APT密钥
apt_key:
url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
state: present

– name: 添加Kubernetes仓库
apt_repository:
repo: “deb https://apt.kubernetes.io/ kubernetes-xenial main”
state: present
filename: kubernetes

– name: 安装Kubernetes组件
apt:
name:
– kubelet={{ k8s_version }}-00
– kubeadm={{ k8s_version }}-00
– kubectl={{ k8s_version }}-00
state: present
update_cache: yes

– name: 锁定Kubernetes版本(防止意外升级)
dpkg_selections:
name: “{{ item }}”
selection: hold
loop:
– kubelet
– kubeadm
– kubectl

– name: 启动kubelet服务
systemd:
name: kubelet
state: started
enabled: yes
4. 控制节点角色(roles/master)
tasks/main.yml
:
—
– name: 初始化Kubernetes集群(仅在第一个控制节点)
shell: |
kubeadm init \
–pod-network-cidr={{ pod_network_cidr }} \
–service-cidr={{ service_cidr }} \
–control-plane-endpoint=”{{ k8s_control_plane_endpoint }}” \
–upload-certs \
–kubernetes-version=v{{ k8s_version }}
register: init_result
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: “inventory_hostname == groups[‘masters’][0]”

– name: 提取加入命令
set_fact:
join_command: “{{ init_result.stdout | regex_search(‘kubeadm join .*’) }}”
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: init_result is defined

– name: 创建.kube目录
file:
path: /home/{{ ansible_user }}/.kube
state: directory
owner: “{{ ansible_user }}”
group: “{{ ansible_user }}”
mode: ‘0755’

– name: 复制admin.conf
copy:
src: /etc/kubernetes/admin.conf
dest: /home/{{ ansible_user }}/.kube/config
remote_src: yes
owner: “{{ ansible_user }}”
group: “{{ ansible_user }}”
mode: ‘0600’
when: “inventory_hostname == groups[‘masters’][0]”

– name: 安装网络插件(Flannel示例)
shell: |
kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
args:
chdir: /home/{{ ansible_user }}
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
run_once: true
delegate_to: “{{ groups[‘masters’][0] }}”
when: “inventory_hostname == groups[‘masters’][0] and cni_plugin == ‘flannel’”

– name: 等待控制节点就绪
shell: kubectl get nodes {{ inventory_hostname }} -o jsonpath='{.status.conditions[?(@.type==”Ready”)].status}’
register: node_status
until: node_status.stdout == “True”
retries: 30
delay: 10
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
when: “inventory_hostname == groups[‘masters’][0]”
5. 工作节点角色(roles/worker)
tasks/main.yml
:
—
– name: 获取加入命令
set_fact:
join_command: “{{ hostvars[groups[‘masters’][0]].join_command }}”
when: hostvars[groups[‘masters’][0]].join_command is defined

– name: 加入集群
shell: “{{ join_command }}”
register: join_result
until: join_result.rc == 0
retries: 5
delay: 15

– name: 等待节点就绪
shell: kubectl get nodes {{ inventory_hostname }} -o jsonpath='{.status.conditions[?(@.type==”Ready”)].status}’
register: node_status
until: node_status.stdout == “True”
retries: 30
delay: 10
environment:
KUBECONFIG: /home/{{ ansible_user }}/.kube/config
delegate_to: “{{ groups[‘masters’][0] }}”
主Playbook编排
playbooks/site.yml
—
– name: 配置所有Kubernetes节点
hosts: k8s_cluster
become: yes
roles:
– common
– docker
– kubernetes

– name: 配置控制节点
hosts: masters
become: yes
roles:
– master

– name: 配置工作节点
hosts: workers
become: yes
roles:
– worker
vars:
# 确保工作节点在控制节点之后执行
ansible_run_tags: [‘always’]
执行部署流程
1. 语法检查
ansible-playbook -i inventory/production.ini –syntax-check playbooks/site.yml
2. 空运行(Dry Run)
ansible-playbook -i inventory/production.ini –check playbooks/site.yml
3. 正式执行
# 使用详细输出
ansible-playbook -i inventory/production.ini playbooks/site.yml -v

# 并行执行(加快速度)
ansible-playbook -i inventory/production.ini playbooks/site.yml -f 10

# 限制只执行特定角色
ansible-playbook -i inventory/production.ini playbooks/site.yml –tags “docker”
常见问题排查指南
问题1:SSH连接失败
症状
:
msg: “Failed to connect to the host via ssh: Permission denied (publickey,password).”
排查步骤
:
验证SSH密钥路径正确
检查目标节点的SSH服务状态:
systemctl status sshd
确认
/etc/ssh/sshd_config
中
PasswordAuthentication
或
PubkeyAuthentication
设置正确
测试手动SSH连接:
ssh -i ~/.ssh/id_rsa user@host
解决方案
:
# 重新复制密钥
ssh-copy-id -i ~/.ssh/id_rsa.pub user@host

# 或在Ansible命令中指定密码(临时方案)
ansible-playbook -i inventory.ini playbooks/site.yml –ask-pass –ask-become-pass
问题2:kubeadm初始化失败
症状
:
[init] Using Kubernetes version: v1.28.2
[preflight] Running pre-flight checks
error execution phase preflight: [preflight] Some fatal errors occurred:
[ERROR FileContent–proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1
排查步骤
:
检查内核参数是否加载:
cat /proc/sys/net/bridge/bridge-nf-call-iptables
lsmod | grep br_netfilter
验证sysctl配置:
sysctl -a | grep bridge-nf-call-iptables
解决方案
:
# 临时设置
sudo sysctl -w net.bridge.bridge-nf-call-iptables=1
sudo modprobe br_netfilter

# 永久设置(Ansible角色中已包含)
echo ‘net.bridge.bridge-nf-call-iptables=1’ | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
问题3:节点加入集群失败
症状
:
error execution phase preflight: [preflight] Running pre-flight checks
[preflight] Some fatal errors occurred:
[ERROR FileContent–proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1
排查步骤
:
检查控制节点的API Server是否可达:
curl -k https://:6443/healthz
验证时间同步:
date
timedatectl status
检查防火墙规则:
sudo ufw status
sudo iptables -L -n
解决方案
:
# 确保时间同步
sudo apt install chrony
sudo systemctl enable –now chrony

# 开放必要端口
sudo ufw allow 6443/tcp
sudo ufw allow 2379-2380/tcp
sudo ufw allow 10250/tcp
sudo ufw allow 10257/tcp
sudo ufw allow 10259/tcp
问题4:Pod网络不通
症状
:
Pod无法解析DNS
Pod之间无法通信
kubectl get pods
显示Pending状态
排查步骤
:
检查CNI插件是否正确安装:
kubectl get pods -n kube-system | grep flannel
验证网络插件Pod状态:
kubectl describe pod -n kube-system
检查节点路由:
ip route
解决方案
:
# 重新应用网络插件
kubectl delete -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml

# 如果使用Calico
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/calico.yaml
问题5:kubelet服务启动失败
症状
:
Job for kubelet.service failed because the control process exited with error code.
排查步骤
:
查看kubelet日志:
journalctl -u kubelet -f
检查容器运行时:
docker ps # 或 crictl ps
验证cgroup驱动:
docker info | grep Cgroup
解决方案
:
# 确保Docker使用systemd驱动
cat > /etc/docker/daemon.json < .vault_pass
chmod 600 .vault_pass

# 加密变量文件
ansible-vault encrypt group_vars/secrets.yml

# 在Playbook中引用
vars_files:
– group_vars/secrets.yml

# 运行时提供密码
ansible-playbook –vault-password-file .vault_pass site.yml
2. 高可用集群配置
对于高可用集群,修改控制节点配置:
# group_vars/masters.yml
k8s_control_plane_endpoint: “k8s-api.example.com:6443”
k8s_apiserver_extra_args:
– –apiserver-cert-extra-sans=k8s-api.example.com
– –control-plane-endpoint=k8s-api.example.com:6443
3. 使用标签选择性执行
# 在Playbook中添加标签
– name: 配置控制节点
hosts: masters
become: yes
roles:
– master
tags:
– master
– control-plane

# 执行时使用标签
ansible-playbook -i inventory.ini site.yml –tags “master”
4. 集成CI/CD
在GitLab CI中使用:
# .gitlab-ci.yml
deploy_k8s:
stage: deploy
script:
– ansible-playbook -i inventory/production.ini playbooks/site.yml –vault-password-file $VAULT_PASS
only:
– main
environment: production
总结
通过Ansible自动化配置Kubernetes集群,我们实现了:
标准化部署
:消除手动配置差异
快速恢复
:灾难恢复时间从小时级降至分钟级
版本控制
:所有配置都在Git中管理
团队协作
:降低对特定人员的依赖
记住,成功的自动化部署依赖于:
详细的前期规划和测试
完善的监控和日志
定期更新和维护Playbook
文档化所有变更
遇到问题时,始终从日志入手,逐步缩小问题范围,利用Ansible的
-v
(详细模式)和
–check
(dry-run)功能来诊断问题。