插件说明

Jenkins 有一个 aws credentials 插件,可以关联到 pipeline 中使用

https://plugins.jenkins.io/aws-credentials/

官方也有给出示例,如何使用 pipeline 关联 ecr

text
1
2
3
withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'plt-ia-dev-images-ecr-use1-read', roleArn: 'arn:aws:iam::130312249203:role/PullDockerImages', roleSessionName: 'PullDockerImages']]){
      sh "aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin  ecr_registry
}

配置过程

创建一个 iam 用户,用于 jenkins 获取 ecr token使用

image-20250608135413022

图 - IAM User

image-20250608135925973

图创建用户 - 创建ecr-user
note
不要选择 “Provide user access to the AWS Management Console - optional

权限可以选择 “AmazonEC2ContainerRegistryFullAccess”, 也可根据自己需求进行选择

image-20250608140414672

图创建用户 - 给用户授权

点创建即可

image-20250608140649434

图创建用户 - 创建ecr-user

点击 Security credentials,生成一个 access key

image-20250608141042589

图用户授权 - 生成access key

配置jenkins

安装 aws credentials 插件

image-20250608141307080

图 - Jenkins插件安装

安装好后,在路径 管理 Jenkins =》Credentials =》 System =》Global credentials (unrestricted) 添加 aws access key

image-20250608141523998

图 - Jenkins Credentials创建

选择 AWS Credentials

image-20250608141645237

图 - Jenkins Credentials创建2

填写上面生成的 Access key 和 Secret

image-20250608141902729

图 - Jenkins Credentials创建3

在 pipeline 中使用

text
1
2
3
4
5
withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: "{credential_id}"]]){
    sh '''
        aws ecr get-login-password --region ap-east-1
    '''
}

完整的示例 pipeline

text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
pipeline {
    agent any
    // 定义变量
    environment {
        current_time = sh(script: "date '+%Y%m%d%H%M%S'", returnStdout: true).trim()
    }
    // 发布步骤
    stages {
        stage('test aws credentials'){
            steps {
                withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: "${registry_auth}"]]){
                    sh '''
                        aws ecr get-login-password --region ap-east-1
                    '''
                }
            } 
        } 
    }
}