如何在Jenkinsfile中循环读取文件并逐行执行ImageScan阶段
Solution for Scanning Multiple Docker Images in Jenkins Pipeline
Here's how to read your images.txt file line by line and run the prismaCloudScanImage step for each image URL in a dedicated stage:
Step 1: Read and Process the Image URL List
First, read the file, clean up each line (trim whitespace, remove empty lines) to get a list of valid image URLs using Jenkins' built-in readFile pipeline step.
Step 2: Dynamically Generate Scan Stages
Use a loop to create a separate ImageScan stage for each URL, passing the URL to the scan step as the image parameter.
Complete Declarative Jenkinsfile Example
pipeline { agent any stages { stage('Prepare Image List') { steps { script { // Read file, split into lines, filter out empty/whitespace-only entries env.IMAGE_URLS = readFile('images.txt').split('\n') .collect { it.trim() } .findAll { it } } } } stage('Scan Images') { steps { script { env.IMAGE_URLS.each { imageUrl -> stage("ImageScan - ${imageUrl}") { echo "Scanning image: ${imageUrl}" // Execute Prisma Cloud scan with the current image URL prismaCloudScanImage(image: imageUrl) // Optional: Keep scanning other images if one fails // catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { // prismaCloudScanImage(image: imageUrl) // } } } } } } } }
Key Details
- File Handling:
readFile('images.txt')pulls the file from your Jenkins workspace—ensure the file exists here (e.g., checked out from version control or generated in an earlier stage). - Line Cleaning: Trimming whitespace and filtering empty lines prevents invalid scan attempts for blank entries.
- Dynamic Stages: Each image gets its own named stage, making it easy to track pass/fail status for individual scans in the Jenkins UI.
- Error Handling: Uncomment the
catchErrorblock if you want the pipeline to continue scanning other images even if one scan fails (adjust result statuses as needed).
Alternative Scripted Pipeline Version
If you're using a scripted pipeline, the code is more concise:
node { def imageUrls = readFile('images.txt').split('\n') .collect { it.trim() } .findAll { it } imageUrls.each { imageUrl -> stage("ImageScan - ${imageUrl}") { echo "Scanning image: ${imageUrl}" prismaCloudScanImage(image: imageUrl) } } }
内容的提问来源于stack exchange,提问作者KJa
相关产品推荐
相关产品推荐

