DEV Community

Yasuhiro Matsuda for AWS Community Builders

Posted on • Edited on

Define secret values registered in Secrets Manager in Terraform in environment variables in Lambda

Setting environment variables in ECS task definition using Terraform can be realized using valueFrom, but I could not find a way to define them in Lambda environment variables, so I verified it.

resource "aws_ecs_task_definition" "keycloak" {
  container_definitions = jsonencode(
    [
      {
        secrets = [
          {
            name : "KeycloakSettings__AdminUser",
            valueFrom : "${var.secrets_manager_secret_arn}: KeycloakSettings__AdminUser::"
          }
        ...
        ]
      }
    ]
  )
}
Enter fullscreen mode Exit fullscreen mode

The same can be achieved with Lambda by using the External Data Source as follows.

data "aws_secretsmanager_secret" "keycloak_env" {
  name = var.secrets_manager_secret_name
}

data "aws_secretsmanager_secret_version" "keycloak_env" {
  secret_id = data.aws_secretsmanager_secret.keycloak_env.id
}

data "external" "keycloak_env_secret_json" {
  program = ["echo", "${data.aws_secretsmanager_secret_version.keycloak_env.secret_string}"]
}

resource "aws_lambda_function" "keycloak" {
    environment {
    variables = {
      KeycloakSettings__AdminUser = "${data.external.keycloak_env_secret_json.result["KeycloakSettings__AdminUser"]}"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)