Jenkinsfile 使用 s3FindFiles 在 S3 中查找文件

Jenkinsfile find files in S3 with s3FindFiles

我想在 Jenkinsfile(管道)中使用 s3FindFiles 来搜索 S3 存储桶中的文件。我试着按照

的方式使用它
        steps {
            withCredentials([[
                $class: 'AmazonWebServicesCredentialsBinding',credentialsId: 'jenkins-user-for-aws',accessKeyVariable: 'AWS_ACCESS_KEY_ID',secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
            ]]) {
                    s3FindFiles(bucket:'my-bucket', path:'firmwares/', glob:'gwsw_*')
                }
        }

打印

      Searching s3://my-bucket/firmwares/ for glob:'gwsw_*' 
      Search complete

如何从中获取文件名?

根据s3FindFiles它return name,所以我尝试了

    steps {
                withCredentials([[
                    $class: 'AmazonWebServicesCredentialsBinding',credentialsId: 'jenkins-user-for-aws',accessKeyVariable: 'AWS_ACCESS_KEY_ID',secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                ]]) {
                        files = s3FindFiles(bucket:'my-bucket', path:'firmwares/', glob:'gwsw_*')
                        echo files[0].name
                    }
            }

但是出现了这个错误:

 WorkflowScript: 256: Expected a step @ line 256, column 19.
                   files = s3FindFiles(bucket:'my-bucket', path:"firmwares/", glob:'gwsw_*')

s3FindFiles

return an array of FileWrapper instances with the following properties:

  • name: the filename portion of the path (for "path/to/my/file.ext", this would be "file.ext")
  • path: the full path of the file, relative to the path specified (for path="path/to/", this property of the file "path/to/my/file.ext" would be "my/file.ext")
  • directory: true if this is a directory; false otherwise length: the length of the file (this is always "0" for directories)
  • lastModified: the last modification timestamp, in milliseconds since the Unix epoch (this is always "0" for directories)

您可以使用上述属性或 dedicated methods

简单地迭代返回的数组

例如:获取文件名

name_by_property = files[0].name   
name_by_method = files[0].getName()

如果您使用 declarative pipeline,您需要用 script 块包装您的代码:

steps {
        withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'jenkins-user-for-aws', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {

            script{
              files = s3FindFiles(bucket:'my-bucket', path:'firmwares/', glob:'gwsw_*', onlyFiles: true)
              
              // get the first name
              println files[0].name

              // iterate over all files
              files.each { println "File name: ${it.name}, timestamp: ${it.lastModified}"}
            }
        }
    }