问题
前端也想用Jenkins的CI/CD工作流。
步骤
Jenkins安装NodeJS插件
安装完成,记得重启Jenkins。
全局配置nodejs
Jenksinfile
pipeline {agent anytools {nodejs "18.15.0"}stages {stage('Check tool version') {steps {sh '''node -vnpm -vnpm config ls'''}}stage('Build Preparation') {steps {sh '''corepack enable pnpmpnpm i'''}}stage('Build') {steps {script {if (env.BRANCH_NAME.startsWith('develop')){sh '''pnpm run build:dev'''} else if (env.BRANCH_NAME.startsWith('uat')){sh '''pnpm run build:uat'''} else {echo 'Skipping pnpm run.'}}}}stage('S3 Sync') {steps {script {if (env.BRANCH_NAME.startsWith('release')){sh '''aws s3 sync ./dist/ s3://prod-web-xxxx/ --exclude "xxxx/*" --exclude "h5/*" --delete'''} else if (env.BRANCH_NAME.startsWith('uat')){sh '''aws s3 sync ./dist/ s3://uat-web-xxxx/ --exclude "xxxx/*" --exclude "h5/*" --delete'''} else {echo 'Skipping S3 Sync.'}}}}stage('CDN invalidation') {steps {script {if (env.BRANCH_NAME.startsWith('release')){sh '''aws cloudfront create-invalidation --distribution-id XXXX --paths '/*''''} else if (env.BRANCH_NAME.startsWith('uat')){sh '''aws cloudfront create-invalidation --distribution-id xxxx --paths '/*''''} else {echo 'Skipping CDN invalidation.'}}}}}
}
这里的18.15.0
必须与上一步中Jenkins安装的NodeJS名称一致。这里还涉及到将文件上传到s3桶和刷新CDN的过程。
创建Jenkins多分支项目
这里设置git源复制一点点,最后,保存应用。
S3同步部署文件权限(可选)
我这里用的是AWS云,所以,这里需要对运行的Jenkins需要设置相关权限。
{"Version": "2012-10-17","Statement": [{"Sid": "ListObjectsInBucket","Effect": "Allow","Action": ["s3:ListBucket"],"Resource": ["arn:aws:s3:::dev-xxx"]},{"Sid": "AllObjectActions","Effect": "Allow","Action": "s3:*Object","Resource": ["arn:aws:s3:::dev-xxx/*"]}]
}
CloudFront刷新权限(可选)
{"Version": "2012-10-17","Statement": [{"Sid": "VisualEditor0","Effect": "Allow","Action": "cloudfront:CreateInvalidation","Resource": "arn:aws:cloudfront::xxxxxxx:distribution/xxxxxxx"}]
}
总结
到这里Jenkins打包前端的工程就结束了。aws cli挺好用的,要是Jenkins出个官方插件就好了。
参考
- NodeJS
- CI/CD Pipeline for a NodeJS Application with Jenkins