我有一个在GCP的Kubernetes引擎中运行的Jenkins pod,我正在尝试运行连接到谷歌云SQL数据库的maven单元测试来执行所述测试。我的项目的application.yaml如下所示:
spring:
cloud:
gcp:
project-id: <my_project_id>
sql:
database-name: <my_database_name>
instance-connection-name: <my_instance_connection_name>
jpa:
database-platform: org.hibernate.dialect.MySQL55Dialect
hibernate:
ddl-auto: create-drop
datasource:
continue-on-error: true
driver-class-name: com.mysql.cj.jdbc.Driver
username: <my_cloud_sql_username>
password: <my_cloud_sql_password>
与此项目关联的当前Jenkinsfile是:
Jenkinsfile:
pipeline {
agent any
tools{
maven 'Maven 3.5.2'
jdk 'jdk8'
}
environment {
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
DEV_DB_USER = "${env.DEV_DB_USER}"
DEV_DB_PASSWORD = "${env.DEV_DB_PASSWORD}"
}
stages {
stage('Build docker image') {
steps {
sh 'mvn -Dmaven.test.skip=true clean package'
script{
docker.build '$IMAGE:$VERSION'
}
}
}
stage('Run unit tests') {
steps {
withEnv(['GCLOUD_PATH=/var/jenkins_home/google-cloud-sdk/bin']) {
withCredentials([file(credentialsId: 'key-sa', variable: 'GC_KEY')]) {
sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
sh("gcloud container clusters get-credentials <cluster_name> --zone northamerica-northeast1-a --project <project_id>")
sh 'mvn test'
}
}
}
}
}
}
}
我的问题是当Pipeline实际尝试使用上面的配置运行mvn测试时(在我的application.yaml中)我收到此错误:
Caused by:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission: Request had insufficient authentication scopes.",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission: Request had insufficient authentication scopes."
}
我有两个Google Cloud项目:
我还在Jenkins的Spring Boot Project中创建了服务帐户,以便使用三个角色:Cloud SQL Editor,Kubernetes Engine Cluster Admin和Project owner(以验证服务帐户没有错误)。
我在两个项目中启用了Cloud SQL,Cloud SQL管理员和Kubernetes API,并且我仔细检查了我的Cloud SQL凭据,他们没问题。另外,我使用在创建服务帐户时生成的json文件对Jenkins管道进行了身份验证,遵循here讨论的建议:
Jenkinsfile(摘录):
...
withCredentials([file(credentialsId: 'key-sa', variable: 'GC_KEY')]) {
sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
sh("gcloud container clusters get-credentials <cluster_name> --zone northamerica-northeast1-a --project <project_id>")
sh 'mvn test'
}
...
我不相信GCP Java SDK完全依赖于gcloud CLI。相反,它会查找指向您的服务帐户密钥文件和GCLOUD_PROJECT的环境变量GOOGLE_APPLICATION_CREDENTIALS(请参阅https://cloud.google.com/docs/authentication/getting-started)。
尝试添加以下内容:
sh("export GOOGLE_APPLICATION_CREDENTIALS=${GC_KEY}")
sh("export GCLOUD_PROJECT=<project_id>")
为了实现这一目标,您应该验证几件不同的事情。我假设你正在使用Cloud SQL JDBC SocketFactory for Cloud SQL。
GOOGLE_APPLICATION_CREDENTIALS
env var,它应该是测试服务帐户密钥的路径。