如何在 GitHub actions 上为 Spring Boot 项目设置环境变量

问题描述 投票:0回答:1

Maven 全新安装步骤在 GitHub Actions 上失败,因为 bean 需要环境变量。

这是豆子:

@Configuration
@PropertySource(value = "file:${secrets.properties}", ignoreResourceNotFound=true)
public class FirebaseConfig {

    @Value("${google.credentials:invalid}")
    String googleJsonCredentials;

    @Bean("FirebaseApp")
    FirebaseApp getFirebaseApp() throws IOException {
        InputStream serviceAccount = new ByteArrayInputStream(googleJsonCredentials.getBytes());

        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("https://hatley-intranet.firebaseio.com").build();
        FirebaseApp app = FirebaseApp.initializeApp(options);
        return app;
    }
}

我希望 String googleJsonCredentials 可用作 GitHub 操作的环境变量: - 名称:使用 Maven 构建 运行:mvn clean install

我在存储库中有一个名为 GOOGLE_CREDENTIALS 的秘密设置: GitHub secret

我尝试在文件之上设置环境:

env:
  google.credentials: ${{ secrets.GOOGLE_CREDENTIALS }}

我尝试将变量添加到 GitHub 环境作为单独的步骤:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      ...
      - name: Set Google credentials in the environment variables
        run: |
          echo "google.credentials=${{ secrets.GOOGLE_CREDENTIALS }}" >> "$GITHUB_ENV"

我尝试在 Maven 步骤中设置变量:

      - name: Build with Maven
        env:
          google.credentials: ${{ secrets.GOOGLE_CREDENTIALS }}
        run: mvn clean install

看来变量设置正确: GitHub Action Step

但这些选择都不起作用。它无法实例化该 bean,因为它找不到凭据。

org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.firebase.FirebaseApp]: Factory method 'getFirebaseApp' threw exception with message: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
java maven github-actions
1个回答
0
投票

这就是我解决问题的方法:

  1. 我的代码期望在名为“secrets.properties”的文件中找到秘密。因此,我设置了一个名称和值为“secrets.properties”的 Maven 属性。
  2. 将机密添加到具有该名称的文件中
  3. 使用 -D 参数运行 Maven,定义与该文件名相同的系统属性

因此 Maven 运行时系统属性指向包含秘密的文件。

YAML:

      - name: Set up settings.xml
        uses: s4u/[email protected]
        with:
          properties: '[{"secrets.properties": "secrets.properties"}]'

      - name: Save secrets to file
        run: |
          echo "google_credentials=${{ secrets.GOOGLE_CREDENTIALS }}" >> secrets.properties

      - name: Build with Maven
        run: mvn -Dsecrets.properties=secrets.properties clean install

弹簧配置:

@Configuration
@PropertySource(value = "file:${secrets.properties}", ignoreResourceNotFound=true)
public class FirebaseConfig {

    @Value("${google_credentials}")
    String googleJsonCredentials;
© www.soinside.com 2019 - 2024. All rights reserved.