如何处理部署到 AWS Lambda 的 Go 函数中的秘密

How to handle secrets in a Go function deployed to AWS Lambda

我有一个在本地运行的功能,我有一个使用 Viper 加载到应用程序中的配置文件,我还设置了 viper.AutomaticEnv()

部署到 AWS Lambda 后,环境变量似乎被忽略了。我转到 Viper 问题页面,发现了这个:https://github.com/spf13/viper/issues/584

看起来 Viper 需要加载配置文件,否则即使我们可以设置环境变量它也会停止工作。

您如何处理 Go 中 lambda 机密的本地开发与部署?

我想尽可能避免使用 AWS Secrets Manager

在 AWS Lambdas 中有很多处理机密的选项。我建议不要使用 Viper 或任何这些工具。构建一个从环境 Lambdas 读取配置的 Lambda 很简单。

也就是说,我还建议您阅读 AWS SSM 参数存储中的秘密。

main.go

func (h handler) handleRequest() error {
    fmt.Printf("My secret: %s", h.config.secret)

    return nil
}

type configuration struct {
    secret string
}

type handler struct {
    config configuration
}

func newConfig() (configuration, error) {
    secret, ok := os.LookupEnv("SECRET")
    if !ok {
        return configuration{}, errors.New("can not read environment variable 'SECRET'")
    }

    return configuration{
        secret: secret
    }, nil
}

func main() {
    cfg, err := newConfig()
    if err != nil {
        fmt.Printf("unable to create configuration: %v\n", err)
        os.Exit(1)
    }

    h := handler{
        config: cfg,
    }

    lambda.Start(h.handleRequest)
}

无需使用 Viper 并不必要地增加二进制文件的大小。请记住:更大的二进制文件,更长的 cold-start 时间。

How do you handle local dev vs deployment for lambda secrets in Go?

通常,我们只在本地使用单元测试,这些单元测试使用不需要机密的模拟服务。大多数“集成”测试都是在 AWS 中完成的。每个开发人员都有自己可以部署的“环境”。为了管理这个,我们使用 Terraform。

如果您真的需要在本地测试某些东西,我建议您创建一个测试文件,然后执行“gitignore”以避免提交它。在这个文件中我只是hard-code秘密。

例如,您可以在 .gitignore 文件中忽略一个 playground_test.go