Logo

Using envvault with Scala

Note: Please ensure that you have completed the previous steps

Prerequisites

  • Java Development Kit (JDK) installed
  • SBT (Scala Build Tool) installed
  • envvault CLI tool installed
  • An existing Scala project

Usage

Running Your Application

To run your Scala application with environment variables from envvault:

$ envvault run --env=dev sbt run

Caching Environment Variables

For better performance, you can cache your environment variables:

$ envvault run --env=dev -c -- sbt run

Example Implementation

Here is how to set up a basic Scala web server with envvault:

// Main.scala
import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import scala.concurrent.{ExecutionContext, Future}
import scala.sys.env
import scala.util.{Success, Failure}

object Main extends App {
  // Your environment variables are automatically loaded
  val port = env.getOrElse("PORT", "8080").toInt
  val dbUrl = env.getOrElse("DB_URL", "")

  implicit val system: ActorSystem[Nothing] = ActorSystem(Behaviors.empty, "my-system")
  implicit val executionContext: ExecutionContext = system.executionContext

  val route =
    path("") {
      get {
        complete(HttpEntity(ContentTypes.text/plain(UTF-8), "Hello from envvault!"))
      }
    }

  val bindingFuture: Future[Http.ServerBinding] = 
    Http().newServerAt("localhost", port).bind(route)

  bindingFuture.onComplete {
    case Success(binding) =>
      println(s"Server running at http://localhost:$port/")
    case Failure(e) =>
      println(s"Failed to bind to $port: ${e.getMessage}")
      system.terminate()
  }
}

// build.sbt
name := "my-app"
version := "1.0"
scalaVersion := "2.13.8"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-http" % "10.2.9",
  "com.typesafe.akka" %% "akka-actor-typed" % "2.6.19",
  "com.typesafe.akka" %% "akka-stream" % "2.6.19"
)