Getting current timestamp in inline pipeline script using pipeline plugin of hudson

自古美人都是妖i 提交于 2019-12-04 00:25:18

Jenkins scripts are running in a sandbox, by default the Groovy script doesn't have permissions for some operations.

When you perform an operation without permissions the RejectAccessException is thrown. So you've to execute your script, and then when the exception is thrown go to:

http://yourHost/jenkins/scriptApproval/

And approve the necessary permission:

dsaydon

you can also use this, I needed this in ms so:

echo "TimeStamp: ${currentBuild.startTimeInMillis}"

echo "TimeStamp: ${Util.getTimeSpanString(System.currentTimeMillis())}"

There are a bunch of ways to get time depending on what APIs you find most intuitive:

  1. new Date() has since been added to the script-security-plugin whitelist

  2. RunWrapper APIs through use of currentBuild global variable

    1. final long startTime = currentBuild.startTimeInMillis: long value of when the build was started in milliseconds
    2. final long scheduledTime = currentBuild.timeInMillis: long value of when the build was scheduled in milliseconds
    3. final long buildDuration = currentBuild.duration: milliseconds it has taken to build
    4. final String buildDurationAsStrong = currentBuild.durationString: duration as a String
  3. Using whitelisted java.time APIs, for example LocalDateTime

    import java.time.LocalDateTime
    final LocalDateTime currentTime = LocalDateTime.now()
    // do stuff with LocalDateTime
    
  4. Of course, shelling out and using the return value in your script

    final String currentTime = sh(returnStdout: true, script: 'date +%Y-%m-%d').trim()
    

And I'm sure there are other methods, too.

You can also avoid script approvals by using LocalDateTime or LocalDate in string context. These will give you ISO 8601 defaults:

script {
  DATE_TAG = java.time.LocalDate.now()
  DATETIME_TAG = java.time.LocalDateTime.now()
}
sh "echo ${DATETIME_TAG}"

Just format the Date object:

stage('Foo') {
  steps {
    script {
        def now = new Date()
        println now.format("yyMMdd.HHmm", TimeZone.getTimeZone('UTC'))
    }
  } 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!