首页 > 解决方案 > Jenkinsfile 使用 s3FindFiles 在 S3 中查找文件

问题描述

我想s3FindFiles在 Jenkinsfile(管道)中使用来搜索 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它返回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_*')

标签: jenkinsjenkins-pipelinejenkins-plugins

解决方案


s3FindFiles

返回具有以下属性的 FileWrapper 实例数组:

  • name:路径的文件名部分(对于“path/to/my/file.ext”,这将是“file.ext”)
  • path:文件的完整路径,相对于指定的路径(对于 path="path/to/",文件 "path/to/my/file.ext" 的此属性将为 "my/file.ext" )
  • 目录:如果这是一个目录,则为 true;false 否则 length:文件的长度(对于目录,这始终为“0”)
  • lastModified:最后一次修改时间戳,自 Unix 纪元以来的毫秒数(对于目录,这始终为“0”)

您可以使用上面的属性或专用方法简单地迭代返回的数组

eg:获取文件名

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}"}
            }
        }
    }

推荐阅读