从 jenkins 管道获取 Maven Spring 配置文件

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

我在使用 Spring 配置文件的 Maven Spring Boot 项目上遇到詹金斯管道问题。

这是pom.xml:

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>svil</id>
        <properties>
            <spring.profiles.active>svil</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

应用程序属性:

#---
[email protected]@

my.prop=used-always-in-all-profiles
#---
spring.config.activate.on-profile=dev
spring.datasource.url=.....
spring.datasource.username=....
spring.datasource.password=....

#---
spring.config.activate.on-profile=svil
spring.datasource.url=.....
spring.datasource.username=....
spring.datasource.password=....
#---
spring.config.activate.on-profile=production
spring.datasource.url=....
spring.datasource.username=....
spring.datasource.password=....

詹金斯文件:

pipeline {
agent any

tools {
      maven 'jenkins-maven'
      jdk 'java-17'
    }

stages {

    stage('Build'){
        steps {
            sh "mvn -Psvil clean install -DskipTests"
        }
    }

    stage('Test'){
        steps{
            sh "mvn test"
        }
    }

    stage('Deploy') {
        steps {
             .....
        }
    }
}}

Jenkins 配置了我的 github 存储库,并运行 Jenkinsfile 中定义的步骤。 使用服务器上安装的maven:

/opt/apache-maven-3.6.3

运行命令时:

sh "mvn -Psvil clean install -DskipTests"

指示的配置文件 (svil) 未正确加载,而是采用默认配置文件 (dev)

2024-04-17T14:25:04.167+02:00  INFO 825213 --- [           main] i.r.p.ApplicationTests      : Starting ApplicationTests using Java 17.0.10 
with PID 825213 (started by jenkins in /var/lib/jenkins/workspace/app)
2024-04-17T14:25:04.168+02:00  INFO 825213 --- [           main] i.r.p.ApplicationTests      : The following 1 profile is active: "dev"

从命令行我没有遇到任何问题,项目编译成jar也没有任何问题。

如何配置 jenkins 管道以采用正确的 spring 配置文件?

谢谢

java spring-boot maven jenkins jenkins-pipeline
1个回答
0
投票

解决方案是修改 Jenkinsfile 并添加带有配置文件的环境,并在构建期间在 mvn clean installan 中使用它们:

environment {
    SPRING_PROFILES_ACTIVE = 'svil'
}

stages {

    stage('Build'){
        steps {
            sh "mvn clean install -Dspring.profiles.active=${SPRING_PROFILES_ACTIVE} -DskipTests"
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.