13
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【AWS SAM Go】.envファイルの制約と環境変数設定のシンプルな解決策

13
Last updated at Posted at 2023-06-14

結論

SAM+golangでは、.envで環境変数は設定できませんでした。

参考
https://github.com/aws/aws-sam-cli/issues/1355

以下方法で設定します。

  • ローカル
    • local.jsonで設定
  • 環境ごとのデプロイ
    • template.yamlにEnvironmentMapで設定

詳細

調べると他にもいろいろな設定方法がありましたが、どれにするのか迷ってしまったので、ここではシンプルに記載します。

他を知りたい方はまとめ記事などあったのでそちらを見てください。

ローカル

  • local.jsonを追加
local.json
{
  "Function": {
    "ENV": "local",
    "HOST": "local-host"
  }
}
  • template.yamlにEnvironmentを追加
template.yaml
Resources:
  Function:
    Type: AWS::Serverless::Function
    Properties:
      Environment:
        Variables:
          ENV:
          HOST:
  • local実行コマンド
sam local start-api --env-vars XXX/local.json

os.Getenv("HOST")などで出せます。

デプロイ

  • template.yamlを修正
template.yaml
Parameters:
  Env:
    Type: String
    AllowedValues:
      - dev
      - stg
      - prd
Mappings:
  EnvironmentMap:
    dev:
      host: "dev-host"
    stg:
      host: "stg-host"
    prd:
      host: "prd-host"
Resources:
  Function:
    Type: AWS::Serverless::Function
    Properties:
      Environment:
        Variables:
          ENV: !Ref Env
          HOST: !FindInMap [EnvironmentMap, !Ref Env, host]
  • デプロイ実行コマンド
sam build --parameter-overrides Env=dev
sam deploy

以上。
(よかったら、いいねお願いします!

13
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?