mgmt/docs/waypoint/waypoint_integration_exampl...

12 KiB

Waypoint 集成示例

本文档提供了将Waypoint与现有基础设施和工具集成的具体示例。

1. 与Nomad集成

1.1 基本Nomad部署配置

app "api-service" {
  build {
    use "docker" {
      dockerfile = "Dockerfile"
      disable_entrypoint = true
    }
  }

  deploy {
    use "nomad" {
      // Nomad集群地址
      address = "http://nomad-server:4646"
      
      // 部署配置
      datacenter = "dc1"
      namespace = "default"
      
      // 资源配置
      resources {
        cpu    = 500
        memory = 256
      }
      
      // 服务配置
      service_provider = "consul" {
        service_name = "api-service"
        tags         = ["api", "v1"]
        
        check {
          type     = "http"
          path     = "/health"
          interval = "10s"
          timeout  = "2s"
        }
      }
    }
  }
}

1.2 高级Nomad配置

app "web-app" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      // 存储卷配置
      volume_mount {
        volume      = "app-data"
        destination = "/data"
        read_only   = false
      }
      
      // 网络配置
      network {
        mode = "bridge"
        port "http" {
          static = 8080
          to     = 80
        }
      }
      
      // 环境变量
      env {
        NODE_ENV = "production"
      }
      
      // 健康检查
      health_check {
        timeout = "5m"
        check {
          name   = "http-check"
          route  = "/health"
          method = "GET"
          code   = 200
        }
      }
    }
  }
}

2. 与Vault集成

2.1 从Vault获取静态密钥

app "database-service" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      env {
        // 从Vault获取数据库凭据
        DB_USERNAME = dynamic("vault", {
          path = "kv/data/database/creds"
          key  = "username"
        })
        
        DB_PASSWORD = dynamic("vault", {
          path = "kv/data/database/creds"
          key  = "password"
        })
      }
    }
  }
}

2.2 使用Vault动态密钥

app "api-service" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      template {
        destination = "secrets/db-creds.txt"
        data = <<EOF
{{- with secret "database/creds/api-role" -}}
DB_USERNAME={{ .Data.username }}
DB_PASSWORD={{ .Data.password }}
{{- end -}}
EOF
      }
      
      env_from_file = ["secrets/db-creds.txt"]
    }
  }
}

3. 与Consul集成

3.1 服务发现配置

app "frontend" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      service_provider = "consul" {
        service_name = "frontend"
        
        meta {
          version = "v1.2.3"
          team    = "frontend"
        }
        
        tags = ["web", "frontend"]
      }
    }
  }
}

3.2 使用Consul KV存储配置

app "config-service" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      template {
        destination = "config/app-config.json"
        data = <<EOF
{
  "settings": {{ key "config/app-settings" | toJSON }},
  "features": {{ key "config/features" | toJSON }}
}
EOF
      }
    }
  }
}

4. 与Gitea Actions集成

4.1 基本CI/CD流水线

name: Build and Deploy

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Install Waypoint
        run: |
          curl -fsSL https://releases.hashicorp.com/waypoint/0.11.0/waypoint_0.11.0_linux_amd64.zip -o waypoint.zip
          unzip waypoint.zip
          sudo mv waypoint /usr/local/bin/          
      
      - name: Configure Waypoint
        run: |
          waypoint context create \
            -server-addr=${{ secrets.WAYPOINT_SERVER_ADDR }} \
            -server-auth-token=${{ secrets.WAYPOINT_AUTH_TOKEN }} \
            -set-default ci-context          
      
      - name: Build and Deploy
        run: waypoint up

4.2 多环境部署流水线

name: Multi-Environment Deploy

on:
  push:
    branches: [ main, staging, production ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Install Waypoint
        run: |
          curl -fsSL https://releases.hashicorp.com/waypoint/0.11.0/waypoint_0.11.0_linux_amd64.zip -o waypoint.zip
          unzip waypoint.zip
          sudo mv waypoint /usr/local/bin/          
      
      - name: Configure Waypoint
        run: |
          waypoint context create \
            -server-addr=${{ secrets.WAYPOINT_SERVER_ADDR }} \
            -server-auth-token=${{ secrets.WAYPOINT_AUTH_TOKEN }} \
            -set-default ci-context          
      
      - name: Determine Environment
        id: env
        run: |
          if [[ ${{ github.ref }} == 'refs/heads/main' ]]; then
            echo "::set-output name=environment::development"
          elif [[ ${{ github.ref }} == 'refs/heads/staging' ]]; then
            echo "::set-output name=environment::staging"
          elif [[ ${{ github.ref }} == 'refs/heads/production' ]]; then
            echo "::set-output name=environment::production"
          fi          
      
      - name: Build and Deploy
        run: |
          waypoint up -workspace=${{ steps.env.outputs.environment }}          

5. 多云部署示例

5.1 AWS ECS部署

app "microservice" {
  build {
    use "docker" {}
  }

  deploy {
    use "aws-ecs" {
      region = "us-west-2"
      cluster = "production"
      
      service {
        name = "microservice"
        desired_count = 3
        
        load_balancer {
          target_group_arn = "arn:aws:elasticloadbalancing:us-west-2:..."
          container_name   = "microservice"
          container_port   = 8080
        }
      }
    }
  }
}

5.2 Google Cloud Run部署

app "api" {
  build {
    use "docker" {}
  }

  deploy {
    use "google-cloud-run" {
      project  = "my-gcp-project"
      location = "us-central1"
      
      port = 8080
      
      capacity {
        memory                     = 512
        cpu_count                  = 1
        max_requests_per_container = 10
        request_timeout            = 300
      }
      
      auto_scaling {
        max_instances = 10
      }
    }
  }
}

5.3 多云部署策略

// 使用变量决定部署目标
variable "deploy_target" {
  type    = string
  default = "nomad"
}

app "multi-cloud-app" {
  build {
    use "docker" {}
  }

  deploy {
    // 根据变量选择部署平台
    use dynamic {
      value = var.deploy_target
      
      // Nomad部署配置
      nomad {
        datacenter = "dc1"
        // 其他Nomad配置...
      }
      
      // AWS ECS部署配置
      aws-ecs {
        region = "us-west-2"
        cluster = "production"
        // 其他ECS配置...
      }
      
      // Google Cloud Run部署配置
      google-cloud-run {
        project = "my-gcp-project"
        location = "us-central1"
        // 其他Cloud Run配置...
      }
    }
  }
}

6. 高级发布策略

6.1 蓝绿部署

app "web-app" {
  build {
    use "docker" {}
  }

  deploy {
    use "nomad" {
      // 基本部署配置...
    }
  }
  
  release {
    use "nomad-bluegreen" {
      service      = "web-app"
      datacenter   = "dc1"
      namespace    = "default"
      
      // 流量转移配置
      traffic_step = 25  // 每次转移25%的流量
      confirm_step = true  // 每步需要确认
      
      // 健康检查
      health_check {
        timeout = "2m"
        check {
          route  = "/health"
          method = "GET"
        }
      }
    }
  }
}

6.2 金丝雀发布

app "api-service" {
  build {
    use "docker" {}
  }

  deploy {
    use "nomad" {
      // 基本部署配置...
    }
  }
  
  release {
    use "nomad-canary" {
      service    = "api-service"
      datacenter = "dc1"
      
      // 金丝雀配置
      canary {
        percentage = 10  // 先发布到10%的实例
        duration   = "15m"  // 观察15分钟
      }
      
      // 自动回滚配置
      auto_rollback = true
      
      // 指标监控
      metrics {
        provider = "prometheus"
        address  = "http://prometheus:9090"
        query    = "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) > 0.01"
      }
    }
  }
}

7. 自定义插件示例

7.1 自定义构建器插件

// custom_builder.go
package main

import (
	"context"
	sdk "github.com/hashicorp/waypoint-plugin-sdk"
)

// CustomBuilder 实现自定义构建逻辑
type CustomBuilder struct {
	config BuildConfig
}

type BuildConfig struct {
	Command string `hcl:"command"`
}

// ConfigSet 设置配置
func (b *CustomBuilder) ConfigSet(config interface{}) error {
	c, ok := config.(*BuildConfig)
	if !ok {
		return fmt.Errorf("invalid configuration")
	}
	b.config = *c
	return nil
}

// BuildFunc 执行构建
func (b *CustomBuilder) BuildFunc() interface{} {
	return b.build
}

func (b *CustomBuilder) build(ctx context.Context, ui terminal.UI) (*Binary, error) {
	// 执行自定义构建命令
	cmd := exec.CommandContext(ctx, "sh", "-c", b.config.Command)
	cmd.Stdout = ui.Output()
	cmd.Stderr = ui.Error()
	
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	
	return &Binary{
		Source: "custom",
	}, nil
}

// 注册插件
func main() {
	sdk.Main(sdk.WithComponents(&CustomBuilder{}))
}

7.2 使用自定义插件

app "custom-app" {
  build {
    use "custom" {
      command = "make build"
    }
  }
  
  deploy {
    use "nomad" {
      // 部署配置...
    }
  }
}

8. 监控和可观测性集成

8.1 Prometheus集成

app "monitored-app" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      // Prometheus注解
      service_provider = "consul" {
        service_name = "monitored-app"
        
        meta {
          "prometheus.io/scrape" = "true"
          "prometheus.io/path"   = "/metrics"
          "prometheus.io/port"   = "8080"
        }
      }
    }
  }
}

8.2 与ELK堆栈集成

app "logging-app" {
  deploy {
    use "nomad" {
      // 基本配置...
      
      // 日志配置
      logging {
        type = "fluentd"
        config {
          fluentd_address = "fluentd.service.consul:24224"
          tag             = "app.${nomad.namespace}.${app.name}"
        }
      }
    }
  }
}

9. 本地开发工作流

9.1 本地开发配置

app "dev-app" {
  build {
    use "docker" {}
  }

  deploy {
    use "docker" {
      service_port = 3000
      
      // 开发环境特定配置
      env {
        NODE_ENV = "development"
        DEBUG    = "true"
      }
      
      // 挂载源代码目录
      binds {
        source      = abspath("./src")
        destination = "/app/src"
      }
    }
  }
}

9.2 本地与远程环境切换

variable "environment" {
  type    = string
  default = "local"
}

app "fullstack-app" {
  build {
    use "docker" {}
  }

  deploy {
    // 根据环境变量选择部署方式
    use dynamic {
      value = var.environment
      
      // 本地开发
      local {
        use "docker" {
          // 本地Docker配置...
        }
      }
      
      // 开发环境
      dev {
        use "nomad" {
          // 开发环境Nomad配置...
        }
      }
      
      // 生产环境
      prod {
        use "nomad" {
          // 生产环境Nomad配置...
        }
      }
    }
  }
}

10. 多应用协调

10.1 依赖管理

project = "microservices"

app "database" {
  // 数据库服务配置...
}

app "backend" {
  // 后端API配置...
  
  // 声明依赖关系
  depends_on = ["database"]
}

app "frontend" {
  // 前端配置...
  
  // 声明依赖关系
  depends_on = ["backend"]
}

10.2 共享配置

// 定义共享变量
variable "version" {
  type    = string
  default = "1.0.0"
}

variable "environment" {
  type    = string
  default = "development"
}

// 共享函数
function "service_name" {
  params = [name]
  result = "${var.environment}-${name}"
}

// 应用配置
app "api" {
  build {
    use "docker" {
      tag = "${var.version}"
    }
  }

  deploy {
    use "nomad" {
      service_provider = "consul" {
        service_name = service_name("api")
      }
      
      env {
        APP_VERSION = var.version
        ENVIRONMENT = var.environment
      }
    }
  }
}