在 Node.js 中使用 Dagger 進行 CI/CD

在 Dagger 中使用加密的 .env.vault 檔案執行 Node.js CI/CD

初始設定

安裝 Dagger Node SDK

npm install @dagger.io/dagger --save-dev

建立 ci/index.mjs 檔案。

ci/index.mjs

// ci/index.mjs
import { connect } from "@dagger.io/dagger"

connect(async (client) => {
  const node = client.container().from("node:16-slim").withExec(["node", "-v"])

  const version = await node.stdout()

  // print output
  console.log(`Hello ${process.env.HELLO}.`)
}, { LogOutput: process.stdout })

執行管線。

node ci/index.mjs
8: [0.11s] v16.20.1
8: exec docker-entrypoint.sh node -v DONE
Hello undefined.

一旦執行,管線建置會顯示 'Hello undefined.',因為它還沒有辦法存取環境變數。接下來讓我們處理這個問題。

安裝 dotenv

安裝 dotenv

npm install dotenv --save-dev # Requires dotenv >= 16.1.0

在專案的根目錄中建立 .env 檔案。

.env

# .env
HELLO="World"

在您的 CI 管線中儘早匯入並設定 dotenv。

ci/index.mjs

// ci/index.mjs
import 'dotenv/config'
console.log(process.env) // remove this after you've confirmed it is working

import { connect } from "@dagger.io/dagger"

connect(async (client) => {
  const node = client.container().from("node:16-slim").withExec(["node", "-v"])

  const version = await node.stdout()

  // print output
  console.log(`Hello ${process.env.HELLO}.`)
}, { LogOutput: process.stdout })

嘗試在本地執行它。

node ci/index.mjs
{
  ...
  HELLO: 'World'
}
Hello World.

完美。現在 process.env 具有您在 .env 檔案中定義的鍵和值。

這涵蓋了 CI 的本地模擬。接下來讓我們解決實際的 CI 環境。

建立 .env.vault

推送您最新的 .env 檔案變更並編輯您的 CI 機密。 了解更多關於同步的資訊

npx dotenv-vault@latest push
npx dotenv-vault@latest open ci

使用 UI 為每個環境設定這些機密。

dotenv.org

然後建立您的加密 .env.vault 檔案。

npx dotenv-vault@latest build

其內容應該如下所示。

.env.vault

#/-------------------.env.vault---------------------/
#/         cloud-agnostic vaulting standard         /
#/   [how it works](https://dotenv.org/env-vault)   /
#/--------------------------------------------------/

# development
DOTENV_VAULT_DEVELOPMENT="/HqNgQWsf6Oh6XB9pI/CGkdgCe6d4/vWZHgP50RRoDTzkzPQk/xOaQs="
DOTENV_VAULT_DEVELOPMENT_VERSION=2

# ci
DOTENV_VAULT_CI="x26PuIKQ/xZ5eKrYomKngM+dO/9v1vxhwslE/zjHdg3l+H6q6PheB5GVDVIbZg=="
DOTENV_VAULT_CI_VERSION=2

設定 DOTENV_KEY

擷取您的 CI DOTENV_KEY

npx dotenv-vault@latest keys ci
# outputs: dotenv://:[email protected]/vault/.env.vault?environment=ci

為 Dagger 設定 DOTENV_KEY

DOTENV_KEY='dotenv://:[email protected]/vault/.env.vault?environment=ci' node ci/index.mjs

結果將是

8: exec docker-entrypoint.sh node -v CACHED
Hello ci.

就是這樣!您的 .env.vault 檔案已解密,其 CI 機密會及時注入為環境變數。

當您在記錄中看到 'Loading env from encrypted .env.vault' 時,您就知道事情已正確運作。如果未設定 DOTENV_KEY(例如在您的本機機器上開發時),它會回退到標準的 dotenv 功能。