Skip to content

配置管理 (Configuration Management)

一、配置管理概述

什么是配置管理

配置管理 (Configuration Management):用自动化方式管理基础设施和应用配置

  • 描述式: "我想要这样的状态"
  • 自动化: 工具自动达到
  • 可重复: 在多台机器一致
  • 可追溯: Git 记录变更
  • 可恢复: 失败可回滚

配置管理的核心价值

  • 一致性: 所有机器配置相同
  • 自动化: 减少手工操作
  • 可扩展: 轻松管理 1 万台
  • 可审计: Git 记录一切
  • 快速恢复: 出问题一键重建
  • 知识沉淀: 配置即文档

配置管理 vs 传统脚本

维度 传统脚本 配置管理工具
状态 命令式 声明式
一致性 难保证 保证
幂等性 需自己实现 内置
失败恢复 难 内置
报告 需自己写 内置
学习曲线 低 中
适合规模 10-50 台 100-10000 台

二、配置管理工具概览

1. 主流工具

工具 类型 推送/拉取 语言 特点
Ansible 通用 推送 Python 简单,无客户端
SaltStack 通用 推送/拉取 Python 高速,可扩展
Puppet 通用 拉取 Ruby 老牌,模型化
Chef 通用 拉取 Ruby 灵活,编程式
CFEngine 通用 拉取 C 老牌,轻量
Ansible Tower 商业 - - Ansible 企业版
SaltStack Enterprise 商业 - - Salt 企业版

2. 新兴工具

  • Terraform: 基础设施即代码 (IaC)
  • Pulumi: 编程式 IaC
  • Crossplane: K8s 上做 IaC
  • Vagrant: 开发环境
  • AWS CloudFormation / Azure ARM / GCP Deployment Manager
  • Helm: K8s 包管理

3. 容器化场景

  • Kustomize: K8s 配置覆盖
  • Helm: K8s 包管理
  • Argo CD / Flux: GitOps
  • OpenTofu: Terraform 分支

三、Ansible 详解

1. Ansible 概述

Ansible:推送式、无客户端、YAML 配置

  • 只需要 SSH + Python
  • 学习曲线低
  • 适合中小规模(< 5000 节点)
  • 红帽维护

特点:

  • 声明式: 描述期望状态
  • 幂等性: 多次执行结果一致
  • 无代理: 不需要装客户端
  • 模块化: 1000+ 内置模块
  • Playbook: YAML 配置
  • Inventory: 主机清单

2. 安装

# RHEL/CentOS
yum install ansible

# Ubuntu
apt install ansible

# pip
pip install ansible

# 验证
ansible --version

3. Inventory (主机清单)

静态 Inventory (/etc/ansible/hosts 或自定义):

# 简单格式
[webservers]
web1.example.com
web2.example.com
web3.example.com

[databases]
db1.example.com
db2.example.com

[loadbalancers]
lb1.example.com

# 变量
[webservers]
web1.example.com http_port=80
web2.example.com http_port=8080

# 子组
[web:children]
webservers
loadbalancers

# 范围
[webservers]
web[01:10].example.com

# 主机变量
[webservers]
web1.example.com ansible_host=192.168.1.10

动态 Inventory:从云 API 拉取(AWS EC2、GCP Compute、Azure、OpenStack、Kubernetes)

# aws_ec2.yml
plugin: aws_ec2
regions:
  - us-east-1
keyed_groups:
  - key: tags.Role
    prefix: role

4. Ad-hoc 命令

# 测试连接
ansible all -m ping

# 执行命令
ansible webservers -m shell -a "uptime"
ansible all -m command -a "df -h" --become
ansible all -m shell -a "systemctl restart nginx" --become

# 复制文件
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts"

# 安装包
ansible webservers -m yum -a "name=httpd state=present" --become

# 看主机信息
ansible all -m setup
ansible web1 -m setup -a "filter=ansible_eth0"

# 指定用户
ansible all -m ping -u alice

# 指定 inventory
ansible -i myhosts all -m ping

5. Playbook (剧本)

基础 Playbook (site.yml):

---
- name: 配置 Web 服务器
  hosts: webservers
  become: yes
  vars:
    http_port: 80
    max_clients: 200
  tasks:
    - name: 安装 httpd
      yum:
        name: httpd
        state: present
      notify: restart httpd

    - name: 启动并启用 httpd
      service:
        name: httpd
        state: started
        enabled: yes

    - name: 部署网站配置
      template:
        src: templates/httpd.conf.j2
        dest: /etc/httpd/conf/httpd.conf
        owner: root
        group: root
        mode: '0644'
      notify: restart httpd

    - name: 部署网站内容
      copy:
        src: files/index.html
        dest: /var/www/html/index.html

    - name: 开放防火墙
      firewalld:
        service: http
        permanent: yes
        state: enabled
      notify: reload firewalld

    - name: SELinux 允许 httpd
      seboolean:
        name: httpd_can_network_connect
        state: yes
        persistent: yes

  handlers:
    - name: restart httpd
      service:
        name: httpd
        state: restarted

    - name: reload firewalld
      service:
        name: firewalld
        state: reloaded

6. Playbook 运行

# 检查语法
ansible-playbook --syntax-check site.yml

# 干跑(不执行)
ansible-playbook --check site.yml

# 详细
ansible-playbook -v site.yml
ansible-playbook -vvv site.yml

# 步骤执行
ansible-playbook --start-at-task="安装 httpd" site.yml
ansible-playbook --step site.yml

# 限制主机
ansible-playbook -l web1 site.yml
ansible-playbook -l webservers site.yml

# 并发
ansible-playbook -f 10 site.yml

# 标签
ansible-playbook -t install site.yml
ansible-playbook --skip-tags install site.yml

7. 常用模块

模块 用途
command / shell 执行命令
copy / fetch 文件复制/拉取
file 文件属性
lineinfile / replace 改行
template 模板渲染
service / systemd 服务
yum / apt 包管理
user / group 用户
uri HTTP 请求
debug 调试输出
stat 文件状态
cron 定时任务
mount 挂载
firewalld / iptables 防火墙
selinux SELinux
reboot 重启
docker_container Docker
k8s K8s
git Git 仓库
pip Python 包
npm Node.js 包

8. 变量与事实

变量类型:

# vars: 在 playbook 中
- hosts: web
  vars:
    http_port: 80
  tasks:
    - debug:
        msg: "Port: {{ http_port }}"

# vars_files: 外部文件
vars_files:
  - vars/common.yml
  - vars/{{ env }}.yml

# vars_prompt: 提示输入
vars_prompt:
  - name: username
    prompt: "Enter username"
    private: no

# host_vars / group_vars
# group_vars/all.yml       所有
# group_vars/web.yml        web 组
# host_vars/web1.yml        web1 主机

# 优先级: 命令行 > vars_prompt > host_vars > group_vars > vars_files > vars > defaults

Jinja2 模板:

# config.j2
{% for port in listen_ports %}
Listen {{ port }}
{% endfor %}

server {
    listen {{ http_port }};
    server_name {{ ansible_fqdn }};
    root {{ doc_root }};
    {% if ssl_enabled %}
    ssl on;
    {% endif %}
}

Facts (事实):Ansible 自动收集的主机信息

- debug:
    msg: >
      Host: {{ ansible_fqdn }}
      OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
      CPU: {{ ansible_processor_count }}
      Memory: {{ ansible_memtotal_mb }} MB
      IPs: {{ ansible_all_ipv4_addresses }}

9. 条件、循环、注册

- name: 条件
  hosts: all
  tasks:
    - name: 仅在 CentOS 装
      yum:
        name: epel-release
        state: present
      when: ansible_distribution == "CentOS"

- name: 循环
  hosts: all
  tasks:
    - name: 装多个包
      yum:
        name: "{{ item }}"
        state: present
      loop:
        - git
        - curl
        - vim
        - htop

- name: 循环字典
  hosts: all
  vars:
    users:
      - name: alice
        uid: 1001
      - name: bob
        uid: 1002
  tasks:
    - name: 创用户
      user:
        name: "{{ item.name }}"
        uid: "{{ item.uid }}"
      loop: "{{ users }}"

- name: 注册变量
  hosts: all
  tasks:
    - name: 查版本
      command: nginx -v
      register: nginx_version
      changed_when: false

    - name: 打印
      debug:
        msg: "{{ nginx_version.stderr }}"

    - name: 失败处理
      command: /bin/false
      failed_when: false
      register: result

    - name: 用结果
      debug:
        msg: "RC: {{ result.rc }}"
      when: result.rc != 0

10. Roles (角色)

Role 结构:

roles/
└── nginx/
    ├── tasks/
    │   └── main.yml
    ├── handlers/
    │   └── main.yml
    ├── templates/
    │   ├── nginx.conf.j2
    │   └── site.conf.j2
    ├── files/
    │   └── index.html
    ├── vars/
    │   └── main.yml
    ├── defaults/
    │   └── main.yml
    ├── meta/
    │   └── main.yml
    └── README.md

tasks/main.yml:

- name: 装 nginx
  yum:
    name: nginx
    state: present
  notify: restart nginx

- name: 部署配置
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify: restart nginx

- name: 部署网站
  copy:
    src: index.html
    dest: /usr/share/nginx/html/index.html

- name: 启动
  service:
    name: nginx
    state: started
    enabled: yes

handlers/main.yml:

- name: restart nginx
  service:
    name: nginx
    state: restarted

vars/main.yml:

nginx_port: 80
nginx_user: nginx

defaults/main.yml:

nginx_port: 80

使用 Role:

- hosts: webservers
  roles:
    - nginx
  vars:
    nginx_port: 8080

11. Ansible Vault (加密)

# 加密文件
ansible-vault encrypt secrets.yml
ansible-vault decrypt secrets.yml
ansible-vault rekey secrets.yml
ansible-vault edit secrets.yml

# 运行时
ansible-playbook --ask-vault-pass site.yml
ansible-playbook --vault-password-file ~/.vault site.yml
ansible-playbook --vault-id @prompt site.yml

# 部分加密
ansible-vault encrypt_string 'my_secret_password'
# 加密
db_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          66386439653...

12. Ansible Tower / AWX

Ansible Tower (商业) / AWX (开源):

  • Web UI
  • REST API
  • 角色权限
  • 作业模板
  • 调度
  • 通知
  • 审计

四、SaltStack 详解

1. SaltStack 概述

SaltStack:高速、可扩展的配置管理

  • 基于 ZeroMQ
  • 推送/拉取都支持
  • 适合大规模(> 5000 节点)
  • Python 编写

2. 架构

Master (控制端)
   ↓
Minions (被控端)

通信: ZeroMQ (pub/sub + req/rep)

3. 安装

# Master
yum install salt-master
systemctl enable --now salt-master

# Minion
yum install salt-minion
echo "master: salt.example.com" > /etc/salt/minion
systemctl enable --now salt-minion

# 接受 key
salt-key -L
salt-key -A
salt-key -a minion-name

4. 执行命令

# 全部
salt '*' test.ping
salt '*' cmd.run "uptime"

# 指定
salt 'web*' cmd.run "df -h"
salt -E 'web(1|2|3)' cmd.run "whoami"

# 状态 (state)
salt '*' state.apply

# 配置
salt '*' grains.items
salt '*' pillar.items

5. Salt State (SLS)

# /srv/salt/webserver.sls
nginx:
  pkg:
    - installed
  service:
    - running
    - enable: True
    - watch:
      - file: /etc/nginx/nginx.conf

/etc/nginx/nginx.conf:
  file:
    - managed
    - source: salt://nginx.conf
    - mode: 644

# 状态
salt '*' state.apply webserver
salt 'web*' state.highstate

6. Grains (静态信息)

salt '*' grains.ls
salt '*' grains.items
salt '*' grains.get os
salt '*' grains.get ipv4

7. Pillars (动态信息)

# /srv/pillar/top.sls
base:
  '*':
    - common

# /srv/pillar/common.sls
user: alice
sudo: true
salt '*' pillar.items
salt '*' pillar.get user

8. Salt 反应器 (Reactor)

# /etc/salt/master.d/reactor.conf
reactor:
  - 'salt/minion/*/start':
    - /srv/reactor/init.sls

# /srv/reactor/init.sls
{% if data['act'] == 'start' %}
highstate:
  cmd.state.apply:
    - tgt: {{ data['id'] }}
{% endif %}

9. Salt SSH

salt-ssh '*' test.ping
salt-ssh 'web*' cmd.run "uptime"

10. Salt 优缺点

优点:

  • 极快(ZeroMQ)
  • 大规模
  • 灵活(推送/拉取)

缺点:

  • 学习曲线陡
  • 社区比 Ansible 小

五、Puppet 详解

1. Puppet 概述

Puppet:拉取式、模型化的配置管理

  • 客户端主动拉配置
  • 适合大规模
  • 模型化语言
  • 商业版:Puppet Enterprise

2. 架构

Puppet Master
   ↓ 拉
Puppet Agent
   ↓
应用配置

3. 安装

# Master
yum install puppetserver
systemctl enable --now puppetserver

# Agent
yum install puppet
systemctl enable --now puppet

4. 资源声明 (Puppet DSL)

# /etc/puppet/code/environments/production/modules/nginx/manifests/init.pp
class nginx {
  package { 'nginx':
    ensure => installed,
  }

  service { 'nginx':
    ensure => running,
    enable => true,
    require => Package['nginx'],
  }

  file { '/etc/nginx/nginx.conf':
    ensure  => file,
    source  => 'puppet:///modules/nginx/nginx.conf',
    notify  => Service['nginx'],
    require => Package['nginx'],
  }
}

5. Puppet 应用

# 试运行
puppet apply --noop site.pp

# 真实应用
puppet apply site.pp

# 客户端拉配置
puppet agent --test

六、Chef 详解

1. Chef 概述

Chef:编程式、Ruby DSL、拉取式 配置管理

  • 客户端主动拉配置
  • 用 Ruby 写配置(灵活)
  • 适合大规模
  • 商业版:Chef Automate

架构:

Chef Server (中央)
   ↓ 拉
Chef Client (节点)

2. 核心概念

  • Cookbook: 配置集合(类似 Ansible Role)
  • Recipe: 单个配置脚本(Ruby)
  • Resource: 资源声明(package, service, file)
  • Attribute: 属性(类似变量)
  • Role: 角色组合
  • Environment: 环境(dev/staging/prod)
  • Knife: CLI 工具
  • Berkshelf: Cookbook 依赖管理
  • Test Kitchen: Cookbook 测试框架
  • ChefSpec: 单元测试

3. 安装

# Chef Workstation (本地开发)
wget https://packages.chef.io/files/stable/chef-workstation/23.7.1042/ubuntu/22.04/chef-workstation_23.7.1042-1_amd64.deb
dpkg -i chef-workstation_23.7.1042-1_amd64.deb

# 验证
chef --version
knife --version

4. Cookbook 结构

mycookbook/
├── recipes/
│   └── default.rb
├── attributes/
│   └── default.rb
├── files/
├── templates/
├── metadata.rb
├── Berksfile
└── test/
    └── integration/

5. Recipe 示例 (Ruby DSL)

# recipes/default.rb

# 装包
package 'nginx' do
  action :install
end

# 起服务
service 'nginx' do
  action [:enable, :start]
end

# 部署配置
template '/etc/nginx/nginx.conf' do
  source 'nginx.conf.erb'
  owner 'root'
  group 'root'
  mode '0644'
  notifies :restart, 'service[nginx]'
end

# 部署文件
cookbook_file '/usr/share/nginx/html/index.html' do
  source 'index.html'
end

6. Knife CLI

# 客户端 bootstrap
knife bootstrap web1.example.com -x ubuntu --sudo

# cookbook
knife cookbook create mycookbook
knife cookbook upload mycookbook
knife cookbook list

# node
knife node list
knife node show web1.example.com
knife ssh 'role:web' 'uptime' -x ubuntu

# 搜索
knife search node 'role:web'

7. Chef 优缺点

优点:

  • 灵活(Ruby 编程)
  • 强大(复杂逻辑)
  • 测试友好(ChefSpec, Test Kitchen)

缺点:

  • 学习曲线陡(Ruby)
  • 部署复杂(需 Chef Server)
  • 社区比 Ansible 小

七、Terraform

1. Terraform 概述

Terraform:HashiCorp 的基础设施即代码 (IaC) 工具

  • 声明式:HCL 语言
  • 跨云: AWS / Azure / GCP / AliCloud
  • 状态管理
  • 模块化
  • 强大的生态(2000+ provider)

2. 核心概念

  • Provider:云厂商插件
  • Resource:基础设施组件
  • State:状态(资源实际状态)
  • Module:可复用代码块
  • Variable / Output:变量和输出
  • HCL:HashiCorp 配置语言

3. 简单示例

# main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  tags = {
    Name = "WebServer"
  }
}

output "instance_ip" {
  value = aws_instance.web.public_ip
}

4. 常用命令

terraform init              # 初始化
terraform plan              # 计划(看变化)
terraform apply             # 应用
terraform apply -auto-approve
terraform destroy           # 销毁
terraform fmt               # 格式化
terraform validate          # 验证
terraform show              # 看状态
terraform output            # 看输出
terraform state list        # 列状态
terraform state show aws_instance.web
terraform refresh           # 刷新状态
terraform import aws_instance.web i-xxx
terraform taint aws_instance.web

5. State 管理

# 本地(默认)
# terraform.tfstate

# 远程(推荐)
terraform {
  backend "s3" {
    bucket = "my-tf-state"
    key    = "prod/terraform.tfstate"
    region = "us-east-1"
    dynamodb_table = "my-tf-locks"
  }
}

支持的 backend:

  • S3, Azure Storage, GCS
  • Consul
  • etcd
  • HTTP
  • local (默认)

6. 模块化

# modules/webserver/main.tf
variable "ami" {}
variable "instance_type" {}

resource "aws_instance" "this" {
  ami           = var.ami
  instance_type = var.instance_type
}

output "ip" {
  value = aws_instance.this.public_ip
}

# 调用
module "web" {
  source   = "./modules/webserver"
  ami      = "ami-xxx"
  instance_type = "t3.micro"
}

7. Workspace

terraform workspace new prod
terraform workspace select prod
terraform workspace list

8. Terraform Cloud / Enterprise

  • 状态存储
  • 团队协作
  • 审计
  • 策略

八、Kustomize

1. Kustomize 概述

Kustomize:Kubernetes 原生配置管理工具

  • 不需要模板
  • Base + Overlay 模式
  • kubectl 内置支持

2. 目录结构

myapp/
├── base/
│   ├── kustomization.yaml
│   ├── deployment.yaml
│   ├── service.yaml
│   └── configmap.yaml
└── overlays/
    ├── dev/
    │   └── kustomization.yaml
    └── prod/
        └── kustomization.yaml

3. base/kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- deployment.yaml
- service.yaml
- configmap.yaml

4. overlays/prod/kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: production
namePrefix: prod-
replicas:
- name: web
  count: 5

images:
- name: myapp
  newName: myregistry/myapp
  newTag: v1.5.0

resources:
- ../../base

patches:
- target:
    kind: Deployment
    name: web
  patch: |-
    - op: replace
      path: /spec/template/spec/containers/0/resources
      value:
        limits:
          cpu: "1"
          memory: 1Gi
        requests:
          cpu: 500m
          memory: 512Mi

configMapGenerator:
- envs:
  - prod.env

5. 常用

# kubectl 内置
kubectl apply -k overlays/prod/

# 独立 kustomize
kustomize build overlays/prod/

九、Helm

1. Helm 概述

Helm:Kubernetes 的包管理工具

  • 模板化
  • 版本管理
  • 仓库
  • 易于共享

2. 概念

  • Chart:Helm 包(类似 rpm)
  • Release:Chart 的一个实例
  • Repository:Chart 仓库
  • Values:配置文件

3. Chart 结构

mychart/
├── Chart.yaml            # Chart 元数据
├── values.yaml           # 默认值
├── templates/            # K8s YAML 模板
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── ingress.yaml
│   └── _helpers.tpl
├── charts/               # 依赖
└── README.md

4. 常用命令

# 装 helm
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

# 仓库
helm repo add stable https://charts.helm.sh/stable
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm search repo nginx

# 安装
helm install my-nginx bitnami/nginx
helm install my-nginx bitnami/nginx -f values.yaml
helm install my-nginx bitnami/nginx --set replicaCount=3

# 查
helm list
helm list -A
helm status my-nginx

# 升级
helm upgrade my-nginx bitnami/nginx -f new-values.yaml

# 回滚
helm rollback my-nginx 1

# 删除
helm uninstall my-nginx

# 仓库管理
helm repo list
helm repo add
helm repo update

5. Chart 模板 (Go template)

# templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}-{{ .Chart.Name }}
  labels:
    app: {{ .Values.app.name }}
    version: {{ .Chart.AppVersion }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ .Values.app.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.app.name }}
    spec:
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
        ports:
        - containerPort: {{ .Values.service.port }}
        resources:
          {{- toYaml .Values.resources | nindent 10 }}

6. values.yaml

replicaCount: 3

image:
  repository: nginx
  tag: 1.25
  pullPolicy: IfNotPresent

service:
  port: 80
  type: ClusterIP

resources:
  requests:
    cpu: 100m
    memory: 128Mi
  limits:
    cpu: 500m
    memory: 512Mi

十、配置管理工具对比

维度 Ansible SaltStack Puppet Chef
类型 推送 推送/拉取 拉取 拉取
客户端 无 有(minion) 有(agent) 有(knife)
协议 SSH ZeroMQ HTTPS HTTPS
速度 中 极快 中 中
学习曲线 低 中 高 高
配置语言 YAML YAML 自己的 DSL Ruby
适合规模 < 5000 5000-50000 5000-100000 5000+
大规模 慢 强 强 强
适用场景 通用 大规模 大规模、模型化 编程式
商业版 Tower SaltStack PE Automate

十一、配置管理最佳实践

1. 仓库组织

  • 配置仓库: 单独 Git 仓库
  • 目录结构:按环境/角色/服务分
  • 敏感信息: 单独仓库 + 加密

2. 命名规范

  • 主机名规范
  • 角色名清晰
  • 变量名一致
  • 任务名描述

3. 幂等性

  • 不要写非幂等的命令
  • 避免 command: rm -rf /tmp/* (重复跑会删)
  • 用 state: present/absent
  • 改文件用 template / lineinfile

4. 测试

  • 单元测试: 模拟执行
  • 集成测试: 真实环境
  • CI/CD: 测试配置变更
# Ansible lint
ansible-lint playbook.yml

# Molecule (Ansible 测试框架)
molecule test

# Serverspec (Ruby)
serverspec

5. 加密

  • Ansible Vault: 加密敏感数据
  • 不要提交密钥
  • 用环境变量 / KMS
  • 轮换密钥

6. 审计

  • Git 记录一切变更
  • PR 审查
  • 谁改了什么
  • 回滚容易

7. 文档

  • README
  • Wiki
  • 注释
  • CHANGELOG

十二、配置管理实战案例

1. Ansible 部署 K8s 集群

# site.yml
- name: 配置 K8s Master
  hosts: masters
  become: yes
  roles:
    - common
    - k8s-common
    - k8s-master

- name: 配置 K8s Node
  hosts: nodes
  become: yes
  roles:
    - common
    - k8s-common
    - k8s-node

2. Terraform 创建 AWS 基础设施

# 创建 VPC
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "myapp-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
}

# EKS 集群
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "19.0"

  cluster_name    = "myapp-cluster"
  cluster_version = "1.28"
  subnets         = module.vpc.private_subnets
  vpc_id          = module.vpc.vpc_id

  node_groups = [
    {
      name          = "workers"
      instance_type = "t3.medium"
      min_size      = 2
      max_size      = 10
      desired_size  = 3
    }
  ]
}

3. Helm 部署应用

# 加 chart
helm repo add bitnami https://charts.bitnami.com/bitnami

# 自定义 values
cat > values.yaml <<EOF
replicaCount: 3
image:
  tag: 1.25.0
service:
  type: LoadBalancer
resources:
  requests:
    cpu: 500m
    memory: 512Mi
ingress:
  enabled: true
  hostname: myapp.example.com
EOF

# 部署
helm install my-nginx bitnami/nginx -f values.yaml

十三、配置安全

1. 密钥管理

  • Ansible Vault: 加密 YAML
  • HashiCorp Vault: 集中密钥管理
  • SOPS: YAML/JSON 文件加密
  • AWS Secrets Manager / Azure Key Vault / GCP Secret Manager
  • 环境变量 / KMS

2. 配置审计

  • Open Policy Agent (OPA): 策略引擎
  • Conftest: OPA 配置测试
  • InSpec: 合规扫描
  • Serverspec: 服务器配置测试
  • CIS Benchmarks: 安全基线
# InSpec
inspec exec my-profile

# Serverspec
serverspec

3. IaC 漏洞扫描

  • Trivy: IaC 扫描(trivy config)
  • Checkov: Terraform/Pulumi/Kustomize 扫描
  • tfsec: Terraform 安全扫描
  • KICS: 多 IaC 扫描
# Checkov
checkov -d .
checkov -f main.tf

# tfsec
tfsec .

# Trivy
trivy config .
trivy config --severity HIGH,CRITICAL .

4. 密钥扫描

  • git-secrets: 防止密钥入仓
  • gitleaks: 扫描历史
  • TruffleHog: 深度扫描
  • detect-secrets: 灵活

5. 合规性

  • CIS Benchmarks: 操作系统/服务基线
  • SOC 2 / PCI DSS: 合规框架
  • GDPR: 数据保护

十四、关键概念速查

概念 含义
Ansible 推送式,YAML,无客户端
SaltStack 推送/拉取,ZeroMQ,高速
Puppet 拉取,Ruby DSL,模型化
Chef 拉取,Ruby DSL,编程式
Terraform IaC,声明式,跨云
Kustomize K8s 配置覆盖
Helm K8s 包管理
Inventory Ansible 主机清单
Playbook Ansible 配置脚本
Module Salt 配置单位
Manifest Puppet 配置
Resource Terraform 基础设施单元
Cookbook Chef 配置集合
Recipe Chef 单个配置脚本
Chart Helm 包
State Terraform 状态
Vault Ansible 加密
Grains Salt 静态信息
Pillar Salt 动态信息
Role Ansible 可复用单元
Handler Ansible 通知
HCL HashiCorp 配置语言
Provider Terraform 云厂商插件
Backend Terraform 状态后端
Values Helm 配置文件
Knife Chef CLI 工具
Berkshelf Chef Cookbook 依赖管理
SLS Salt 状态文件
Idempotency 幂等性
GitOps 仓库即真理
SOPS 文件加密
OPA 策略引擎
CIS 安全基线
Checkov IaC 扫描

十五、核心要点速记

  • Ansible = 简单推送式,YAML,SSH,无客户端
  • SaltStack = 高速,可大扩展,ZeroMQ
  • Puppet = 拉取,模型化,大规模
  • Chef = 编程式,Ruby
  • Terraform = IaC,跨云,声明式
  • Kustomize = K8s 配置覆盖,Base + Overlay
  • Helm = K8s 包管理,模板化
  • Inventory = 主机清单
  • Playbook = Ansible 配置脚本
  • Module = Salt 配置单位
  • Manifest = Puppet 配置
  • Resource = Terraform 基础设施单元
  • Chart = Helm 包
  • State = Terraform 状态(关键!)
  • Vault = Ansible 加密
  • Grains = Salt 静态信息
  • Pillar = Salt 动态信息
  • Role = Ansible 可复用单元
  • Handler = Ansible 通知
  • 幂等性 = 多次执行结果一致
  • 推送 vs 拉取: 推送简单,拉取可扩展
  • 声明式 vs 命令式: 声明式更可靠
  • Ansible Vault 加密 = 密钥
  • State 远程存储 = S3/Consul
  • Kustomize patches = 改字段
  • Helm Values 覆盖 = 部署时参数
  • Provider 生态 = Terraform 强项
  • 幂等性 / 测试 / 审计 / 文档 / 加密 / 命名 = 最佳实践