← 返回首页
🏗️

基础设施即代码实践

📂 devops ⏱ 2 min 298 words

基础设施即代码实践

什么是IaC

基础设施即代码(Infrastructure as Code)是使用代码来管理和配置基础设施的方法。

核心价值

工具对比

工具 类型 适用场景
Terraform 声明式 云资源管理
Ansible 过程式 配置管理
Pulumi 编程式 复杂逻辑
CloudFormation 声明式 AWS专用

Terraform最佳实践

项目结构

infrastructure/
├── environments/
│   ├── dev/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── terraform.tfvars
│   ├── staging/
│   └── production/
├── modules/
│   ├── vpc/
│   ├── ecs/
│   └── rds/
└── scripts/

模块化设计

# modules/vpc/main.tf
resource "aws_vpc" "this" {
  cidr_block = var.cidr_block
  
  tags = merge(var.tags, {
    Name = "${var.project}-vpc"
  })
}

resource "aws_subnet" "public" {
  count             = length(var.public_subnets)
  vpc_id            = aws_vpc.this.id
  cidr_block        = var.public_subnets[count.index]
  availability_zone = var.azs[count.index]
  
  tags = merge(var.tags, {
    Name = "${var.project}-public-${var.azs[count.index]}"
  })
}
# 使用模块
module "vpc" {
  source = "./modules/vpc"
  
  project         = "myapp"
  cidr_block      = "10.0.0.0/16"
  public_subnets  = ["10.0.1.0/24", "10.0.2.0/24"]
  azs             = ["us-west-2a", "us-west-2b"]
}

Ansible最佳实践

目录结构

ansible/
├── inventories/
│   ├── dev/
│   │   └── hosts.yml
│   ├── staging/
│   └── production/
├── roles/
│   ├── common/
│   ├── nginx/
│   └── app/
├── playbooks/
│   ├── site.yml
│   ├── webservers.yml
│   └── dbservers.yml
└── ansible.cfg

Role设计

# roles/nginx/tasks/main.yml
---
- name: Install Nginx
  apt:
    name: nginx
    state: present
    update_cache: yes
  when: ansible_os_family == "Debian"

- name: Copy nginx config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: '0644'
  notify: Restart nginx

- name: Start nginx
  service:
    name: nginx
    state: started
    enabled: yes

GitOps实践

# argocd-application.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: myapp
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/user/infra.git
    targetRevision: HEAD
    path: k8s/production
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true

实践:完整IaC流程

# 1. Terraform创建基础设施
cd infrastructure/environments/production
terraform init
terraform plan -out=tfplan
terraform apply tfplan

# 2. Ansible配置服务器
cd ansible
ansible-playbook -i inventories/production/hosts.yml playbooks/site.yml

# 3. 部署应用
kubectl apply -f k8s/

# 4. GitOps同步
# ArgoCD自动同步

最佳实践总结

  1. 模块化:将基础设施分解为可复用模块
  2. 版本控制:所有配置文件使用Git管理
  3. 环境隔离:为不同环境维护独立配置
  4. 自动化:通过CI/CD自动部署
  5. 测试:对基础设施代码进行测试
  6. 文档:保持文档与代码同步

总结

基础设施即代码是现代运维的核心实践。通过Terraform、Ansible等工具,可以实现基础设施的自动化、可重复和可审计管理。