发布于 2026-01-06 5 阅读
0

如何在 AWS 上设置 Jenkins 和 Pipeline

如何在 AWS 上设置 Jenkins 和 Pipeline

目录

  1. 介绍
  2. 创建 IAM 用户
  3. 创建密钥对
  4. 创建安全组
  5. 创建 EC2 实例
  6. 安装和配置 Jenkins
  7. 创建管道
  8. 清理
  9. 概括
  10. 转诊

介绍

在本篇博客中,我们将在 EC2 实例上搭建 Jenkins,然后搭建一个流水线来从 S3 复制文件。
我们将从最基础的开始,并随着项目的推进逐步完善。

Jenkins是什么?

Jenkins 提供了一种简便的方法,可以使用流水线为几乎任何语言和源代码仓库组合搭建持续集成/持续交付 (CI/CD) 环境,并自动化其他日常开发任务。虽然 Jenkins 并不能完全消除为每个步骤编写脚本的需求,但它确实提供了一种比自行构建更快、更强大的方式来集成整个构建、测试和部署工具链。

什么是 Jenkins Pipeline?

Jenkins Pipeline 是一套插件,支持将持续交付流水线集成到 Jenkins 中。

Pipeline 提供了一套可扩展的工具,as code用于通过Pipeline 领域特定语言 (DSL) 语法对从简单到复杂的交付管道进行建模。


演示

让我们开始演示吧。

步骤 1. 创建 IAM 用户

  1. 导航至 IAM > 用户 > 点击添加用户
  2. 输入用户名 JenkinsUser
  3. 选择访问密钥 - 程序化访问,然后单击“下一步:权限”。
  4. 单击“直接附加现有策略”,然后单击“创建策略” 。
  5. 在“创建策略”窗口中,单击“JSON”,添加以下JenkinsEC2Policy,并将策略保存为JenkinsEC2Policy。
  6. 在“直接附加现有策略”下选择 AmazonS3ReadOnlyAccess 和 JenkinsEC2Policy
  7. 点击“下一步:标签”“下一步:审核”,然后点击“创建用户” 。
  8. 下载凭据.csv文件,因为我们将在步骤 6 配置 Jenkins 时需要它。

    JenkinsEC2策略

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1312295543082",
            "Action": [
                "ec2:DescribeSpotInstanceRequests",
                "ec2:CancelSpotInstanceRequests",
                "ec2:GetConsoleOutput",
                "ec2:RequestSpotInstances",
                "ec2:RunInstances",
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:TerminateInstances",
                "ec2:CreateTags",
                "ec2:DeleteTags",
                "ec2:DescribeInstances",
                "ec2:DescribeInstanceTypes",
                "ec2:DescribeKeyPairs",
                "ec2:DescribeRegions",
                "ec2:DescribeImages",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "iam:ListInstanceProfilesForRole",
                "iam:PassRole",
                "ec2:GetPasswordData"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
    }
    

IAM_JenkinsUser1

IAM_JenkinsUser1

IAM_JenkinsUser2

IAM_JenkinsUser2

IAM_JenkinsUser3

IAM_JenkinsUser3


步骤二:创建密钥对

  1. 导航至 EC2 > 密钥对(位于“网络和安全”下)。
  2. 点击 Create key pair
  3. 找到密钥对下载所在的文件夹并运行。
   chmod 400 <key_pair_name>.pem
Enter fullscreen mode Exit fullscreen mode

Jenkins_Keypair

Jenkins_Keypair


步骤 3:创建安全组

  1. 我们将创建一个用于 SSH 和 Jenkins Web 访问的安全组。
  2. 导航至 EC2 > 安全组 > 为您的 ALB 创建一个新的安全组,并设置以下值:
    • 姓名:JenkinsSG
    • 添加入站规则以允许SSH (TCP 22)来自以下位置的流量My IP
    • 添加另一条入站规则,允许Custom (TCP 8080)来自以下位置的流量My IP

Jenkins_SG

Jenkins_SG


步骤 4:创建 EC2 实例

  1. 导航至 EC2 > EC2 控制面板 > 点击启动实例
  2. 使用屏幕截图中显示的以下值启动实例。
  3. 当实例状态为“运行中”时,选择该实例,然后单击“连接”,再复制连接详细信息。
  4. 连接到实例。

    ssh -i "Jenkins-Keypair.pem" ec2-user@ec2-54-211-70-130.compute-1.amazonaws.com
    

Jenkins_EC1

Jenkins_EC1

Jenkins_EC2

Jenkins_EC2


步骤 5. 安装和配置 Jenkins


安装 Jenkins
  1. 请执行以下命令,确保实例上的软件包已更新至最新版本:

    [ec2-user ~]$ sudo yum update –y
    
  2. 使用以下命令添加 Jenkins 仓库:

    [ec2-user ~]$ sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
    
  3. 从 Jenkins-CI 导入密钥文件以启用软件包安装:

    [ec2-user ~]$ sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
    
    [ec2-user ~]$ sudo yum upgrade
    
  4. 安装 Java:

    [ec2-user ~]$ sudo amazon-linux-extras install java-openjdk11 -y
    
  5. 安装 Jenkins:

    [ec2-user ~]$ sudo yum install jenkins -y
    
  6. 启用 Jenkins 服务开机自动启动:

    [ec2-user ~]$ sudo systemctl enable jenkins
    
  7. 以服务形式启动 Jenkins:

    [ec2-user ~]$ sudo systemctl start jenkins
    
  8. 您可以使用以下命令检查 Jenkins 服务的状态:

    [ec2-user ~]$ sudo systemctl status jenkins
    
  9. 以防万一我们在设置/配置过程中需要重启 Jenkins。

    [ec2-user ~]$ sudo systemctl restart jenkins
    

配置 Jenkins
  1. 复制EC2 实例的公有 IPv4 DNS 地址,并将 URL 粘贴到浏览器中,例如:http://ec2-54-211-70-130.compute-1.amazonaws.com: 8080
  2. 输入初始管理员密码,/var/lib/jenkins/secrets/initialAdminPassword然后单击“继续”。

    [ec2-user@ip-172-31-89-157 ~]$ sudo cat /var/lib/jenkins/secrets/initialAdminPassword
        671x0x5x3xxx46xxxxxx099x1xf0149x
    
  3. 选择“安装推荐插件”。

  4. 安装完成后,将打开“创建第一个管理员用户”窗口。输入您的信息,然后选择“保存继续”

  5. 点击“控制面板”,选择“管理 Jenkins”,然后选择“管理插件”

  6. 点击“可用插件”,搜索并选择“Amazon EC2”,然后点击“无需重启即可安装”。

  7. 安装完成后,返回控制面板,选择“管理 Jenkins”,选择“管理节点和云”,然后单击“配置云”

  8. 选择“添加新云”,然后选择“Amazon EC2”。此时会弹出一个新窗口,其中包含更多字段。

  9. 点击 Amazon EC2 凭证下的“添加”,然后选择Jenkins

    • Jenkins 凭证提供程序:Jenkins,选择AWS 凭证作为种类。
    • 输入密钥对中的访问密钥 ID秘密访问密钥,然后单击“添加”
  10. 向下滚动至“地区”并选择您的地区。

  11. 点击EC2 密钥对私钥下的“添加” ,然后选择Jenkins

    • Jenkins 凭据提供程序:Jenkins,选择SSH Username with private key“Kind”作为类型,并将“Username”设置为ec2-user
    • 在“私钥”Enter Directly选择,然后选择“添加”。
    • 打开您在创建密钥对步骤中创建的私钥对,并将内容从 粘贴-----BEGIN RSA PRIVATE KEY-----到。完成后,-----END RSA PRIVATE KEY-----选择“添加” 。
  12. 向下滚动到“测试连接”并确保其显示“测试连接” Success,然后单击“保存”

Jenkins_Configure1

Jenkins_Configure1

Jenkins_Configure2

Jenkins_Configure2

Jenkins_Configure3

Jenkins_Configure3

Jenkins_Configure4

Jenkins_Configure4

Jenkins_Configure5

Jenkins_Configure5

Jenkins_Configure6

Jenkins_Configure6

Jenkins_Configure7

Jenkins_Configure7

Jenkins_Configure8

Jenkins_Configure8

Jenkins_Configure9

Jenkins_Configure9

Jenkins_Configure10

Jenkins_Configure10

Jenkins_Configure10.1

Jenkins_Configure10.1

Jenkins_Configure10.2

Jenkins_Configure10.2

Jenkins_Configure11

Jenkins_Configure11

Jenkins_Configure11.1

Jenkins_Configure11.1

Jenkins_Configure11.2

Jenkins_Configure11.2

Jenkins_Configure12

Jenkins_Configure12


步骤 6:创建管道

  1. 导航至“控制面板” > “管理 Jenkins”,复制在步骤 1 中创建的 IAM 用户ID,我们需要将其替换IDxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  2. 导航至控制面板>管理 Jenkins >插件管理器> 点击可用插件
  3. 搜索AWS 步骤安装,无需重启
  4. 导航至仪表板>新建作业> 输入download-a-file-from-s3> 选择管道并单击确定
  5. 向下滚动到“管道”,添加以下内容Pipeline script,然后单击“保存”。
  6. 创建一个S3存储桶,并将一些文件复制到该存储桶中。
  7. 将 `<bucket_name>` 替换s3bucket为您的存储桶名称,并将 `<file>`filename替换为您的 S3 存储桶中的一个文件。
  8. 导航至“控制面板” > “从 S3 下载文件”,然后单击“立即构建”
  9. 导航至最新的构建历史记录链接并查看控制台输出

    pipeline 
    {
    agent any
        stages
        {
        stage('S3download') 
            {      
                steps {
                    withAWS(region:'us-east-1',credentials:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')\
                    {
                        s3Download(file: "filename", bucket: 's3bucket', path: '')
                    }
                }
            }
        }
    }
    

Jenkins_Pipeline1

Jenkins_Pipeline1

Jenkins_Pipeline2

Jenkins_Pipeline2

Jenkins_Pipeline3

Jenkins_Pipeline3

Jenkins_Pipeline4

Jenkins_Pipeline4

以下是控制台日志,显示管道已成功运行。✅

Started by user Sri
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/download-a-file-from-s3
[Pipeline] {
[Pipeline] stage
[Pipeline] { (S3download)
[Pipeline] withAWS
Constructing AWS CredentialsSetting AWS region us-east-1 
[Pipeline] {
[Pipeline] s3Download
Downloading s3://s3bucket/ to file:/var/lib/jenkins/workspace/download-a-file-from-s3/receiveMessages.sh 
Finished: Downloading from s3bucket/
Download complete
[Pipeline] }
[Pipeline] // withAWS
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Enter fullscreen mode Exit fullscreen mode

从 S3 复制到 EC2 实例的文件。✅

[ec2-user@ip-172-31-89-157 ~]$ ls -lrt /var/lib/jenkins/workspace/download-a-file-from-s3/
total 0
drwxr-xr-x 2 jenkins jenkins 55 Dec 31 03:45 receiveMessages.sh
Enter fullscreen mode Exit fullscreen mode

让我们再次运行构建,这次构建失败,出现以下错误❓
错误信息建议使用set force=true.

Started by user Sri
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/download-a-file-from-s3
[Pipeline] {
[Pipeline] stage
[Pipeline] { (S3download)
[Pipeline] withAWS
Constructing AWS CredentialsSetting AWS region us-east-1 
[Pipeline] {
[Pipeline] s3Download
Downloading s3://s3bucket/ to file:/var/lib/jenkins/workspace/download-a-file-from-s3/receiveMessages.sh/ 
Download failed due to existing target file; set force=true to overwrite target file
[Pipeline] }
[Pipeline] // withAWS
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.RuntimeException: Target exists: file:/var/lib/jenkins/workspace/download-a-file-from-s3/receiveMessages.sh/
    at de.taimos.pipeline.aws.S3DownloadStep$Execution.run(S3DownloadStep.java:146)
    at de.taimos.pipeline.aws.S3DownloadStep$Execution.run(S3DownloadStep.java:113)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
Finished: FAILURE
Enter fullscreen mode Exit fullscreen mode

因此,我们需要force:true按照Pipeline: AWS Steps 文档进行添加。

pipeline 
{
agent any
    stages
    {
    stage('S3download') 
        {      
            steps {
                withAWS(region:'us-east-1',credentials:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')\
                {
                    s3Download(file: "filename", bucket: 's3bucket', path: '', force:true)
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

添加完成后构建成功force:true,现在我们可以多次运行构建。

现在让我们来参数化目标文件夹名称。
  1. 导航至“控制面板”>“从 S3 下载文件”,然后单击“配置”。
  2. 选择“此项目已参数化”,然后选择“添加字符串参数” 。
  3. 输入名称默认值foldername然后保存foldername
  4. 点击“使用参数构建”
  5. 导航至最新的构建历史记录链接并查看控制台输出
pipeline 
{
agent any
    stages
    {
    stage('S3download') 
        {      
            steps {
                withAWS(region:'us-east-1',credentials:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')\
                {
                    echo "${foldername}" 
                    s3Download(file: "${foldername}", bucket: 's3bucket', path: '', force:true)
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Jenkins_Pipeline_Parameter

Jenkins_Pipeline_Parameter

Jenkins_Pipeline_Build-with-Parameters

Jenkins_Pipeline_Build-with-Parameters

以下是控制台日志,显示管道已成功运行。✅

Started by user Sri
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/download-a-file-from-s3
[Pipeline] {
[Pipeline] stage
[Pipeline] { (S3download)
[Pipeline] withAWS
Constructing AWS CredentialsSetting AWS region us-east-1 
[Pipeline] {
[Pipeline] echo
s3files
[Pipeline] s3Download
Downloading s3://s3bucket/ to file:/var/lib/jenkins/workspace/download-a-file-from-s3/s3files 
Finished: Downloading from sqssri/
Download complete
[Pipeline] }
[Pipeline] // withAWS
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Enter fullscreen mode Exit fullscreen mode

文件已复制到EC2 实例上的s3files目录。✅

[ec2-user@ip-172-31-89-157 ~]$ ls -lrt /var/lib/jenkins/workspace/download-a-file-from-s3/s3files 
total 8
-rw-r--r-- 1 jenkins jenkins 952 Dec 31 03:40 receiveMessages.sh
-rw-r--r-- 1 jenkins jenkins 646 Dec 31 03:40 sendMessages.sh
Enter fullscreen mode Exit fullscreen mode

清理

  1. 删除该EC2实例。
  2. 删除JenkinsUser
  3. 删除key pair
  4. 删除安全组JenkinsSG

概括

  • 我们学习了如何安装和配置 Jenkins。
  • 我们还学习了如何搭建管道。

转诊

文章来源:https://dev.to/aws-builders/how-to-set-up-jenkins-and-a-pipeline-on-aws-2pak