[
  {
    "path": ".gitignore",
    "content": "*.tex\n.DS_Store\nREADME.pdf\n"
  },
  {
    "path": "00-csrf.groovy",
    "content": "// https://wiki.jenkins.io/display/JENKINS/CSRF+Protection\nimport hudson.security.csrf.DefaultCrumbIssuer\nimport jenkins.model.Jenkins\n \ndef instance = Jenkins.instance\ninstance.setCrumbIssuer(new DefaultCrumbIssuer(true))\ninstance.save()\n"
  },
  {
    "path": "00-disable-cli-remoting.groovy",
    "content": "// https://stackoverflow.com/questions/44501596/jenkins-disable-cli-over-remoting-via-a-groovy-script\nimport jenkins.model.Jenkins\n\njenkins.model.Jenkins.instance.getDescriptor(\"jenkins.CLI\").get().setEnabled(false)\nJenkins.instance.save()\n"
  },
  {
    "path": "00-slave-to-master-access.groovy",
    "content": "// https://wiki.jenkins.io/display/JENKINS/Slave+To+Master+Access+Control\nimport jenkins.security.s2m.AdminWhitelistRule\nimport jenkins.model.Jenkins\nJenkins.instance.getInjector().getInstance(AdminWhitelistRule.class).setMasterKillSwitch(false)\n"
  },
  {
    "path": "README.org",
    "content": "* CheatSheet: Jenkins & Groovy                                    :Languages:\n:PROPERTIES:\n:type:     language\n:export_file_name: cheatsheet-jenkins-groovy-A4.pdf\n:END:\n\n#+BEGIN_HTML\n<a href=\"https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4\"><img align=\"right\" width=\"200\" height=\"183\" src=\"https://www.dennyzhang.com/wp-content/uploads/denny/watermark/github.png\" /></a>\n<div id=\"the whole thing\" style=\"overflow: hidden;\">\n<div style=\"float: left; padding: 5px\"> <a href=\"https://www.linkedin.com/in/dennyzhang001\"><img src=\"https://www.dennyzhang.com/wp-content/uploads/sns/linkedin.png\" alt=\"linkedin\" /></a></div>\n<div style=\"float: left; padding: 5px\"><a href=\"https://github.com/dennyzhang\"><img src=\"https://www.dennyzhang.com/wp-content/uploads/sns/github.png\" alt=\"github\" /></a></div>\n<div style=\"float: left; padding: 5px\"><a href=\"https://www.dennyzhang.com/slack\" target=\"_blank\" rel=\"nofollow\"><img src=\"https://www.dennyzhang.com/wp-content/uploads/sns/slack.png\" alt=\"slack\"/></a></div>\n</div>\n\n<br/><br/>\n<a href=\"http://makeapullrequest.com\" target=\"_blank\" rel=\"nofollow\"><img src=\"https://img.shields.io/badge/PRs-welcome-brightgreen.svg\" alt=\"PRs Welcome\"/></a>\n#+END_HTML\n\n- PDF Link: [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/cheatsheet-jenkins-groovy-A4.pdf][cheatsheet-jenkins-groovy-A4.pdf]], Category: [[https://cheatsheet.dennyzhang.com/category/languages/][languages]]\n- Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-A4\n- Related posts: [[https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-A4][Jenkins CheatSheet]], [[https://github.com/topics/denny-cheatsheets][#denny-cheatsheets]]\n\nFile me [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/issues][Issues]] or star [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4][this repo]].\n** Jenkins Pipeline\n| Name                                      | Comment                                                                   |\n|-------------------------------------------+---------------------------------------------------------------------------|\n| Specify parameter to run jobs             | =build job:'job1', parameters:[string(name:'name1', value:va1)]=          |\n| Run job in different agents               | =node($agent_label) {...}=                                                |\n| Ask for user input                        | =stage('stage2'){ input \"OK to go?\" }=                                    |\n| Actively fail current pipeline job        | =error(\"Build failed because of this and that..\")=                        |\n| List all Jenkins plugins and versions     | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/list-all-plugins.groovy][list-all-plugins.groovy]]                                                   |\n| [[https://stackoverflow.com/questions/43875093/check-if-property-exists-groovy][Check whether property exists]]             | =if (env.keep_failed_env)=                                                |\n| [[https://stackoverflow.com/questions/47039924/jenkins-pipeline-enable-timestamps-in-build-log-console][Jenkins Pipeline enable timestamps]]        | =options{timestamps()}=                                                   |\n| [[https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-withenv-code-set-environment-variables][Set envs within a jenkins pipeline]]        | =withEnv([\"key1=$var1\"])=                                                 |\n| Install plugin via groovy                 | =Hudson.instance.updateCenter.getPlugin(plugin).deploy().get()=           |\n| Keep previous job run via groovy          | =buildDiscarder(logRotator(daysToKeepStr: '20', numToKeepStr: '60'))=     |\n| [[https://jenkins.io/doc/book/pipeline/syntax/][Customize job workspace]]                   | =customWorkspace \"/some/other/path\"=                                      |\n| [[https://jenkins.io/doc/pipeline/steps/workflow-scm-step/][git scm checkout to relative directory]]    | =extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'XXX']]= |\n| Keep going when previous stage has failed | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/keep-going-with-errors.groovy][keep-going-with-errors.groovy]]                                             |\n| Send slack notification in pipeline       | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/slack-notification.groovy][slack-notification.groovy]]                                                 |\n| Pass parameter across jenkins jobs        | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkinsfile-pass-parameter.groovy][jenkinsfile-pass-parameter.groovy]]                                         |\n| Set timeout & retry                       | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkinsfile-timeout-retry.groovy][jenkinsfile-timeout-retry.groovy]]                                          |\n| Use finally to do cleanup                 | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkinsfile-finally.groovy][jenkinsfile-finally.groovy]]                                                |\n| Run jenkins jobs in a sequential way      | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkinsfile-sequentially.groovy][jenkinsfile-sequentially.groovy]]                                           |\n| Run jenkins jobs in parallel              | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkinsfile-parallelly.groovy][jenkinsfile-parallelly.groovy]]                                             |\n| Reference                                 | [[https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Syntax-Reference][Link: Syntax Reference]], [[https://jenkins.io/doc/][Link: Jenkins User Documentation]]                  |\n| Reference                                 | [[http://docs.groovy-lang.org/latest/html/documentation/][Link: Groovy Language Documentation]]                                       |\n| Reference                                 | [[https://gist.github.com/jonico/e205b16cf07451b2f475543cf1541e70][Link: Example]], [[https://gist.github.com/vdupain/832964527b4b8d7d4c648169dae8c656][Link: Example]]                                              |\n** Config Jenkins Via Groovy\n| Name                                 | Comment                                                                                   |\n|--------------------------------------+-------------------------------------------------------------------------------------------|\n| Set timezone for jenkins             | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/timezone.groovy][timezone.groovy]]                                                                           |\n| Set timezone for jenkins             | =System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'America/Los_Angeles')= |\n| Configure default view               | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-views.groovy][jenkins-views.groovy]]                                                                      |\n| Configure Jenkins url                | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-url.groovy][jenkins-url.groovy]]                                                                        |\n| Create a Jenkins user                | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/create-jenkins-user.groovy][create-jenkins-user.groovy]]                                                                |\n| Groovy manages files/folders         | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/files-folder.groovy][files-folder.groovy]]                                                                       |\n| Configure max executors in Jenkins   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/master-executors.groovy][master-executors.groovy]]                                                                   |\n| Configure only 1 executor per worker | For each agent, configure # of executors                                                  |\n| Configure slack plugin               | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/config-slack.groovy][config-slack.groovy]]                                                                       |\n| Configure pipeline shared libraries  | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/config-pipeline-library.groovy][config-pipeline-library.groovy]]                                                            |\n| [[https://stackoverflow.com/questions/34585356/get-jenkins-version-via-java-jar-jenkins-war-version-without-spam-output][Get jenkins version from CLI]]         | =java -jar /usr/share/jenkins/jenkins.war --version=                                      |\n| Reference                            | [[https://github.com/cloudbees/jenkins-scripts][GitHub: cloudbees/jenkins-scripts]], [[https://github.com/jenkinsci/pipeline-examples][GitHub: jenkinsci/pipeline-examples]]                    |\n** Jenkins Trouble Shooting\n| Name                                             | Comment                   |\n|--------------------------------------------------+---------------------------|\n| List performance metrics for each Jenkins agents | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/list-all-jenkins-agent.sh][list-all-jenkins-agent.sh]] |\n** Jenkins Kubernetes Via Groovy\n| Name                                | Comment                                     |\n|-------------------------------------+---------------------------------------------|\n| Config jenkins kubernetes plugin    | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-kubernetes-cloud.groovy][jenkins-kubernetes-cloud.groovy]]             |\n| Validate Kubernetes jenkins setup   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/validate-kubernetes-cloud.groovy][validate-kubernetes-cloud.groovy]]            |\n| Kubernetes run with envs configured | [[https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/resources/org/csanchez/jenkins/plugins/kubernetes/pipeline/runWithEnvVariables.groovy][runWithEnvVariables.groovy]]                  |\n| Reference                           | [[https://github.com/jenkinsci/kubernetes-plugin/tree/master/src/test/resources/org/csanchez/jenkins/plugins/kubernetes/pipeline][GitHub: kubernetes-plugin pipeline examples]] |\n** Jenkins View Via Groovy\n| Name                                    | Comment                                                                    |\n|-----------------------------------------+----------------------------------------------------------------------------|\n| [[https://javadoc.jenkins.io/hudson/model/ListView.html#setIncludeRegex-java.lang.String-][Add a list of jobs by regexp to a view]]  | =myView.setIncludeRegex(\".*Integration.*\")=, [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/addjobstoview-byregexp.groovy][addjobstoview-byregexp.groovy]] |\n| Create jenkins views and add jobs to it | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-views.groovy][jenkins-views.groovy]]                                                       |\n| [[https://github.com/jan-molak/jenkins-build-monitor-plugin/blob/master/build-monitor-plugin/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView.java][Add a view of build monitor view plugin]] | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/build-monitor-views.xml][build-monitor-views.xml]]                                                    |\n| [[https://stackoverflow.com/questions/39111350/how-to-set-a-views-description-in-groovy][Change view description in groovy]]       | =myView.doSubmitDescription=                                               |\n#+BEGIN_HTML\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" width=\"185\" height=\"37\" src=\"https://raw.githubusercontent.com/dennyzhang/cheatsheet.dennyzhang.com/master/images/cheatsheet_dns.png\"></a>\n#+END_HTML\n** Jenkins Job Via Groovy\n| Name                                            | Comment                                                 |\n|-------------------------------------------------+---------------------------------------------------------|\n| List all my jenkins jobs                        | =println Jenkins.instance.projects.collect { it.name }= |\n| List all jenkins jobs                           | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/list-all-jobs.groovy][list-all-jobs.groovy]]                                    |\n| Create and trigger a job                        | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/create-jenkins-job.groovy][create-jenkins-job.groovy]]                               |\n| Manage jenkins jobs                             | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/manage-jenkins-jobs.groovy][manage-jenkins-jobs.groovy]]                              |\n| Cancel queued jenkins jobs by regexp            | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/kill-queued-jenkins.groovy][kill-queued-jenkins.groovy]]                              |\n| [[https://stackoverflow.com/questions/33821217/html-in-jenkins-job-descriptions][Support HTML for job and parameter descriptions]] | [[https://wiki.jenkins.io/display/JENKINS/OWASP+Markup+Formatter+Plugin][Link: OWASP Markup Formatter Plugin]]                     |\n** Jenkins Different Parameters\n| Name     | Comment                                                                              |\n|----------+--------------------------------------------------------------------------------------|\n| string   | =string(name: 'key1', defaultValue: 'Default value', description: 'some parameter')= |\n| text     | =text(name: 'key1', defaultValue: 'Default value', description: 'some parameter')=   |\n| boolean  | =booleanParam(name: 'key1', defaultValue: true, description: 'some parameter')=      |\n| choice   | =choice(name: 'key1', choices: 'One\\nTwo\\nThree\\n', description: 'some parameter')=  |\n| password | =password(name: 'key1', defaultValue: 'SECRET', description: 'Enter a password')=    |\n| file     | =file(name: 'key1', description: 'Choose a file to upload')=                         |\n** Jenkins Security Via Groovy\n| Name                                     | Comment                                                          |\n|------------------------------------------+------------------------------------------------------------------|\n| logged-in users can do anything          | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/logged-in-users.groovy][logged-in-users.groovy]]                                           |\n| [[https://wiki.jenkins.io/display/JENKINS/LDAP+Plugin][Enable ldap in Jenkins]]                   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/enable-ldap.groovy][enable-ldap.groovy]]                                               |\n| Create a jenkins secret text             | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/create-secret-text.groovy][create-secret-text.groovy]]                                        |\n| Configure authorization in Jenkins       | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/matrix-authorization-strategy.groovy][matrix-authorization-strategy.groovy]]                             |\n| [[https://stackoverflow.com/questions/35960883/how-to-unlock-jenkins][Jenkins skip wizzard when initialization]] | -Djenkins.install.runSetupWizard=false                           |\n| [[https://stackoverflow.com/questions/35960883/how-to-unlock-jenkins][Jenkins skip wizzard when initialization]] | =instance.setInstallState(InstallState.INITIAL_SETUP_COMPLETED)= |\n| [[https://wiki.jenkins.io/display/JENKINS/Slave+To+Master+Access+Control][Slave To Master Access Control]]           | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/00-slave-to-master-access.groovy][00-slave-to-master-access.groovy]]                                 |\n| [[https://wiki.jenkins.io/display/JENKINS/CSRF+Protection][CSRF Protection]]                          | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/00-csrf.groovy][00-csrf.groovy]]                                                   |\n| Add Jenkins permission                   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-permission.groovy][jenkins-permission.groovy]]                                        |\n| Disable CLI over Remoting                | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/00-disable-cli-remoting.groovy][00-disable-cli-remoting.groovy]]                                   |\n| Disable jnlp                             | =jenkins.setSlaveAgentPort(-1)=                                  |\n| [[https://wiki.jenkins.io/display/JENKINS/Authorize+Project+plugin][Access Control for Builds]]                | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins.security.QueueItemAuthenticatorConfiguration.xml][jenkins.security.QueueItemAuthenticatorConfiguration.xml]]         |\n** Load Jenkins settings via folder copy\n| Name                                 | Comment                                                                  |\n|--------------------------------------+--------------------------------------------------------------------------|\n| [[https://stackoverflow.com/questions/43691539/create-jenkins-docker-image-with-pre-configured-jobs][Add default jobs]]                     | =Copy jobs/ /usr/share/jenkins/ref/jobs/=                                |\n| Copy custom built plugins            | =COPY plugins/*.hpi /usr/share/jenkins/ref/plugins/=                     |\n| Use jenkins cli                      | =COPY config/jenkins.properties /usr/share/jenkins/ref/=                 |\n| Add jenkins groovy scripts           | =COPY config/*.groovy /usr/share/jenkins/ref/init.groovy.d/=             |\n| Configure Jenkins with some defaults | =COPY config/*.xml /usr/share/jenkins/ref/=                              |\n| [[https://github.com/jenkinsci/docker/tree/587b2856cd225bb152c4abeeaaa24934c75aa460#script-usage][Install jenkins plugins]]              | =/usr/local/bin/install-plugins.sh < /usr/share/jenkins/ref/plugins.txt= |\n#+BEGIN_HTML\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" width=\"185\" height=\"37\" src=\"https://raw.githubusercontent.com/dennyzhang/cheatsheet.dennyzhang.com/master/images/cheatsheet_dns.png\"></a>\n#+END_HTML\n** Jenkins Plugins\n| Plugin                     | Summary                                                                   |\n|----------------------------+---------------------------------------------------------------------------|\n| [[https://github.com/jenkinsci/kubernetes-plugin][Kubernetes Plugin]]          | Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment   |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/Credentials+Plugin][Credentials Plugin]]         | Load the ssh key                                                          |\n| [[https://wiki.jenkins.io/display/JENKINS/SiteMonitor+Plugin][SiteMonitor Plugin]]         | Monitor URLs                                                              |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/Timestamper][Timestamper Plugin]]         | Add timestamp to job output                                               |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/Dashboard+View][Dashboard View Plugin]]      | Create dashboard                                                          |\n| [[https://wiki.jenkins.io/display/JENKINS/Log+Parser+Plugin][Log Parser Plugin]]          | Parse the console output and highlight error/warning/info lines.          |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/Build-timeout+Plugin][Build-timeout Plugin]]       | Abort if job takes too long                                               |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/Naginator+Plugin][Naginator Plugin]]           | Retry failed a job                                                        |\n| [[https://wiki.jenkins-ci.org/display/JENKINS/thinBackup][ThinBackup Plugin]]          | Backup jenkins                                                            |\n| [[https://plugins.jenkins.io/jobConfigHistory][JobConfigHistory Plugin]]    | Backup job configuration                                                  |\n| [[https://wiki.jenkins.io/pages/viewpage.action?pageId=60915753][\"Anything Goes\" formatter]]  | use JavaScript inside your project description                            |\n| [[https://wiki.jenkins.io/display/JENKINS/AnsiColor+Plugin][AnsiColor Plugin]]           | Add support for ANSI escape sequences, including color, to Console Output |\n| [[https://wiki.jenkins.io/display/JENKINS/Build+User+Vars+Plugin][Build User Vars Plugin]]     | Describe the user who started the build                                   |\n| [[https://wiki.jenkins.io/display/JENKINS/GitLab+Plugin][Gitlab Plugin]]              | Allows GitLab to trigger Jenkins builds                                   |\n| [[https://wiki.jenkins.io/display/JENKINS/Workspace+Cleanup+Plugin][Workspace Cleanup]]          | Plugin to delete the build workspace.                                     |\n| [[https://wiki.jenkins.io/display/JENKINS/UpdateSites+Manager+plugin][UpdateSites Manager plugin]] | manage update sites, where Jenkins accesses in order to retrieve plugins  |\n** Jenkins Git Via Groovy\n| Name                                   | Comment                           |\n|----------------------------------------+-----------------------------------|\n| Git checkout code                      | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/git-checkout.groovy][git-checkout.groovy]]               |\n| Get all git commits since last success | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/git-commits-before-fail.groovy][git-commits-before-fail.groovy]]    |\n| List git tags and branches             | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/git-list-tags-and-branches.groovy][git-list-tags-and-branches.groovy]] |\n\n** Jenkins networking Via Groovy\n| Name                            | Comment                                                                  |\n|---------------------------------+--------------------------------------------------------------------------|\n| Get hostname                    | =println InetAddress.localHost.canonicalHostName=                        |\n| Get IP address                  | =println InetAddress.localHost.hostAddress=                              |\n| Get hostname by ip              | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/get-ip-by-hostname.groovy][get-ip-by-hostname.groovy]]                                                |\n| validate user input: ip address | =assert ip_address.matches(\"\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\")= |\n** Jenkins with Kubernetes/Docker\n| Name                                               | Comment                                                                 |\n|----------------------------------------------------+-------------------------------------------------------------------------|\n| [[https://github.com/jenkinsci/kubernetes-plugin][Kubernetes Plugin]]                                  | Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment |\n| Config jenkins kubernetes plugin                   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/jenkins-kubernetes-cloud.groovy][jenkins-kubernetes-cloud.groovy]]                                         |\n| Cleanup for Docker stale containers/images/volumes | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/docker-cleanup.groovy][docker-cleanup.groovy]]                                                   |\n| Jenkins customize docker build args                | =additionalBuildArgs '--build-arg SSH_PRIVATE_KEY...'=                  |\n** Groovy Common Errors/Exceptions\n| Name               | Comment                                    |\n|--------------------+--------------------------------------------|\n| Illegal class name | [[https://stackoverflow.com/questions/22839352/jenkins-groovy-post-build-script-to-evaluate-file-with-function][JVM doesn't like class names with a hyphen]] |\n\n** Groovy Basic\n| Name                           | Comment                                                   |\n|--------------------------------+-----------------------------------------------------------|\n| Get environment variables      | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/get-env.groovy][get-env.groovy]], =println env.WORKSPACE=                   |\n| Groovy execute command         | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/execute-command.groovy][execute-command.groovy]]                                    |\n| [[https://stackoverflow.com/questions/2060427/groovy-grails-how-to-determine-a-data-type][Get data type of a variable]]    | =myObject.getClass()=                                     |\n| Print stdout                   | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/print.groovy][print.groovy]] echo 'Action is done', println \"Hello World\" |\n| Use boolean parameter          | if (istrue == \"false\") {...}                              |\n| Basic integer caculation       | def a = 3, b = 7; println \"$a + $b = ${a + b}\"            |\n| Run groovy online              | [[https://groovyconsole.appspot.com][SaaS: Groovy Web console]]                                  |\n| Run groovy script from Jenkins | [[https://wiki.jenkins.io/display/JENKINS/Jenkins+Script+Console][Link: Jenkins Script Console]]                              |\n| Reference                      | [[http://groovy-lang.org][Link: Apache Groovy]]                                       |\n#+BEGIN_HTML\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" width=\"185\" height=\"37\" src=\"https://raw.githubusercontent.com/dennyzhang/cheatsheet.dennyzhang.com/master/images/cheatsheet_dns.png\"></a>\n#+END_HTML\n** Groovy String\n| Name                           | Comment                                                        |\n|--------------------------------+----------------------------------------------------------------|\n| Check string startsWith        | =assert s.startsWith(\"\\t\")=                                    |\n| Trim whitespaces               | s=s.trim()                                                     |\n| Concat string                  | =first = 'Joe'; last = 'Smith'; println(\"Name: $first $last\")= |\n| [[http://groovy-lang.org/groovy-dev-kit.html#_list_literals][Convert list to string]]         | =l.join(\";\")=                                                  |\n| Create string with multi-lines | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/multi-line-string.groovy][multi-line-string.groovy]]                                       |\n| Convert string to list         | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/split-string.groovy][split-string.groovy]]                                            |\n| [[http://groovy-lang.org/json.html][Convert string to json]]         | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/string-to-json.groovy][string-to-json.groovy]]                                          |\n| Remove tags                    | =input.replaceAll(\"\\\\<.*?>\",\"\")=                               |\n| Regex match                    | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/regexp-match.groovy][regexp-match.groovy]]                                            |\n** Groovy Regexp\n| Name                   | Comment                        |\n|------------------------+--------------------------------|\n| [[https://www.ngdc.noaa.gov/wiki/index.php/Regular_Expressions_in_Groovy][Regex case insensitive]] | (item.name == ~/(?i).*NSX.*/ ) |\n| Reference              | [[https://www.ngdc.noaa.gov/wiki/index.php/Regular_Expressions_in_Groovy][Regular Expressions in Groovy]]  |\n** Groovy Array\n| Name                        | Comment                                  |\n|-----------------------------+------------------------------------------|\n| Iterate a list              | =for(item in [1,2,3,4]){ println item }= |\n| Iterate a list              | =(1..3).each { println \"Number ${it}\"}=  |\n| Add item to list            | =def alist = [10, 9, 8]; alist << 7=     |\n| List size                   | =def alist = [10, 9, 8]; alist.size()=   |\n| Split string with delimiter | ='1128-2'.tokenize('-')=                 |\n** Groovy File\n| Name                            | Comment                                                                 |\n|---------------------------------+-------------------------------------------------------------------------|\n| [[https://stackoverflow.com/questions/7729302/how-to-read-a-file-in-groovy-into-a-string][Read file into a string]]         | =String fileContents = new File('/tmp/test.txt).text=                   |\n| Read file content as a variable | =def env = System.getenv()=, =def content = readFile(\"/tmp/test.txt\")=  |\n| [[https://jenkins.io/doc/pipeline/examples/][Write file in pipeline]]          | writeFile file: \"output/my.txt\", text: \"This is a test\"                 |\n| [[https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#code-readproperties-code-read-properties-from-files-in-the-workspace-or-text][Read a property file]]            | def conf = readProperties file: \"${env.WORKSPACE}@script/my.properties\" |\n| Read and write json files       | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/json-file.groovy][json-file.groovy]]                                                        |\n| Obtain a relative path          | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/json-file.groovy][relative-path.groovy]]                                                    |\n** Groovy Shell Command\n| Name                        | Comment                                             |\n|-----------------------------+-----------------------------------------------------|\n| Run shell and get output    | def out = sh script: command, returnStdout: true    |\n| Run shell and get exit code | def status = sh script: command, returnStatus: true |\n** Groovy Dictionary\n| Name                | Comment                                        |\n|---------------------+------------------------------------------------|\n| Create a map        | =def m = ['fruit':'Apple', 'veggie':'Carrot']= |\n| Add an item to map  | =m.put('denny','hello')=                       |\n| Check if key exists | =m.containsKey('key1')=                        |\n| Loop a map          | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/loop-map.groovy][loop-map.groovy]]                                |\n** Groovy json\n| Name                       | Comment               |\n|----------------------------+-----------------------|\n| [[http://groovy-lang.org/json.html][Convert string to json]]     | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/string-to-json.groovy][string-to-json.groovy]] |\n| Convert dictionary to json | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/dict-to-json.groovy][dict-to-json.groovy]]   |\n| Read and write json files  | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/json-file.groovy][json-file.groovy]]      |\n#+BEGIN_HTML\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" width=\"185\" height=\"37\" src=\"https://raw.githubusercontent.com/dennyzhang/cheatsheet.dennyzhang.com/master/images/cheatsheet_dns.png\"></a>\n#+END_HTML\n** Groovy Date\n| Name           | Comment                                                                      |\n|----------------+------------------------------------------------------------------------------|\n| Date to string | =new Date().format(\"yyyy-MM-dd'T'HH:mm:ss'Z'\", TimeZone.getTimeZone(\"UTC\"))= |\n| String to date | =Date.parse(\"yyyy-MM-dd'T'HH:mm:ss'Z'\", \"2001-01-01T00:00:00Z\")=             |\n| String to date | =Date.parse(\"yyyy-MM-dd'T'HH:mm:ssZ\", \"2001-01-01T00:00:00+0000\")=           |\n** Jenkins Agent\n| Name                                | Comment                        |\n|-------------------------------------+--------------------------------|\n| Check jenkins slave jar version     | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/check-slave-jar-version.groovy][check-slave-jar-version.groovy]] |\n| Find dead executors and remove them | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/find-dead-executors.groovy][find-dead-executors.groovy]]     |\n| Set env for each agent              | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/set-agent-env.groovy][set-agent-env.groovy]]           |\n** Jenkins Maintenance\n| Name                            | Comment                                                 |\n|---------------------------------+---------------------------------------------------------|\n| Delete jenkins job by regexp    | [[https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4/blob/master/delete-job-by-regexp.groovy][delete-job-by-regexp.groovy]]                             |\n| Deploy Jenkins via docker       | https://hub.docker.com/r/jenkins/jenkins/               |\n| Clean up old builds             | [[https://support.cloudbees.com/hc/en-us/articles/215549798-Best-Strategy-for-Disk-Space-Management-Clean-Up-Old-Builds?mobile_site=true][Link: CloudBees Best Strategy for Disk Space Management]] |\n** More Resources\nhttp://groovy-lang.org/documentation.html#gettingstarted\n\nhttps://github.com/fabric8io/jenkins-docker\n\nLicense: Code is licensed under [[https://www.dennyzhang.com/wp-content/mit_license.txt][MIT License]].\n#+BEGIN_HTML\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" width=\"201\" height=\"268\" src=\"https://raw.githubusercontent.com/USDevOps/mywechat-slack-group/master/images/denny_201706.png\"></a>\n<a href=\"https://cheatsheet.dennyzhang.com\"><img align=\"right\" src=\"https://raw.githubusercontent.com/dennyzhang/cheatsheet.dennyzhang.com/master/images/cheatsheet_dns.png\"></a>\n\n<a href=\"https://www.linkedin.com/in/dennyzhang001\"><img align=\"bottom\" src=\"https://www.dennyzhang.com/wp-content/uploads/sns/linkedin.png\" alt=\"linkedin\" /></a>\n<a href=\"https://github.com/dennyzhang\"><img align=\"bottom\"src=\"https://www.dennyzhang.com/wp-content/uploads/sns/github.png\" alt=\"github\" /></a>\n<a href=\"https://www.dennyzhang.com/slack\" target=\"_blank\" rel=\"nofollow\"><img align=\"bottom\" src=\"https://www.dennyzhang.com/wp-content/uploads/sns/slack.png\" alt=\"slack\"/></a>\n#+END_HTML\n* org-mode configuration                                           :noexport:\n#+STARTUP: overview customtime noalign logdone showall\n#+DESCRIPTION:\n#+KEYWORDS:\n#+LATEX_HEADER: \\usepackage[margin=0.6in]{geometry}\n#+LaTeX_CLASS_OPTIONS: [8pt]\n#+LATEX_HEADER: \\usepackage[english]{babel}\n#+LATEX_HEADER: \\usepackage{lastpage}\n#+LATEX_HEADER: \\usepackage{fancyhdr}\n#+LATEX_HEADER: \\pagestyle{fancy}\n#+LATEX_HEADER: \\fancyhf{}\n#+LATEX_HEADER: \\rhead{Updated: \\today}\n#+LATEX_HEADER: \\rfoot{\\thepage\\ of \\pageref{LastPage}}\n#+LATEX_HEADER: \\lfoot{\\href{https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4}{GitHub: https://github.com/dennyzhang/cheatsheet-jenkins-groovy-A4}}\n#+LATEX_HEADER: \\lhead{\\href{https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-A4}{Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-A4}}\n#+AUTHOR: Denny Zhang\n#+EMAIL:  denny@dennyzhang.com\n#+TAGS: noexport(n)\n#+PRIORITIES: A D C\n#+OPTIONS:   H:3 num:t toc:nil \\n:nil @:t ::t |:t ^:t -:t f:t *:t <:t\n#+OPTIONS:   TeX:t LaTeX:nil skip:nil d:nil todo:t pri:nil tags:not-in-toc\n#+EXPORT_EXCLUDE_TAGS: exclude noexport\n#+SEQ_TODO: TODO HALF ASSIGN | DONE BYPASS DELEGATE CANCELED DEFERRED\n#+LINK_UP:\n#+LINK_HOME:\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* TODO groovy challenges                                           :noexport:\n** 101\nUse groovy to add a test user in Jenkins\nFor better security, use groovy to only allow registered user login\nQuiz:\n\nOnce I have enabled Jenkins security, how my chef update will work?\n** 102\nDefine a Jenkins pipeline job automatically\nDefine a Jenkins job via Jenkinsfile script automatically\nFor automated backup, enable and configure ThinBackup plugin via Groovy\n** 301\nDefine a dummy Jenkins pipeline job using Jenkinsfile\nDefine a Jenkins parameterized pipeline job using Jenkinsfile. It shall trigger another job.\nQuiz:\n\nOnce I have enabled Jenkins security, how my chef update will work?\n* TODO [#A] Blog: Jenkins pipeline: run multiple related jobs in a managed order :noexport:IMPORTANT:\n** basic use\nJenkins Pipeline is a suite of plugins which supports implementing and\nintegrating continuous delivery pipelines into Jenkins.\n** TODO jenkins pipeline show slack error message\n** TODO why unecessary delay when running jobs via pipeline: http://injenkins.carol.ai:48080/view/Pipeline/job/PipelineMonitor/\n** TODO Why pipeline scheduling takes serveral minutes\n** TODO [#A] How to support testing different branch with scm: http://jenkins.shibgeek.com:48084/view/Pipeline/job/PipelineCodeCheck/\n** TODO [#A] Jenkins pipeline doesn't set who initiate the deployment\njenkins APP [11:32 AM]\nRefreshDemoEnvAll - #7 Started by upstream project \"PipelineRefreshDemoEnvAll\" build number 3 (Open)\n** TODO [#A] kill in jenkins job doesn't stop the bash: curl\n root@bematech-do-es-2:~/elasticsearch-cli-tool# curl \"http://${es_ip}:9200/_alias/staging-8a18aa800e5911e785f24a8136534b63\"\n {\"staging-index-8a18aa800e5911e785f24a8136534b63-new3\":{\"aliases\":{\"staging-8a18aa800e5911e785f24a8136534b63\":{}}}}root@bematech-do-es-2:~/elasticsearch-cli-tool# curl \"http://${es_ip}:9200/_alias/staging-8a18aa800e5911e785f24a8136534b63\"\n {\"staging-index-8a18aa800e5911e785f24a8136534b63-new3\":{\"aliases\":{\"staging-8a18aa800e5911e785f24a8136534b63\":{}}}}root@bematech-do-es-2:~/elasticsearch-cli-tool# ps -ef | grep curl\n root     11085 11062  0 22:51 ?        00:00:00 curl -XPOST http://138.68.246.50:9200/_reindex?pretty -d       {        \"conflicts\": \"proceed\",        \"source\": {        \"index\": \"master-index-8a18aa800e5911e785f24a8136534b63-new2\",        \"size\": \"500\"     },        \"dest\": {        \"index\": \"master-index-8a18aa800e5911e785f24a8136534b63-new3\",        \"op_type\": \"create\"     }  }\n root     11109  9468  0 22:51 pts/2    00:00:00 grep --color=auto curl\n root     13367 13348  0 13:05 ?        00:00:04 curl -XPOST http://138.68.246.50:9200/_reindex?pretty -d       {        \"conflicts\": \"proceed\",        \"source\": {        \"index\": \"master-index-321bb9606b2111e7b579a2f42be00f79-new2\",        \"size\": \"500\"     },        \"dest\": {        \"index\": \"master-index-321bb9606b2111e7b579a2f42be00f79-new3\",        \"op_type\": \"create\"     }  }\n root@bematech-do-es-2:~/elasticsearch-cli-tool# date\n** #  --8<-------------------------- separator ------------------------>8-- :noexport:\n** TODO [#A] Jenkinsfile/Pipeline                                 :IMPORTANT:\n https://jenkins.io/doc/book/pipeline/jenkinsfile/\n\n Pipeline supports two syntaxes, Declarative (introduced in Pipeline 2.5) and Scripted Pipeline\n\n https://jenkins.io/pipeline/getting-started-pipelines/\n\n https://plugins.jenkins.io/workflow-aggregator\n\n https://github.com/jenkinsci/pipeline-examples/tree/master/jenkinsfile-examples/nodejs-build-test-deploy-docker-notify\n*** Pipeline Vocabulary: Steps, Nodes, and Stages\n https://dzone.com/articles/jenkins-pipeline-plugin-tutorial\n - A step, also known as a \"build step\", is a single task that we want Jenkins to execute.\n\n - A \"node\", within the contexts of a pipeline, refers to a step that does two things.\n\n   First, it schedules the defined steps so that it'll run as soon as\n   an executor is available. Second, it creates a temporary workspace\n   which is removed once all steps have completed.\n\n - And lastly, we have \"Stages\". Stages are for setting up logical\n   divisions within pipelines. The Jenkins Pipeline visualization\n   plugin will display each stage as a separate segment. Because of\n   this, teams tend to name stages for each phase of the development\n   process, such as \"Dev, Test, Stage, and Production\".\n*** Jenkins pipeline is durable from Jenkins master restart\n https://dzone.com/articles/jenkins-pipeline-plugin-tutorial\n #+BEGIN_EXAMPLE\n - One huge benefit of using a pipeline is that the job itself is\n   durable. A Pipeline job is able to survive planned or even unplanned\n   restarts of the Jenkins master. If you need to survive slave\n   failures as well, you'll have to use checkpoints.\n\n - Unfortunately, the checkpoints plugin is only available for the\n   enterprise edition of Jenkins. Pipelines are also pausable.\n #+END_EXAMPLE\n*** hello world: http://localhost:18083/job/jenkinsfile1/1/console\n https://serversforhackers.com/c/covering-a-simpler-jenkinsfile\n https://jenkins.io/doc/book/pipeline/getting-started/\n** TODO Jenkins pipeline: Supporting APIs v2.10\n #+BEGIN_EXAMPLE\n INFO: Listed all plugins\n Nov 26, 2017 5:03:17 PM jenkins.InitReactorRunner$1 onTaskFailed\n SEVERE: Failed Loading plugin Pipeline: Nodes and Processes v2.8 (workflow-durable-task-step)\n java.io.IOException: Pipeline: Nodes and Processes v2.8 failed to load.\n  - Pipeline: Supporting APIs v2.10 is older than required. To fix, install v2.12 or later.\n\t at hudson.PluginWrapper.resolvePluginDependencies(PluginWrapper.java:626)\n\t at hudson.PluginManager$2$1$1.run(PluginManager.java:516)\n\t at org.jvnet.hudson.reactor.TaskGraphBuilder$TaskImpl.run(TaskGraphBuilder.java:169)\n\t at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:282)\n\t at jenkins.model.Jenkins$7.runTask(Jenkins.java:1090)\n\t at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:210)\n\t at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:117)\n\t at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\t at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\t at java.lang.Thread.run(Thread.java:748)\n #+END_EXAMPLE\n** TODO jenkins pipeline agent\n https://www.digitalocean.com/community/tutorials/how-to-set-up-continuous-integration-pipelines-in-jenkins-on-ubuntu-16-04\n\n The pipeline contains the entire definition that Jenkins will\n evaluate. Inside, we have an agent section that specifies where the\n actions in the pipeline will execute. To isolate our environments from\n the host system, we will be testing in Docker containers, specified by\n the docker agent.\n\n #+BEGIN_EXAMPLE\n #!/usr/bin/env groovy\n\n pipeline {\n\n     agent {\n         docker {\n             image 'node'\n             args '-u root'\n         }\n     }\n\n     stages {\n         stage('Build') {\n             steps {\n                 echo 'Building...'\n                 sh 'npm install'\n             }\n         }\n         stage('Test') {\n             steps {\n                 echo 'Testing...'\n                 sh 'npm test'\n             }\n         }\n     }\n }\n #+END_EXAMPLE\n** TODO Jenkins pipeline enable slack notificaiton\n** TODO [#A] jenkins workflow: https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow\nhttps://dzone.com/articles/top-10-best-practices-for-jenkins-pipeline\n** TODO jenkins plugins: git, checkstyle, build-pipeline-plugin, clone-workspace-scm, deploy, Text-finder\nhttps://github.com/ThoughtWorks-Chengdu-DevOps-Club/tw_devops_workshop/tree/master/season_1/workshop_2\n** TODO verify whether local docker image is up-to-date\n** TODO Why jenkins container use so much memory?\n** TODO jenkins docker demo: https://hub.docker.com/u/jenkinsci/\ndocker run --rm -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock --group-add=$(stat -c %g /var/run/docker.sock) jenkinsci/docker-workflow-demo\n** TODO jenkins plugin: job plugin\n根据前置job成功与否来执行当前job\n插件链接 https://wiki.jenkins-ci.org/display/JENKINS/Join+Plugin\n\nnice, 可以用于我们的CommonServerCheck的jenkins job依赖\n** TODO jenkins job priority\n** TODO jenkins plugin: HTML Publisher Plugin\nhttps://wiki.jenkins-ci.org/display/JENKINS/HTML+Publisher+Plugin\nhttps://wiki.jenkins-ci.org/display/JENKINS/DocLinks+Plugin\n** #  --8<-------------------------- separator ------------------------>8--\n** TODO [#A] jenkins get overview of scheduled jenkins jobs        :IMPORTANT:\n** TODO Jenkins Warnings plugin: http://dustinrcollins.com/detecting-chef-upload-failures-with-jenkins\n** TODO Jenkins Dependency-Check Plugin: https://wiki.jenkins-ci.org/display/JENKINS/OWASP+Dependency-Check+Plugin\n** TODO jenkins restrict user running jobs on prod env\nhttp://stackoverflow.com/questions/30397699/how-to-use-a-different-set-of-parameters-for-release-builds-in-jobs-triggered-vi\n** TODO Jenkins job: stop/start container\ndocker pull sandbox image\n** TODO Jenkins ssh key security: SSH Credentials Plugin; SSH Agent Plugin\nhttps://wiki.jenkins-ci.org/display/JENKINS/SSH+Agent+Plugin\nhttps://wiki.jenkins-ci.org/display/JENKINS/SSH+Credentials+Plugin\n** TODO jenkins setting: only registered user can trigger, only admin can configure\n** TODO [#A] Jenkinse use a cluster for testing; jenkins slave     :IMPORTANT:\nhttp://blog.dataman-inc.com/20150623-jenkins-apache-mesos-marathon/\nhttp://blog.alexellis.io/jenkins-2-0-first-impressions/\nhttps://www.huangyunkun.com/2015/08/29/docker-with-jenkins/\n** [#A] jenkins change enrinvonment variables for post-actions\nhttp://stackoverflow.com/questions/23995648/jenkins-execute-shell-script-vars-needed-in-post-build-action-specifically-in\nhttps://issues.jenkins-ci.org/browse/JENKINS-25355\n** TODO [#A] jenkins docker plugin                                 :IMPORTANT:\n** TODO [#A] QA jenkins job doesn't destroy the VMs\n\nImagesNetworkingMonitoringAPISupport\nC\n\ndenny.zhang\ndenny.zhang@totvs.com\nC\nCarol\nSettings\nNotifications2\nLogout\nCreate\nkitchen-cluster-mdm-qa-4nodes-node4 4 GB Memory / 60 GB Disk / SFO2 - Ubuntu 14.04.5 x64\nipv4: 165.227.0.213 Copy ipv6:  Enable now Private IP:  Enable now Floating IP:  Enable now Console:\nGraphs\nAccess\nPower\nVolumes\nResize\nNetworking\nBackups\nSnapshots\nKernel\nHistory\nDestroy\nTags\n** TODO jenkins slave\nU can attach ur nodes as a slaves to master Jenkins or if u want to to run a command from an endpoint, u can use pac software\n** TODO Jenkins Blueocean\n** TODO jenkins cancel job doesn't stop db backup\n** TODO [#A] jenkins cancel job doesn't force-merge command        :IMPORTANT:\nroot@bematech-do-es-01:/var/log/elasticsearch# ps -ef | grep el\nroot        90     2  0 Aug11 ?        00:00:00 [khelper]\nroot      8097  8096  0 13:50 ?        00:00:00 python /opt/devops/bin/elasticsearch_force_merge.py --es_pattern_regexp staging-index-abae8b30ac9b11e692000401f8d88101-new3 --min_deleted_count 100000 --min_deleted_ratio 0\nroot     13315 13314  0 20:47 ?        00:00:00 python /opt/devops/bin/elasticsearch_force_merge.py --es_pattern_regexp staging-index-abae8b30ac9b11e692000401f8d88101-new3 --min_deleted_count 100000 --min_deleted_ratio 0\nroot     20846  1844  0 22:49 pts/1    00:00:00 grep --color=auto el\nelastic+ 31034     1 99 Aug11 ?        36-14:05:03 /usr/lib/jvm/java-8-oracle-amd64/bin/java -Xms12288m -Xmx12288m -Djava.awt.headless=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Djna.nosys=true -server -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Xms12288m -Xmx12288m -Xss256k -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Djna.nosys=true -Des.path.home=/usr/share/elasticsearch -cp /usr/share/elasticsearch/lib/elasticsearch-2.3.3.jar:/usr/share/elasticsearch/lib/* org.elasticsearch.bootstrap.Elasticsearch start -d -p /var/run/elasticsearch/elasticsearch.pid --default.path.home=/usr/share/elasticsearch --default.path.logs=/var/log/elasticsearch --default.path.data=/usr/share/elasticsearch --default.path.conf=/etc/elasticsearch\n** TODO jenkins multi-stage build\n** TODO jenkins multiple configuration\n** TODO jenkins syntax generator\nthat means, constantly having to look up on plugin docs for pipeline steps\n\n\n4 replies\nPuneeth [41 minutes ago]\nUse the pipeline syntax generator in your Jenkins installation\n\n\namrit [40 minutes ago]\nYea thats what I started using now :slightly_smiling_face: . Do people still use those?\n\n\namrit [< 1 minute ago]\n@Denny Zhang (Github . Blogger) this can be handy for those situations\n\n\nDenny Zhang (Github . Blogger) [< 1 minute ago]\nthanks. I haven't used it. Will give it a try\n** TODO How to force jenkins to reload a jenkinsfile?\n** TODO Blog: Jenkins pipeline: reconfigure jenkins job and reload it\nhttps://stackoverflow.com/questions/44422691/how-to-force-jenkins-to-reload-a-jenkinsfile\nhttps://issues.jenkins-ci.org/browse/JENKINS-32984\nhttps://issues.jenkins-ci.org/browse/JENKINS-33734\nQuestion: How to use jenkins pipeline to reconfigure parameters of another jenkins job.\n\n(Ideally I wish I could avoid reloading or restarting jenkins)\n\nI remember this channel has similar discussion about this. Anyone remember the suggestion?\n*** TODO Jenkins pipeline: Get current setting and add a new attribute\n** TODO try Jenkins X\n** TODO create a jenkins job to update markdown wiki\n** TODO Why jenkins are up and running, after machine reboot. But couchbase, es are not\ndocker exec -it mdm-jenkins service jenkins status\ndocker exec -it mdm-all-in-one bash\n\nservice couchbase-server start && service elasticsearch start\n\nservice couchbase-server status && service elasticsearch status\n\nservice mdm start\n\nservice couchbase-server status && service elasticsearch status && service mdm status\n** TODO Lessons learned: run one jenkins backup\n** TODO jenkins load bundle\n** HALF jenkins pipeline get job configuration\nhttps://support.cloudbees.com/hc/en-us/articles/218353308-How-to-update-job-config-files-using-the-REST-API-and-cURL-\n\ndennyzhang\nlrpChangeMe1\n\ncurl -X GET http://dennyzhang:lrpChangeMe1@myjenkins:18080/job/dennytestRehearsal/config.xml -o mylocalconfig.xml\n\ncurl -X POST http://dennyzhang:lrpChangeMe1@myjenkins:18080/job/dennytestRehearsal/config.xml --data-binary \"@mymodifiedlocalconfig.xml\"\n** TODO why has_error variable hasn't passed: http://myjenkins:18080/job/CheckDNSPropagation/14/console\n** TODO jenkins docker image: why /var/jenkins_home/.bashrc folder is missing?\n** TODO Use groovy to add a user\n** TODO Use groovy to only allow register users use Jenkins\n** TODO Use groovy script to restart jenkins\n** TODO Use groovy to install a jenkins plugin\n** #  --8<-------------------------- separator ------------------------>8-- :noexport:\n** TODO jenkins pipeline job: add node\n*** original one\nnode {\n     // TODO: validate users input\n     def ip_list = [];\n     def ip_port_list = [];\n     def ssh_port = '2702'\n     for (entry in ip_hostname_list.split(\"\\n\")) {\n         entry = entry.trim()\n         ip_address = entry.split(\" \")[0]\n         ip_address = ip_address.trim()\n         ip_list.add(ip_address)\n         ip_port_list.add(ip_address + \":\" + ssh_port)\n     }\n\n    stage('UpdateHAProxy') {\n       build job: 'FixHostsFileBinding', parameters: [text(name: 'server_list', value: 'https://prodmgmt.carol.ai/querycluster/haproxy'), text(name: 'add_hosts', value: ip_hostname_list)]\n       build job: 'UpdateHAProxyNodeListDOBematech'\n       build job: 'CheckIPAddressInList',  parameters: [text(name: 'new_ip_list', value: ip_list.join(\"\\n\"))]\n    }\n\n    stage('FixConf') {\n        parallel firstBranch: {\n            def target_host_file='/tmp/hosts_target'\n            retry(2) {\n              build job: 'GetHostFileBinding',  parameters: [string(name: 'target_host_file', value: target_host_file)]\n            }\n            // update hosts file for existing nodes\n            build job: 'FixHostsFileBinding', parameters: [text(name: 'add_hosts', value: ip_hostname_list)]\n            // update hosts file for new nodes\n            def host_binding_content=readFile(target_host_file)\n            build job: 'FixHostsFileBinding', parameters: [text(name: 'server_list', value: ip_port_list.join(\"\\n\")), text(name: 'add_hosts', value: host_binding_content)]\n            retry(2) {\n                build 'FixHostsFileTemplateBematechDO'\n            }\n        }, secondBranch: {\n            build job: 'UFWAddNodesBematechDO', parameters: [text(name: 'new_ip_list', value: ip_list.join(\"\\n\"))]\n            retry(2) {\n                build 'FixESYamlBematechDO'\n            }\n            retry(2) {\n                build 'FixMDMYamlBematechDO'\n            }\n        },\n        failFast: false\n    }\n\n    stage('Rehearsal') {\n        if (skip_deployment_rehearsal == \"false\") {\n           build job: 'DeploySystemRehearsalDOBematech', parameters: [text(name: 'server_list', value: ip_port_list.join(\"\\n\"))]\n        }\n    }\n}\n** TODO pipeline best practice\nhttps://github.com/jenkinsci/pipeline-examples/blob/master/docs/BEST_PRACTICES.md\n** TODO Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject\n** HALF groovy load a json file\nhttp://groovy-lang.org/json.html\nhttps://stackoverflow.com/questions/26230225/hashmap-getting-first-key-value\n/usr/local/scripts/terraform_jenkins_digitalocean/bematech-do-es-39/terraform.tfstate\n** HALF groovy send http request\nhttps://stackoverflow.com/questions/25692515/groovy-built-in-rest-http-client\n** TODO jenkins monitor\nDenny Zhang [4:47 PM]\nNice, any screenshots? (Ignore, if it's against the policy)\n\n\nStefan Jansson\n[4:49 PM]\nthe jenkins-plugin is called build monitor plugin: https://wiki.jenkins.io/display/JENKINS/Build+Monitor+Plugin\n\n\n[4:50]\na competitor is radiator: https://wiki.jenkins.io/display/JENKINS/Radiator+View+Plugin\n- i'd use radiator once getting over a certain amount of jobs to monitor, since it has an option to only display failing jobs\n\n\n[4:54]\nYou could even call it \"continuous testing in production\" to make it an even stronger trend buzzword... \"continuous testing\" and \"testing in production\" are buzzwords that traditional testers do shrug from, but something I believe strongly in for the future, for devops teams, and teams running a continuous delivery process, and bigger organisations where you depend on other teams/products\n\n\nDenny Zhang [4:54 PM]\nYes, we have Jenkins monitor plugin enabled\n\n\n[4:55]\nDon't quite understand its value though\n\n\nStefan Jansson [4:57 PM]\nwhat is it that you don't understand?\n\n\nDenny Zhang\n[4:57 PM]\nIt gives me an overview. But what I can get from it?\n\n\nnew messages\nStefan Jansson [5:05 PM]\nmy example works like an extra layer of monitoring, to discover even faster if you got a problem in production, if your data-logging, alarms etc might not be as fast with, or as obvious.. it won't even catch everything, that a test can.\n\nfor example, my teams builds a booking-flow for the nordics biggest travel-company.. if you cannot book a seat on a plane, simply because an API somewhere doesn't respond, or are having slow timeouts so it doesn't even display the option for the customer... the error-code monitoring and larms might go up, but it takes a while until the larms sets off, or that the error count get's to a suspicious amount so that you take a look at it.. but the TEST that runs making a booking, will fail immidiatly and give you a RED-flag on the monitor\n** TODO Jenkins SCM Sync configuration plugin\n*** SCM Sync configuration plugin\nhttps://wiki.jenkins.io/display/JENKINS/SCM+Sync+configuration+plugin\n*** jenkinsfile: groovy script\n*** Manage Jenkins Jobs with YAML\nhttps://blogs.rdoproject.org/6006/manage-jenkins-jobs-with-yaml\n** TODO configure pipeline status in a better way\n** TODO jenkins pipeline: can't abort it\n** TODO Jenkins group stage: 5 groups\nRomain B. [12:21 AM]\n@Denny Zhang (Github . Blogger): You should regroup your tests in less stages, you can still get a \"test overview\" in the `test result` webpage (append `testReport/` to your job)\nAlso, give BlueOcean a try, it doesn't do everything well but its pretty usefull to output pipeline status (especially to spot an error)\n\nDario Tranchitella [1:25 AM]\nSome used Dependency Injection (with Inversion of Control) and Singleton patterns using Groovy shared library?\nI noticed that documentation is really poor and I'm facing some scalability issues with a complex pipelines...\n\nDenny Zhang (Github . Blogger) [8:07 AM]\n@romainrbr, let me give it a try\n** TODO Jenkins Features Controlled with System Properties: https://wiki.jenkins-ci.org/display/JENKINS/Features+controlled+by+system+properties\n** TODO SCM Sync Configuration Plugin: http://www.scmtechblog.net/2014/12/14-must-have-jenkins-plugins-to.html\n** TODO Explore env Jenkins update issue: updatejenkinsitself\ncd /var/chef/cache/\n\njava -jar ./jenkins-cli.jar -s http://localhost:18080/ login --username chefadmin --password \"TOTVS123FD\"\njava -jar ./jenkins-cli.jar -s http://localhost:18080/ list-jobs\n** TODO ip list as an inventory file provided by jenkins\n** TODO Use Jenkins ssh plugin: http://davidsj.co.uk/blog/how-i-update-my-blog-with-jenkins/\n** TODO jenkins powershell\nseanturner83 [5:17 AM]\n@dennyzhang you like powershell? https://github.com/poshbotio/PoshBot\nGitHub\nposhbotio/PoshBot\nPoshBot - Powershell-based bot framework\n** TODO improve bematech jenkins security: about tcp ports\n** TODO [#A] secure sonarqube port forwarding jenkins\n** TODO [#A] jenkins pipeline fail to be aborted\n** TODO jenkins pipeline specify git credential\n** TODO Blog: jenkins pipeline back to normal notification\n** TODO [#A] Blog: jenkins piepline update job parameter\n** TODO [#A] jenkins pipeline job to update existing job\n** TODO jenkins create admin user from configure\n** TODO [#A] How to keep jenkins in sync for two directions?       :IMPORTANT:\n** TODO whenever I configure jenkins, it will crash\n** TODO Candy Jenkins: https://github.com/david7482/caddy-jenkins-docker\nhttps://caddyserver.com/\n#+BEGIN_EXAMPLE\nAlso, the demo Jenkins you guys are running on docker?\n\n\n3 replies\nDenny Zhang (Github . Blogger) [3 minutes ago]\nJenkins is running on docker. Via AWS ECS (edited)\n\n\nAnmolNagpal [1 minute ago]\nOke I have a suggestion try caddy with it  it's really nice and Jenkins will run on https\n\n\nDenny Zhang (Github . Blogger) [< 1 minute ago]\nThis one?https://github.com/david7482/caddy-jenkins-docker\nGitHub\ndavid7482/caddy-jenkins-docker\ncaddy-jenkins-docker - Host Jenkins with Caddy as https proxy in Docker\n#+END_EXAMPLE\n** TODO jenkins SCM Sync configuration plugin\nhttps://wiki.jenkins.io/display/JENKINS/SCM+Sync+configuration+plugin\n** TODO [#A] Automatically generating Jenkins jobs\nhttps://www.slalom.com/thinking/automatically-generating-jenkins-jobs\n*** Jenkins Job Builder\nJenkins Job Builder is a command-line utility that will create Jenkins jobs based upon YAML configurations.\n** TODO advanced jenkins customization\nHide port: Change http://XXX.XXX.XXX.XXX:8080 to http://XXX.XXX.XXX.XXX:18080\nThe whole process takes more than 10 minutes, I only acccept 5 minutes\nCreate a dedicated policy\nCustomize EC2 profile\nCreate Tags to manage the stack\nWhen container restart/recreate, Jenkins configuration won't be lost\n** TODO Blog: how to avoid Jenkins SPOF\n#+BEGIN_EXAMPLE\nDenny Zhang (Github . Blogger) [10:43 AM]\nLet's say above 2 Jenkins instances serve the service.\n\nAs we know Jenkins have local $JENKINS_HOME folder.\n\nSo how these 2 instances work together to serve HA?\n\nAny thoughts?\n@Pradipta Dash @Stefan Jansson (QA in Continuous Delivery) @Jonathan.McAllister @Keef Baker\n\n\nJonathan McAllister [10:43 AM]\njoined #jenkins by invitation from Denny Zhang (Github . Blogger).\n\n\nPhilip Schwartz [11:20 AM]\n@Denny Zhang (Github . Blogger) are those suppose to be 2 jenkins masters running in ecs with a load balancer infront of them?\n\n\nDenny Zhang (Github . Blogger)\n[11:20 AM]\nyes\n\n\nPhilip Schwartz [11:20 AM]\nJenkins doesn't work that way. You can't drop a load balance infront of masters as they don't cross communicate\n\n\n[11:22]\nIf they are cloudbees instances you can use the HA plugin to allow promotion on single master failure. But it is still not the same and requires  shared file systems between them\n\n\nDenny Zhang (Github . Blogger) [11:22 AM]\nHow we can avoid Jenkins SPOF, Philip?\n\n\nnew messages\nPhilip Schwartz [11:23 AM]\nWith jenkins OSS there is no way\n#+END_EXAMPLE\n*** TODO Jenkins HA\n#+BEGIN_EXAMPLE\nPuneeth [12:48 PM]\n@Denny Zhang (Github . Blogger)  jenkins master HA is essentially jenkins master in an asg with efs volume for jenkins home\n\n\n[12:49]\n@Denny Zhang (Github . Blogger) there is a white paper from aws on jenkins HA\n\n\n[12:49]\njenkins slaves ha is again via asg and spot fleet\n\n\n[12:49]\nat least that's our approach\n\n\nPuneeth [12:54 PM]\n@Denny Zhang (Github . Blogger) there can only be one master unless unless unless you move the main job queues from the jenkins master. and use an external job queue :) In this case there can be multi master jenkins confg spread across many regions or within the same region. this is a super advanced approach. this approach is used by openstack . we used it too in our previous company\n\n\n[12:56]\nhttps://wiki.jenkins.io/plugins/servlet/mobile?contentId=66846870#content/view/66846870\n#+END_EXAMPLE\n**** TODO Jenkins: https://jenkins.io/blog/2016/06/10/save-costs-with-ec2-spot-fleet/\n**** TODO Jenkins Plugin: https://wiki.jenkins.io/display/JENKINS/Gearman+Plugin\n**** TODO [#A] Jenkins HA: https://jenkins.io/doc/book/architecting-for-scale/\n** TODO Why jenkins create user doesn't seem to work?\nhttps://github.com/chef-cookbooks/jenkins/blob/master/test/fixtures/cookbooks/jenkins_credentials/recipes/create.rb\n** TODO [#A] Blog: How chef keep as login user, even if jenkins restart\n** TODO jenkins warning: Email notifications could be sent to people who are not users of Jenkins\n#+BEGIN_EXAMPLE\nWarnings have been published for the following currently installed components:\nMailer Plugin 1.18:\nEmail notifications could be sent to people who are not users of Jenkins\n#+END_EXAMPLE\n** TODO 4 Jenkins warning\n#+BEGIN_EXAMPLE\nYou have data stored in an older format and/or unreadable data.\nManage\nDismiss\nDisable CLI over Remoting\nDismiss\nAllowing Jenkins CLI to work in -remoting mode is considered dangerous and usually unnecessary. You are advised to disable this mode. Please refer to the CLI documentation for details.\nWarnings have been published for the following currently installed components:\nMailer Plugin 1.18:\nEmail notifications could be sent to people who are not users of Jenkins\nGo to plugin manager\nConfigure which of these warnings are shown\nExamine\nDismiss\nAgent to master security subsystem is currently off. Please read the documentation and consider turning it on\n#+END_EXAMPLE\n** TODO [#A] jenkins Build Pipeline plugin                         :IMPORTANT:\nhttps://jenkins.io/doc/pipeline/\nhttps://dzone.com/articles/top-10-best-practices-for-jenkins-pipeline\nhttps://github.com/ThoughtWorks-Chengdu-DevOps-Club/tw_devops_workshop/tree/master/season_1/workshop_2\nhttps://jenkins.io/blog/2017/02/01/pipeline-scalability-best-practice/\n** TODO Pipeline as Code with Jenkins\nhttps://jenkins.io/solutions/pipeline/\nhttps://www.cloudbees.com/blog/top-10-best-practices-jenkins-pipeline-plugin\n** TODO try jenkinsfile-solution: backup Jenkins configuration\nStefan Jansson [12:33 PM]\nFor sure. We'll see\n\n\n[12:33]\nYou feel your jenkins-backup solution works good for you?\n\n\nDenny Zhang [12:33 PM]\nNot very. But it's working\n\n\n[12:33]\nThinBackup is good. But it will introduce some problem\n\n\nStefan Jansson [12:35 PM]\nThe jenkinsfile-solution seems pretty damn nice. I havent gone deepnintonit yet though.\n\nYou basicly points out a github-repo and its jenkinsfile. And it configures your jenkinsjob from scatch.\n\n\n[12:35]\nSets up, and configures, if ive understoodnitncorrectlt\n\n\nDenny Zhang [12:35 PM]\nYeah, I've heard of this part.\n\nLet me give it a try.\n** TODO [#A] Use Jenkinsfile instead of the UI\nhttp://www.anniehedgie.com/jenkinsfile\nhttps://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ci_jenkins_sample_walkthrough.htm\n** TODO What's Jenkins JNLP worker?\n** TODO Jenkins plugin: Build Monitor Plugin71 - Visual view of your builds status\n** TODO Jenkins plugin: SSH Slaves64 - Manage workers through SSH\n** TODO Jenkins plugin: Nested View Plugin70 - Groups jobs into multiple levels instead of a single big list of tabs\n** TODO Jenkins plugin: Gearman\nhttps://wiki.jenkins.io/plugins/servlet/mobile?contentId=66846870#content/view/66846870\n\nhttps://plugins.jenkins.io/gearman-plugin\n\nJenkins core does not support multiple masters.\n** TODO git jenkins depths issue\nKen Godoy [1:38 PM]\nSee my first screenshot\n\n\nDenny Zhang (Github . Blogger) [1:38 PM]\nOh yes\n\nKen Godoy [1:38 PM]\nThe other options are to create a reference repo locally\nOr to just create a new repo as you mentioned.\n\nDenny Zhang (Github . Blogger) [1:39 PM]\nhmm, the depth of 1 should be recognized. That looks weird indeed\n\nKen Godoy [1:39 PM]\nBut creating a new repo I still need history for at least one year. I have automation that uses history to generate SQL script packages.\nI love Jenkins but sometimes it's a pain in the wazoo.\n\nDenny Zhang (Github . Blogger) [1:40 PM]\nNeed to deep dive into the git jenkins plugin\nLet me give it a try tonight as well.\n** TODO When we cancel jenkins backup job, the python script won't die\n** TODO try jenkins X: http://jenkins-x.io/\n*** TODO [#A] why we need jenkins x\n*** DONE jx help\n   CLOSED: [2018-04-23 Mon 15:46]\n➜  ~ jx help\n\n\nInstalling:\n  install              Install Jenkins X in the current Kubernetes cluster\n  uninstall            Uninstall the Jenkins X platform\n  upgrade              Upgrades a resource\n  create cluster       Create a new kubernetes cluster\n  create jenkins token Adds a new username and api token for a Jenkins server\n  init                 Init Jenkins X\n\nAdding Projects to Jenkins X:\n  import               Imports a local project or git repository into Jenkins\n  create archetype     Create a new app from a Maven Archetype and import the generated code into git and Jenkins for CI/CD\n  create spring        Create a new spring boot application and import the generated code into git and Jenkins for CI/CD\n  create lile          Create a new lile based application and import the generated code into git and Jenkins for CI/CD\n  create micro         Create a new micro based application and import the generated code into git and Jenkins for CI/CD\n  create quickstart    Create a new app from a Quickstart and import the generated code into git and Jenkins for CI/CD\n\nAddons:\n  create addon         Creates an addon\n  environment          View or change the current environment in the current kubernetes cluster\n  namespace            View or change the current namespace context in the current kubernetes cluster\n  prompt               Generate the command line prompt for the current team and environment\n  shell                Create a sub shell so that changes to the kubernetes context, namespace or environment remain local to the shell\n  status               status of the Kubernetes cluster or named node\n\nWorking with Applications:\n  console              Opens the Jenkins console\n  cdx                  Opens the CDX dashboard for visualising CI/CD and your environments\n  logs                 Tails the log of the latest pod for a deployment\n  open                 Open a service in a browser\n  rsh                  Opens a terminal in a pod or runs a command in the pod\n\nWorking with Environments:\n  preview              Creates or updates a Preview Environment for the current version of an application\n  promote              Promotes a version of an application to an environment\n  create environment   Create a new Environment which is used to promote your Team's Applications via Continuous Delivery\n  delete environment   Deletes one or more environments\n  edit environment     Edits an Environment which is used to promote your Team's Applications via Continuous Delivery\n  get environments     Display one or many Environments\n\nWorking with Jenkins X resources:\n  get                  Display one or many resources\n  edit                 Edit a resource\n  create               Create a new resource\n  delete               Deletes one or many resources\n  start                Starts a process such as a pipeline\n\nJenkins X Pipeline Commands:\n  step                 pipeline steps\n\nOther Commands:\n  help                 Help about any command\n  version              Print the version information\nUsage:\n  jx [flags] [options]\nUse \"jx <command> --help\" for more information about a given command.\n*** TODO easy how-to\ngithub token: jenkins-x\n\nfe67390d1be344bb48b6a4d524d9ebfa167030af\n** TODO Github oauth on jenkins servers\n** TODO [#A] avoid wrong input parameter issues\n#+BEGIN_EXAMPLE\nDenny Zhang (DevOps) [10:08 PM]\nThat's something I have done this morning.\n\nSince we haven't update any other parts. Only the list is incorrect, so the impact is not big.\n\nThus I didn't mention that in the slack. But that's wrong indeed.\n\nRobson Poffo [10:09 PM]\nyes, it was low impact\nSandro got something wrong on some reportings\nand he asked me that\n:slightly_smiling_face:\nall good\n\n\nDenny Zhang (DevOps) [10:09 PM]\nInputing wrong parameters happens sometimes. But it could be very dangerous.\n\nI definitely need to think how to prevent this misconfigure issue!\nI have made a note. Will think more, and discuss with Carlos and Kung\n#+END_EXAMPLE\n** TODO when jenkins jobs take too long, abort it and send out alerts\n** TODO How to add jenkins slave nodes in jenkins master server using Chef cookbook\n https://stackoverflow.com/questions/32219134/how-to-add-jenkins-slave-nodes-in-jenkins-master-server-using-chef-cookbook\n** TODO Use a jenkins job to reconfigure the same chef_json for 3 jobs: DeploySystemDOBematech, DeploySystemRehearsalDOBematech, UpdateHAProxyNodeListDOBematech\n** HALF copy json folder across nodes: http://myjenkins:18080/job/CopyFolderFromNode1ToNode2/\n > copy_folder_node1_to_node2.sh && vim copy_folder_node1_to_node2.sh\n\n bash -ex copy_folder_node1_to_node2.sh \"138.197.206.101\" \"/data/staging/\" \"165.227.52.135\" \"/tmp/staging\"\n** HALF [#A] doc: why vm shutdown has failed: http://myjenkins:18080/job/RunCommandOnServers/187/\n** TODO [#A] problem: Fail to shutdown couchbase nodes: http://myjenkins:18080/job/RunCommandOnServers/181/console\nhttps://issues.couchbase.com/browse/MB-11765\n159.65.76.92 (bematech-do-cb-008)\n\n06:43:04\n06:43:04  * couchbase-server is running\n06:43:04\n\n#+BEGIN_EXAMPLE\nDenny Zhang (DevOps) [8:48 AM]\nSo far, haven't found major issues.\n\nAll ES/mdm/haproxy services have been shutdown.\nAll CB services have been shutdown, except one. `159.65.76.92 (bematech-do-cb-008)`\n\nIt has been 13 minutes since we have issued the service stop command.\nWill watch another 2 minutes, then \"stop again\". If still doesn't work, use kill, then kill -9.\n#+END_EXAMPLE\n\n#+BEGIN_EXAMPLE\nroot@bematech-do-cb-008:/opt/couchbase/var/lib/couchbase/logs# service couchbase-server stop\n{error_logger,{{2018,2,26},{14,48,36}},\"Protocol: ~tp: the name executioner@executioner seems to be in use by another Erlang node\",[\"inet_tcp\"]}\n{error_logger,{{2018,2,26},{14,48,36}},crash_report,[[{initial_call,{net_kernel,init,['Argument__1']}},{pid,<0.21.0>},{registered_name,[]},{error_info,{exit,{error,badarg},[{gen_server,init_it,6,[{file,\"gen_server.erl\"},{line,320}]},{proc_lib,init_p_do_apply,3,[{file,\"proc_lib.erl\"},{line,239}]}]}},{ancestors,[net_sup,kernel_sup,<0.10.0>]},{messages,[]},{links,[#Port<0.53>,<0.18.0>]},{dictionary,[{longnames,true}]},{trap_exit,true},{status,running},{heap_size,610},{stack_size,27},{reductions,783}],[]]}\n{error_logger,{{2018,2,26},{14,48,36}},supervisor_report,[{supervisor,{local,net_sup}},{errorContext,start_error},{reason,{'EXIT',nodistribution}},{offender,[{pid,undefined},{name,net_kernel},{mfargs,{net_kernel,start_link,[['executioner@executioner',longnames]]}},{restart_type,permanent},{shutdown,2000},{child_type,worker}]}]}\n{error_logger,{{2018,2,26},{14,48,36}},supervisor_report,[{supervisor,{local,kernel_sup}},{errorContext,start_error},{reason,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}},{offender,[{pid,undefined},{name,net_sup},{mfargs,{erl_distribution,start_link,[]}},{restart_type,permanent},{shutdown,infinity},{child_type,supervisor}]}]}\n{error_logger,{{2018,2,26},{14,48,36}},crash_report,[[{initial_call,{application_master,init,['Argument__1','Argument__2','Argument__3','Argument__4']}},{pid,<0.9.0>},{registered_name,[]},{error_info,{exit,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}}},{kernel,start,[normal,[]]}},[{application_master,init,4,[{file,\"application_master.erl\"},{line,133}]},{proc_lib,init_p_do_apply,3,[{file,\"proc_lib.erl\"},{line,239}]}]}},{ancestors,[<0.8.0>]},{messages,[{'EXIT',<0.10.0>,normal}]},{links,[<0.8.0>,<0.7.0>]},{dictionary,[]},{trap_exit,true},{status,running},{heap_size,376},{stack_size,27},{reductions,117}],[]]}\n{error_logger,{{2018,2,26},{14,48,36}},std_info,[{application,kernel},{exited,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}}},{kernel,start,[normal,[]]}}},{type,permanent}]}\n{\"Kernel pid terminated\",application_controller,\"{application_start_failure,kernel,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}}},{kernel,start,[normal,[]]}}}\"}\n\nCrash dump was written to: erl_crash.dump.1519656516.20531.babysitter\nKernel pid terminated (application_controller) ({application_start_failure,kernel,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}}},{k\n * Failed to stop couchbase-server\n#+END_EXAMPLE\n** TODO jenkins: jenkins-job-builder plugin for job creation\n** TODO https://jenkins.io/doc/book/managing/cli/#remoting-connection-mode\n** TODO Jenkins: SCM Sync configuration plugin: https://wiki.jenkins.io/display/JENKINS/SCM+Sync+configuration+plugin\n** TODO learn from other repo: aws jenkins: https://github.com/search?p=2&q=aws-jenkins&type=Repositories&utf8=✓\n** TODO http://myjenkins:18080/job/CopyFolderFromNode1ToNode2/\n** TODO mute the output of token: http://myjenkins:18080/job/CreateAndProvisionVMInCloud/176/console\n** TODO restart es: console output is very slow to show: http://myjenkins:18080/job/RestartOneESSafely/5/console\n** TODO https://medium.com/meedan-updates/github-jenkins-hubot-slack-1e61a466e388\n** TODO Pull Request Validation Between Jenkins and Bitbucket: http://icarobichir.com.br/posts/pull-request-validation-between-jenkins-and-bitbucket/\n** TODO beautify ansible output: http://jenkinscn.dennyzhang.com:18088/job/dennytest/3/console\n** TODO jenkins: http://www.hugeinc.com/ideas/perspective/best-practices-for-jenkin-jobs\nhttps://www.infoq.com/articles/orch-pipelines-jenkins\n** HALF avoid jenkins: Jenkins is going to shut down\nhttps://stackoverflow.com/questions/12182882/how-to-prevent-hudson-from-entering-shutdown-mode-automatically-or-when-idle\nSolution: disable the thinBackup plugin\n\nhttps://wiki.jenkins.io/display/JENKINS/thinBackup\nhttps://issues.jenkins-ci.org/browse/JENKINS-13239\n\nHave you installed any plugin called Thin backup? if yes  it might  configured to shut down after back up, then change the setting.\n** #  --8<-------------------------- separator ------------------------>8-- :noexport:\n** TODO Jenkins credential parameter\n  http://steve-jansen.github.io/blog/2014/12/16/parsing-jenkins-secrets-in-a-shell-script/\nhttps://stackoverflow.com/questions/34815482/accessing-credentials-in-jenkins-with-the-credentials-parameter-plugin\nhttps://www.cloudbees.com/blog/injecting-secrets-jenkins-builds-using-credentials-plugin\n** TODO Jenkins shell get credential secret text\n** TODO Jenkins parse credential parameter\nhttps://stackoverflow.com/questions/34815482/accessing-credentials-in-jenkins-with-the-credentials-parameter-plugin\nhttps://wiki.jenkins-ci.org/display/JENKINS/Credentials+Binding+Plugin\n** TODO Jenkins apache issue!\nls -lth /var/run/apache2/apache2.pid\n** TODO bug: cancel backup from Jenkins won't kill the process\nroot@bematech-do-jenkins:/opt/couchbase/backup# ps -ef | grep cou\nroot     30800 30799  0 18:57 ?        00:00:00 python /opt/devops/bin/cb_backup.py --bucket_list=mdm-session --cbserver=http://138.68.225.199:8091 --cbbackup_bin=/opt/couchbase/mdmpublic/couchbase-cli/bin/cbbackup --backup_dir=/opt/couchbase/backup --username Administrator --password password1234 --backup_method full\nroot     30801 30800  0 18:57 ?        00:00:00 /bin/sh -c /opt/couchbase/mdmpublic/couchbase-cli/bin/cbbackup http://138.68.225.199:8091 /opt/couchbase/backup/mdm-session -u Administrator -p password1234 -b mdm-session -m full -t 4 >> /var/log/cb_backup.log\nroot     30802 30801 99 18:57 ?        00:00:43 python /opt/couchbase/mdmpublic/couchbase-cli/lib/python/cbbackup http://138.68.225.199:8091 /opt/couchbase/backup/mdm-session -u Administrator -p password1234 -b mdm-session -m full -t 4\nroot     31120 12741  0 18:58 pts/4    00:00:00 grep --color=auto cou\nroot@bematech-do-jenkins:/opt/couchbase/backup# kill 30800\n** TODO Jenkins create a global variable: to avoid duplication configurations\n** TODO Automate the thinbackup Jenkins restore\n** TODO Jenkins agent and servers\n** TODO automate Jenkins restore from thinbackup\n** TODO High Jenkins CPU load: we can't run the jobs\n** TODO Run Docker commands from Jenkins container\nhttps://sreeninet.wordpress.com/2016/01/23/ci-cd-with-docker-jenkins-and-tutum/\n\nhttps://stackoverflow.com/questions/38510952/jenkins-running-docker-commands-on-a-docker-slave\nhttps://github.com/jenkinsci/docker-workflow-plugin/tree/master/demo\nhttps://stackoverflow.com/questions/36088227/how-to-run-a-docker-command-in-jenkins-build-execute-shell\nhttps://stackoverflow.com/questions/42859443/execute-docker-commands-in-jenkins-in-docker-container\n** TODO Use AWS S3 for my critical backup: Jenkins configurations\n* TODO [#A] try Jenkins X                                          :noexport:\n* TODO jenkins pipeline run docker container                       :noexport:\n* TODO jenkins enable github authentication                        :noexport:\nhttps://jenkins.io/solutions/github/\n* useful link                                                      :noexport:\nhttp://tdongsi.github.io/blog/2017/12/30/groovy-hook-script-and-jenkins-configuration-as-code/\nhttp://tdongsi.github.io/blog/2017/07/18/basic-jenkinsfile-cookbook/\nhttp://tdongsi.github.io/blog/2017/06/16/troubleshooting-groovy-scripts-in-jenkinsfile/\nhttp://tdongsi.github.io/blog/2017/04/18/groovy-code-in-jenkins-pipeline/\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* TODO Provision agent using Jenkins swarm plugin                  :noexport:\n* TODO Automate agent provisioning and make them ephemeral         :noexport:\n* TODO Jenkins pipeline: docker image as agent                     :noexport:\n* TODO docker image as agent with persistent storage               :noexport:\n* HALF Jenkins script approval                                     :noexport:\nhttps://gist.github.com/dnozay/e7afcf7a7dd8f73a4e05\nhttps://stackoverflow.com/questions/43476370/exporting-and-importing-jenkins-pipeline-script-approvals/43477258\n\n#+BEGIN_EXAMPLE\n// instance containing the approvals\n// list of approved hashes: println instance.approvedScriptHashes\n \nScriptApproval instance = Jenkins.getInstance().getExtensionList(RootAction.class).get(ScriptApproval.class);\napprovedScriptHashes = instance.approvedScriptHashes\n#+END_EXAMPLE\n* TODO groovy: Use a regular expression to include jobs into the view :noexport:\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* DONE [#A] Jenkins: send slack notification for job failures      :noexport:\n  CLOSED: [2019-05-01 Wed 11:06]\n* DONE [#A] jenkins kubo_ssh_passwd: jenkins secret text           :noexport:\n  CLOSED: [2019-05-01 Wed 11:06]\nhttps://support.cloudbees.com/hc/en-us/articles/204897020-Fetch-a-userid-and-password-from-a-Credential-object-in-a-Pipeline-job-\nhttps://stackoverflow.com/questions/48330402/secret-text-git-credentials-not-showing-up-in-jenkins-project-source-code-mana#comment83676647_48336020\nhttps://github.com/jenkinsci/slack-plugin/issues/270\nhttps://fedidat.com/270-jenkinsfile-scripted-secret-text/\nhttps://jenkins.io/doc/pipeline/steps/credentials-binding/\nhttp://steve-jansen.github.io/blog/2014/12/16/parsing-jenkins-secrets-in-a-shell-script/\nhttps://kb.novaordis.com/index.php/Injecting_Jenkins_Credentials_into_a_Build_Job\n\n* DONE jenkins groovy get job                                      :noexport:\n  CLOSED: [2019-04-25 Thu 22:13]\nhttps://medium.com/@garimajdamani/how-to-get-jenkins-build-job-details-b8c918087030\nimport jenkins.model.Jenkins\nname = \"ProvisionPKSEnvRaw\"\ndef job = Hudson.instance.getJob(name)\nprintln job.getLastBuild().getLog(50)\n\n* DONE doc: Jenkins pipeline: if ip not found, skip healthcheck    :noexport:\n  CLOSED: [2019-04-26 Fri 19:16]\n#+BEGIN_SRC groovy\nvoid triggerHealthCheck() {\n    if (!kuboIP.isEmpty()) {\n        def child_job = build job: &apos;HealthCheckPKSEnv&apos;,\n            propagate: false,\n            parameters: [string(name: &apos;jumpbox_ip&apos;, value: kuboIP),\n                         string(name: &apos;skip_kubectl_test&apos;, value: &apos;true&apos;)]\n        loadAndParseJobLogs(child_job)\n        updateBuild(child_job)\n    } else {\n        println(&quot;WARNING: kuboIP is not found from downstream job output. Skip health check&quot;)\n    }\n}\n#+END_SRC\n\n#+BEGIN_SRC groovy\n        stage(&apos;Health check&apos;) {\n            steps {\n                echo &apos;===&gt; Start the health check of the provisioned nimbus testbed...&apos;\n                timeout(time: 180, unit: &apos;MINUTES&apos;) {\n                    script {\n                        triggerHealthCheck()\n                    }\n                }\n            }\n#+END_SRC\n\n* DONE Jenkins pipeline show user id                               :noexport:\n  CLOSED: [2019-04-28 Sun 21:42]\nhttps://stackoverflow.com/questions/49726409/jenkins-get-current-user-in-pipeline?answertab=votes#tab-top\nnode {\n  wrap([$class: 'BuildUser']) {\n       def user = env.BUILD_USER_ID\n       println \"user: \" + user\n     }\n}\n* DONE Jenkins pipeline if else not working                        :noexport:\n  CLOSED: [2019-04-28 Sun 22:13]\nhttps://stackoverflow.com/questions/43587964/jenkins-pipeline-if-else-not-working\n\n- you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using \"when\". \n- wrap it in a script step\n\n#+BEGIN_SRC groovy\npipeline {\n    agent any\n\n    stages {\n        stage('test') {\n            steps {\n                sh 'echo hello'\n            }\n        }\n        stage('test1') {\n            steps {\n                sh 'echo $TEST'\n            }\n        }\n        stage('test3') {\n            steps {\n                script {\n                    if (env.BRANCH_NAME == 'master') {\n                        echo 'I only execute on the master branch'\n                    } else {\n                        echo 'I execute elsewhere'\n                    }\n                }\n            }\n        }\n    }\n}\n#+END_SRC\n* DONE jenkins credentials                                         :noexport:\n  CLOSED: [2019-04-29 Mon 14:45]\nhttps://www.tikalk.com/posts/2017/03/07/how-to-mask-credentials-in-your-jenkins-jobs/\n\n* DONE jenkins fails to send slack notification: check slack plugin version: slack:2.2 :noexport:\n  CLOSED: [2019-03-06 Wed 16:59]\nhttps://github.com/jenkinsci/slack-plugin/issues/323\n* DONE Better Jenkins UI: ocean-blue                               :noexport:\n  CLOSED: [2019-03-14 Thu 16:11]\nhttps://jenkins.io/doc/book/blueocean/getting-started/#as-part-of-jenkins-in-docker\n* DONE Dynamically create jenkins users                            :noexport:\n  CLOSED: [2019-03-27 Wed 11:04]\n\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* TODO Jenkins credential scope: Global(jenkins, nodes, items, all child items, etc) and System (Jenkins and nodes only) :noexport:\n* HALF Jenkins pipeline credentials for all stages                 :noexport:\nhttps://stackoverflow.com/questions/49739933/jenkins-pipeline-credentials-for-all-stages\n* TODO Configure jenkins slave Node                                :noexport:\n* TODO Semantic Versioning class for Groovy                        :noexport:\nhttps://gist.github.com/michaellihs/a6621376393821d6d206ccfc8dbf86ec\n* TODO [#A] Run jenkins pipeline code inside docker image          :noexport:\nhttps://akomljen.com/set-up-a-jenkins-ci-cd-pipeline-with-kubernetes/\nhttps://gist.github.com/cyrille-leclerc/8cad9d1b35ea553820a1\n* TODO [#A] jenkins wrap class                                     :noexport:\nhttps://gist.github.com/cyrille-leclerc/552e3103139557e0196a\nhttps://gist.github.com/HarshadRanganathan/97feed7f91b7ae542c994393447f3db4\n* TODO Load groovy script as import, instead of                    :noexport:\npipelineUtils = load \"${JENKINS_HOME}/init.groovy.d/pipeline-utils.groovy\"\n\n                    script {\n                        pipelineUtils.sendSlackNotification(slack_target, jobLogs, downstreamJobResult)\n                    }\n* HALF Jenkins pipeline check website availability issue           :noexport:\nhttps://stackoverflow.com/questions/40393557/jenkins-pipeline-script-to-check-the-website-is-up\nhttps://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.triggers.MultibranchWorkflowTriggerContext.urlTrigger\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* DONE Builds in Jenkins run as the virtual SYSTEM user with full permissions by default. :noexport:\n  CLOSED: [2019-06-13 Thu 11:18]\nhttps://wiki.jenkins.io/display/JENKINS/Authorize+Project+plugin\n#+BEGIN_EXAMPLE\nBuilds in Jenkins run as the virtual SYSTEM user with full permissions by default. This can be a problem if some users have restricted or no access to some jobs, but can configure others. If that is the case, it is recommended to install a plugin implementing build authentication, and to override this default.\n✅ An implementation of access control for builds is present.\n❌ Access control for builds is possible, but not configured. Configure it in the global security configuration\n#+END_EXAMPLE\n* TODO Tried proxying jenkins.telemetry.Correlator to support a circular dependency, but it is not an interface. :noexport:\nhttps://github.com/marcelbirkner/docker-ci-tool-stack/issues/70\n* #  --8<-------------------------- separator ------------------------>8-- :noexport:\n* Jenkins cheatshee: https://www.edureka.co/blog/cheatsheets/jenkins-cheat-sheet/ :noexport:\n* TODO update doc                                                  :noexport:\nhttps://wilsonmar.github.io/jenkins2-pipeline/\n* Jenkins code coverage                                            :noexport:\n** Cobertura coverage report\nhttps://wiki.jenkins.io/display/JENKINS/Cobertura+Plugin\n\nhttps://vmoperator.svc.eng.vmware.com/view/Auth%20Service/job/gcm-build/59/\n* jenkins groovy timeout set the value                             :noexport:\nhttps://stackoverflow.com/questions/38597006/input-step-with-timeout-which-continues-with-default-settings-using-jenkins-pipe?rq=1\n* TODO Integrate GitLab MR with Jenkins Job in your CI Pipeline    :noexport:\nhttps://confluence.eng.vmware.com/display/BUTLER/Jenkins+Troubleshooting#JenkinsTroubleshooting-Jenkinsgitlabplugin:Can'ttriggerbuildsonAcceptedMergeRequests\n\n#+BEGIN_EXAMPLE\n\nCreate a Pipeline Job and configure Build Trigger as follows\n\nPlease Note that \"Filter merge request by label\" is optional. If you add any label, this job will be triggered only when the MR contains these labels\nGenerate Secret toke by clicking \"Generate\" button. (Please make note of the token, we need to enter same value in the GitLab hook in Step 3)\nConfigure your Pipeline job location. (Jenkins Job will scan the git-repo that you configure for \"Jenkinsfile\" file)\n\nCredentials : You can use whoever have atleast \"developer\" permission on this project.\nBranches to build: \"${gitlabSourceRepoName}/${gitlabSourceBranch}\"\nScript path: This is the path to the Jenkinsfile in your repo.\nSave your pipeline job.\nNow, its time to configure the webhook in GitLab repo to trigger this job on MR.\nGo to your repo in GitLab → Settings → Integrations\n\nEnter the token that you generated in your Jenkins pipeline job and enable all appropriate checkboxes for your project.\nAdd GitLab logger in Jenkins\nGo to Jenkins -> Manage Jenkins -> System Log\nAdd new log recorder\nEnter 'Gitlab plugin' or whatever you want for the name\nOn the next page, enter 'com.dabsquared.gitlabjenkins' for Logger, set log level to FINEST, and save\nThen click on your Gitlab plugin log, click 'Clear this log' if necessary, and then use GitLab to trigger some actions\nRefresh the log page and you should see output\nGo back to the Integration page in the GitLab, click on \"Test\" button to see if your webhook is triggering the Jenkins job. you can just see the log in the Jenkins under the logger you just created in previous step\nSend a Dummy MR to the branch (Make sure you add the \"labels\" if you enabled any filtering in your job) and see if the pipeline is getting triggered, if not, check the logs in the Jenkins and Gitlab (by editing the hook, you can see the Recent Deliveries)\nMore info: https://github.com/jenkinsci/gitlab-plugin\nMore info on writing pipeline stages with GitLab: https://gitlab.eng.XXX.com/devtools/butler/butler-next/blob/butler-generic-workflow/api/Jenkinsfile\n#+END_EXAMPLE\n* TODO jenkins pipeline use array                                  :noexport:\n* TODO jenkins groovy format string                                :noexport:\n* groovy                                                           :noexport:\nString fileContents = \"zdenny-vdnet-esx-sb-30035046-1-poc-dev-denny-22 | 10.161.178.251 zdenny-vdnet-esx-sb-30035046-3-poc-dev-denny-22 | 10.161.164.134 zdenny-vdnet-esx-sb-30035046-2-poc-dev-denny-22 | 10.161.166.34 zdenny-vdnet-esx-sb-30035046-100-poc-dev-denny-22 | 10.161.181.6 zdenny-vdnet-vc-sb-30035088-1-poc-dev-denny-22 | 10.161.182.121 zdenny-vdnet-nsxmanager-14880419-1-poc-dev-denny-22 | 10.161.184.67 zdenny-wn-1-poc-dev-denny-22\";\n\ndef digitPattern = ~/.*(vdnet-vc).*/;\n\ndef matcher = fileContents =~ digitPattern;\nmatcher.size();\nmatcher[0]\nmatcher[1]\n\n// digitPattern.matcher(fileContents).find()\n\n [0-9]+\\.[0-9]+\\.[0-9]+121\n"
  },
  {
    "path": "addjobstoview-byregexp.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: addjobstoview-byregexp.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-23 14:37:35>\n//-------------------------------------------------------------------\n// imports\nimport jenkins.model.Jenkins\nimport hudson.model.ListView\nimport hudson.model.View\n\n// get Jenkins instance\nJenkins jenkins = Jenkins.getInstance()\n\ndef viewName = 'MyTest'\njenkins.addView(new ListView(viewName))\nmyView = hudson.model.Hudson.instance.getView(viewName)\nfor (item in Jenkins.instance.projects.collect()) {\n    if (item.name ==~ /.*Test.*/ ) {\n        myView.doAddJobToView(item.name)\n    }\n}\n\n// Add by regexp\nviewName = 'Integration'\njenkins.addView(new ListView(viewName))\nmyView = hudson.model.Hudson.instance.getView(viewName)\nmyView.setIncludeRegex(\".*Integration.*\")\n"
  },
  {
    "path": "build-monitor-views.xml",
    "content": "  <views>\n    <hudson.model.AllView>\n      <owner class=\"hudson\" reference=\"../../..\"/>\n      <name>all</name>\n      <filterExecutors>false</filterExecutors>\n      <filterQueue>false</filterQueue>\n      <properties class=\"hudson.model.View$PropertyList\"/>\n    </hudson.model.AllView>\n    <com.smartcodeltd.jenkinsci.plugins.buildmonitor.BuildMonitorView plugin=\"build-monitor-plugin@1.12+build.201809061734\">\n      <owner class=\"hudson\" reference=\"../../..\"/>\n      <name>AutoReport</name>\n      <filterExecutors>false</filterExecutors>\n      <filterQueue>false</filterQueue>\n      <properties class=\"hudson.model.View$PropertyList\"/>\n      <jobNames>\n        <comparator class=\"hudson.util.CaseInsensitiveComparator\"/>\n        <string>DetectTestbedFormatChanges</string>\n        <string>MonitorDownloadURLs</string>\n        <string>NightlyProvisionBasicTest</string>\n        <string>NightlyProvisionGear2Test</string>\n        <string>NightlyProvisionIntegrationTest</string>\n        <string>ProvisionPKSEnvNimbus</string>\n        <string>ProvisionPKSEnvNimbusAdvancew</string>\n      </jobNames>\n      <jobFilters/>\n      <columns/>\n      <recurse>false</recurse>\n      <title>AutoReport</title>\n      <config>\n        <displayCommitters>false</displayCommitters>\n        <buildFailureAnalyzerDisplayedField>Name</buildFailureAnalyzerDisplayedField>\n        <order class=\"com.smartcodeltd.jenkinsci.plugins.buildmonitor.order.ByName\"/>\n      </config>\n    </com.smartcodeltd.jenkinsci.plugins.buildmonitor.BuildMonitorView>\n  </views>\n"
  },
  {
    "path": "check-slave-jar-version.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: check-slave-jar-version.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:51:48>\n//-------------------------------------------------------------------\n// https://gist.github.com/ctran/8f82adedaa23ea924c52\nimport jenkins.model.*\nimport hudson.remoting.Launcher\nimport hudson.slaves.SlaveComputer\n\ndef expectedVersion = Launcher.VERSION\nfor (computer in Jenkins.instance.getComputers()) {\n  if (! (computer instanceof SlaveComputer)) continue\n  if (!computer.getChannel()) continue\n\t\n  def version = computer.getSlaveVersion()\n  if (!expectedVersion.equals(version)) {\n    println \"${computer.name} - expected ${expectedVersion} but got ${version}\"\n  }\n}\n"
  },
  {
    "path": "config-pipeline-library.groovy",
    "content": "// https://github.com/thbkrkr/jks/blob/master/init.groovy.d/11-configure-pipeline-global-shared.groovy\n/*\n * Configure pipeline shared libraries in the global Jenkins configuration.\n * This will safely compare configured libraries and only overwrite the global\n * shared library config if changes have been made.\n * workflow-cps-global-lib 2.9\n */\nimport jenkins.model.Jenkins\nimport jenkins.plugins.git.GitSCMSource\nimport jenkins.plugins.git.traits.BranchDiscoveryTrait\nimport org.jenkinsci.plugins.workflow.libs.GlobalLibraries\nimport org.jenkinsci.plugins.workflow.libs.LibraryConfiguration\nimport org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever\n\nList libraries = [] as ArrayList\n\ndef remote = System.getenv(\"PIPELINE_SHARED_LIB_REMOTE\")\ndef credentialsId = System.getenv(\"PIPELINE_SHARED_LIB_CREDS_ID\")\n\nname = 'pipeline-lib'\ndefaultVersion = 'master'\n\nif (remote != null) {\n\n    def scm = new GitSCMSource(remote)\n    if (credentialsId != null) {\n        scm.credentialsId = credentialsId\n    }\n\n    scm.traits = [new BranchDiscoveryTrait()]\n    def retriever = new SCMSourceRetriever(scm)\n\n    def library = new LibraryConfiguration(name, retriever)\n    library.defaultVersion = defaultVersion\n    library.implicit = true\n    library.allowVersionOverride = true\n    library.includeInChangesets = true\n\n    libraries << library\n\n    def global_settings = Jenkins.instance.getExtensionList(GlobalLibraries.class)[0]\n    global_settings.libraries = libraries\n    global_settings.save()\n    println 'Configured Pipeline Global Shared Libraries:\\n    ' + global_settings.libraries.collect { it.name }.join('\\n    ')\n}\n"
  },
  {
    "path": "config-slack.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: slack_notification.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Description :\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-30 16:07:20>\n//-------------------------------------------------------------------\n// https://github.com/jenkinsci/slack-plugin/blob/master/src/main/java/jenkins/plugins/slack/SlackNotifier.java\nimport jenkins.model.Jenkins\nimport jenkins.plugins.slack.SlackNotifier.*\n\n// def slack = Jenkins.instance.getDescriptorByType(jenkins.plugins.slack.SlackNotifier.DescriptorImpl)\ndef slack = Jenkins.instance.getExtensionList('jenkins.plugins.slack.SlackNotifier$DescriptorImpl')[0]\n\nslack.tokenCredentialId = 'slack_token_passwd'\nslack.baseUrl = 'https://vmware.slack.com/services/hooks/jenkins-ci'\n\nslack.save()\nprintln 'Slack global settings configured.'\n"
  },
  {
    "path": "create-jenkins-job.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: create-jenkins-job.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 13:47:38>\n//-------------------------------------------------------------------\nimport jenkins.model.Jenkins;\nimport hudson.model.FreeStyleProject;\nimport hudson.tasks.Shell;\n\njob = Jenkins.instance.createProject(FreeStyleProject, 'job-name')\n\njob.buildersList.add(new Shell('echo hello world'))\n\njob.save()\n\nbuild = job.scheduleBuild2(5, new hudson.model.Cause.UserIdCause())\n\nbuild.get()\n"
  },
  {
    "path": "create-jenkins-user.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: create-jenkins-user.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:51:53>\n//-------------------------------------------------------------------\n// https://gist.github.com/hayderimran7/50cb1244cc1e856873a4\nimport jenkins.model.*\nimport hudson.security.*\n\ndef instance = Jenkins.getInstance()\n\n// Create a jenkins user\ndef hudsonRealm = new HudsonPrivateSecurityRealm(false)\nhudsonRealm.createAccount(\"jenkinsadmin\",\"password1234\")\ninstance.setSecurityRealm(hudsonRealm)\n"
  },
  {
    "path": "create-secret-text.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: create-secret-text.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:51:58>\n//-------------------------------------------------------------------\n// https://gist.github.com/chrisvire/383a2c7b7cfb3f55df6a\nimport jenkins.model.*\nimport hudson.util.Secret\nimport com.cloudbees.plugins.credentials.*\nimport com.cloudbees.plugins.credentials.domains.*\nimport org.jenkinsci.plugins.plaincredentials.impl.*\n\ndomain = Domain.global()\nstore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()\n\nsecretText = new StringCredentialsImpl(\nCredentialsScope.GLOBAL,\n\"secret-text\",\n\"Secret Text Description\",\nSecret.fromString(\"some secret text goes here\"))\n\nstore.addCredentials(domain, secretText)\n"
  },
  {
    "path": "delete-job-by-regexp.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: delete-job-by-regexp.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:03>\n//-------------------------------------------------------------------\n// https://gist.github.com/nextrevision/d11b2df4e8b229c6855b\nimport jenkins.model.*\n\ndef matchedJobs = Jenkins.instance.items.findAll { job ->\n    job.name =~ /my_regex_here/\n}\n    \nmatchedJobs.each { job ->\n    println job.name\n    //job.delete()\n}\n"
  },
  {
    "path": "dict-to-json.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: dict-to-json.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:51:19>\n//-------------------------------------------------------------------\nimport static groovy.json.JsonOutput.*\ndef config = ['name': 'denny']\nprintln prettyPrint(toJson(config))\n"
  },
  {
    "path": "docker-cleanup.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: docker-cleanup.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:13>\n//-------------------------------------------------------------------\n// https://gist.github.com/rcbop/4acabfb15db6b361698ebd76ce5646e2\nnode(\"${params.BUILD_AGENT}\") {\n    \n    stage('Dangling Containers') {\n      sh 'docker ps -q -f status=exited | xargs --no-run-if-empty docker rm'\n    }\n\n    stage('Dangling Images') {\n      sh 'docker images -q -f dangling=true | xargs --no-run-if-empty docker rmi'\n    }\n    \n    stage('Dangling Volumes') {\n      sh 'docker volume ls -qf dangling=true | xargs -r docker volume rm'\n    }\n}\n\n"
  },
  {
    "path": "enable-ldap.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: enable-ldap.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:17>\n//-------------------------------------------------------------------\nimport jenkins.model.*\n\nimport hudson.security.LDAPSecurityRealm\nimport hudson.security.HudsonPrivateSecurityRealm\nimport hudson.security.FullControlOnceLoggedInAuthorizationStrategy\nimport hudson.util.Secret\nimport jenkins.model.IdStrategy\nimport jenkins.security.plugins.ldap.LDAPConfiguration\nimport net.sf.json.JSONObject\n\n// https://wiki.jenkins.io/display/JENKINS/LDAP+Plugin\nif(!binding.hasVariable('ldap_settings')) {\n   ldap_settings = [\n      'server': 'ldaps://ldaps.mycompany.com:636',\n      'rootDN': 'DC=mycompany,DC=com',\n   ]\n}\nif(!(ldap_settings instanceof Map)) {\n   throw new Exception('ldap_settings must be a Map.')\n}\n\nldap_settings = ldap_settings as JSONObject\n\nif(!(Jenkins.instance.securityRealm instanceof LDAPSecurityRealm)) {\n   LDAPConfiguration conf = new LDAPConfiguration(\n      ldap_settings.optString('server'),\n      ldap_settings.optString('rootDN'),\n      ldap_settings.optBoolean('inhibitInferRootDN'),\n      ldap_settings.optString('managerDN'),\n      Secret.fromString(ldap_settings.optString('managerPasswordSecret')))\n\n   conf.userSearchBase = ldap_settings.optString('userSearchBase')\n   conf.userSearch = ldap_settings.optString('userSearch', LDAPSecurityRealm.DescriptorImpl.DEFAULT_USER_SEARCH)\n   conf.groupSearchBase = ldap_settings.optString('groupSearchBase')\n   conf.groupSearchFilter = ldap_settings.optString('groupSearchFilter')\n   conf.environmentProperties = (ldap_settings.opt('environmentProperties')?:[:]).collect { k, v ->\n      new LDAPSecurityRealm.EnvironmentProperty(k.toString(), v.toString())\n   } as LDAPSecurityRealm.EnvironmentProperty[]\n   conf.displayNameAttributeName = ldap_settings.optString('displayNameAttributeName', LDAPSecurityRealm.DescriptorImpl.DEFAULT_DISPLAYNAME_ATTRIBUTE_NAME)\n   conf.mailAddressAttributeName = ldap_settings.optString('mailAddressAttributeName', LDAPSecurityRealm.DescriptorImpl.DEFAULT_MAILADDRESS_ATTRIBUTE_NAME)\n\n   List<LDAPConfiguration> configurations = [conf]\n   Jenkins.instance.securityRealm = new LDAPSecurityRealm(\n      configurations,\n      ldap_settings.optBoolean('disableMailAddressResolver'),\n      null,\n      IdStrategy.CASE_INSENSITIVE,\n      IdStrategy.CASE_INSENSITIVE)\n\n   def strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()\n   strategy.setAllowAnonymousRead(true)\n   Jenkins.instance.setAuthorizationStrategy(strategy)\n\n   Jenkins.instance.save()\n   println 'Security realm set to LDAP.'\n}\nelse {\n   println 'Nothing changed.  LDAP security realm already configured.'\n}\n"
  },
  {
    "path": "execute-command.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: execute-command.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:22>\n//-------------------------------------------------------------------\n// https://gist.github.com/katta/5465317\ndef command = \"date\"\ndef proc = command.execute()\nproc.waitFor()     \n\nprintln \"Process exit code: ${proc.exitValue()}\"\nprintln \"Std Err: ${proc.err.text}\"\nprintln \"Std Out: ${proc.in.text}\" \n"
  },
  {
    "path": "files-folder.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: files-folder.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:26>\n//-------------------------------------------------------------------\nimport groovy.io.FileType\n\n// Create folder if missing\ndef folderName = '/var/jenkins_home/jobs/backup'\n\ndef thinBackupDir = new File(folderName)\nif (thinBackupDir.exists() == false) {\n   // https://github.com/cloudbees/jenkins-scripts/blob/master/copy-move-diagnosis.groovy#L19\n   thinBackupDir.mkdirs()\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Create folders and files\n// https://mrhaki.blogspot.com/2010/04/groovy-goodness-working-on-files-or.html\n// First create sample dirs and files.\n(1..3).each {\n new File(\"dir$it\").mkdir()\n}\n(1..3).each {\n def file = new File(\"file$it\")\n file << \"Sample content for ${file.absolutePath}\"\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Create files with different methods\n// https://mrhaki.blogspot.com/2009/08/groovy-goodness-working-with-files.html\n// Normal way of creating file objects.\ndef file1 = new File('groovy1.txt')\ndef file2 = new File('groovy2.txt')\ndef file3 = new File('groovy3.txt')\n \n// Writing to the files with the write method:\nfile1.write 'Working with files the Groovy way is easy.\\n'\n \n// Using the leftShift operator:\nfile1 << 'See how easy it is to add text to a file.\\n'\n \n// Using the text property:\nfile2.text = '''We can even use the text property of\na file to set a complete block of text at once.'''\n \n// Or a writer object:\nfile3.withWriter('UTF-8') { writer ->\n    writer.write('We can also use writers to add contents.')\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Reading contents of files to an array:\ndef lines = file1.readLines()\nassert 2 == lines.size()\nassert 'Working with files the Groovy way is easy.' == lines[0]\n\n// Or we read with the text property:\nassert 'We can also use writers to add contents.' == file3.text\n\n     \n////////////////////////////////////////////////////////////////////////////////\n// Delete all files:\n// https://mrhaki.blogspot.com/2009/08/groovy-goodness-working-with-files.html\nfiles.each { new File(it).delete() }\n\n////////////////////////////////////////////////////////////////////////////////\n/*\n// https://mrhaki.blogspot.com/2009/12/groovy-goodness-delete-non-empty.html\ndef mainDir = new File('test')\ndef subDir = new File(mainDir, 'app')\ndef file = new File(subDir, 'test.txt')\n \nsubDir.mkdirs()  // Create directories.\nfile << 'sample'  // Create file and add contents.\n \nassert mainDir.exists() && subDir.exists() && file.exists()\n \ndef result = mainDir.deleteDir()  // Returns true if all goes well, false otherwise.\nassert result\nassert !mainDir.exists() && !subDir.exists() && !file.exists()\n*/    \n"
  },
  {
    "path": "find-dead-executors.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: find-dead-executors.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 14:09:37>\n//-------------------------------------------------------------------\n// https://gist.github.com/malonem/5045386\n// get handle to build output\ndef config = new HashMap()\ndef bindings = getBinding()\nconfig.putAll(bindings.getVariables())\ndef out = config['out']\n\nfor (aSlave in hudson.model.Hudson.instance.slaves) {\n  // check if executor is dead\n  execList = aSlave.getComputer().getExecutors()      \n  for( exec in execList ) {\n    if (exec.getCauseOfDeath()) {\n      println(\"\\tSlave ${aSlave.name} has a dead executor.\")\n      println(\"Error:\")\n      exec.getCauseOfDeath().printStackTrace(out) \n      println('\\n')\n      println(\"\\tRemoving Dead Executor.\")\n      exec.doYank()\n    }\n  } \n}\n"
  },
  {
    "path": "get-env.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: get-env.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-30 15:27:12>\n//-------------------------------------------------------------------\n// http://www.mytechtoday.com/2009/01/read-environment-variables-with-groovy.html\ndef env = System.getenv()\n// Print all the environment variables.\n\nenv.each{\nprintln it\n} \n// You can also access the specific variable, say 'username', as show below \nString user= env['USERNAME']\n\n// https://stackoverflow.com/questions/31707667/how-to-access-jenkins-environment-variables-with-dsl\n\ndef envVars = Jenkins.instance.getGlobalNodeProperties()[0].getEnvVars()\nprintln envVars['myVar']\n\n/*\nimport hudson.model.*;\nimport jenkins.model.*;\n\nThread.start {\n      sleep 10000\n      println \"--> setting agent port for jnlp\"\n      def env = System.getenv()\n      int port = env['JENKINS_SLAVE_AGENT_PORT'].toInteger()\n      Jenkins.instance.setSlaveAgentPort(port)\n      println \"--> setting agent port for jnlp... done\"\n}\n*/\n"
  },
  {
    "path": "get-ip-by-hostname.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: get-ip-by-hostname.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// https://asoftwareguy.com/2014/04/17/get-the-ip-address-for-a-host-name-in-groovy/\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:37>\n//-------------------------------------------------------------------\ndef hostname = 'google.com'\nprintln InetAddress.getByName(hostname).address.collect { it & 0xFF }.join('.')\n"
  },
  {
    "path": "git-checkout.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: git-checkout.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:31>\n//-------------------------------------------------------------------\n// https://gist.github.com/lferro9000/471ae1a98267e20530d989f64f5290ee\n#!/usr/bin/env groovy\n\nnode('php') {\n\n    stage('Get code from SCM') {\n        checkout(\n                [$class: 'GitSCM', branches: [[name: '*/#your-dev-branch#']],\n                 doGenerateSubmoduleConfigurations: false,\n                 extensions: [],\n                 submoduleCfg: [],\n                 userRemoteConfigs: [[url: '#your-git-link#']]]\n        )\n    }\n\n    stage('Composer Install') {\n        sh 'composer install'\n    }\n\n    stage(\"PHPLint\") {\n        sh 'find app -name \"*.php\" -print0 | xargs -0 -n1 php -l'\n    }\n}\n"
  },
  {
    "path": "git-commits-before-fail.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: git-commits-before-fail.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:35>\n//-------------------------------------------------------------------\n// https://gist.github.com/ftclausen/8c46195ee56e48e4d01cbfab19c41fc0\n// -*- mode: groovy -*-\n// vim: set filetype=groovy :\nnode( 'some_node' ) {\n  stage( \"Phase 1\" ) {\n    sshagent( credentials: [ 'some_creds' ] ) {\n      checkout scm\n      def lastSuccessfulCommit = getLastSuccessfulCommit()\n      def currentCommit = commitHashForBuild( currentBuild.rawBuild )\n      if (lastSuccessfulCommit) {\n        commits = sh(\n          script: \"git rev-list $currentCommit \\\"^$lastSuccessfulCommit\\\"\",\n          returnStdout: true\n        ).split('\\n')\n        println \"Commits are: $commits\"\n      }\n    }\n  }\n}\n\ndef getLastSuccessfulCommit() {\n  def lastSuccessfulHash = null\n  def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild()\n  if ( lastSuccessfulBuild ) {\n    lastSuccessfulHash = commitHashForBuild( lastSuccessfulBuild )\n  }\n  return lastSuccessfulHash\n}\n\n/**\n * Gets the commit hash from a Jenkins build object, if any\n */\n@NonCPS\ndef commitHashForBuild( build ) {\n  def scmAction = build?.actions.find { action -> action instanceof jenkins.scm.api.SCMRevisionAction }\n  return scmAction?.revision?.hash\n}\n"
  },
  {
    "path": "git-list-tags-and-branches.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: git-list-tags-and-branches.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:47:01>\n//-------------------------------------------------------------------\n// https://gist.github.com/eeichinger/9761870\ndef gettags = (\"git ls-remote -t -h ssh://jenkins@<mygitpath>/repo/some.git feature/*\").execute()\n\nreturn gettags.text.readLines()\n         .collect { it.split()[1].replaceAll('refs/heads/', '')  }\n         .unique()\n         .findAll { it.startsWith('<some more pattern>') }\n"
  },
  {
    "path": "jenkins-kubernetes-cloud.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkins-kubernetes-cloud.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:44>\n//-------------------------------------------------------------------\n// https://stackoverflow.com/questions/38273070/groovy-script-to-apply-kubernetes-cloud-config-in-jenkins\nimport org.csanchez.jenkins.plugins.kubernetes.*\nimport jenkins.model.*\n\ndef j = Jenkins.getInstance()\n\ndef k = new KubernetesCloud(\n  'kubernetes',\n  null,\n  'https://192.168.150.100:8443',\n  '',\n  'http://40.0.4.3:8080',\n  '10', 0, 0, 5\n)\nk.setSkipTlsVerify(true)\n\nj.clouds.replace(k)\nj.save()\n"
  },
  {
    "path": "jenkins-permission.groovy",
    "content": "import jenkins.model.Jenkins;\nimport hudson.security.GlobalMatrixAuthorizationStrategy;\n\nif (hudson.model.User.getAll().size()==1 && hudson.model.User.getAll()[0].toString().equals('admin')) {\n  List admins = [\n    'admin1',\n    'admin2'\n  ]\n\n  def strategy = new hudson.security.GlobalMatrixAuthorizationStrategy()\n  admins.each {\n    strategy.add(hudson.model.Hudson.ADMINISTER, it)\n  }\n\n  // Add read permission for all users\n  strategy.add(hudson.model.Item.READ,'anonymous')\n  strategy.add(hudson.model.Item.DISCOVER,'anonymous')\n  strategy.add(hudson.model.Hudson.READ,'anonymous')\n  strategy.add(hudson.model.Item.READ,'authenticated')\n  strategy.add(hudson.model.Item.DISCOVER,'authenticated')\n  strategy.add(hudson.model.Hudson.READ,'authenticated')\n  Jenkins.instance.setAuthorizationStrategy(strategy)\n}\n"
  },
  {
    "path": "jenkins-url.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkins-url.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-09 11:43:15>\n//-------------------------------------------------------------------\n// https://gist.github.com/fishi0x01/7c2d29afbaa0f16126eb4d4b35942f76\n/*\n * This script configures the Jenkins base URL.\n */\n\nimport jenkins.model.JenkinsLocationConfiguration\n\nJenkinsLocationConfiguration location = Jenkins.instance.getExtensionList('jenkins.model.JenkinsLocationConfiguration')[0]\nlocation.url = 'https://jenkins-as-code-poc.devtail.io/'\nlocation.save()\n\n// Solution 2\n// https://github.com/docksal/service-jenkins/blob/master/groovy/default-config.groovy\nimport jenkins.model.*\nimport hudson.security.*\n\n// Get environment variables.\ndef env = System.getenv()\n\n// Change location configuration for admin address and Jenkins URL.\n// Currently this will override settings changed via Jenkins UI.\ndef jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()\njenkinsLocationConfiguration.setAdminAddress(env.JENKINS_EMAIL)\njenkinsLocationConfiguration.setUrl(env.JENKINS_URL)\njenkinsLocationConfiguration.save()\n"
  },
  {
    "path": "jenkins-views.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkins-views.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-02-16 22:03:51>\n//-------------------------------------------------------------------\n// imports\nimport jenkins.model.Jenkins\nimport hudson.model.ListView\nimport hudson.model.View\n\n// get Jenkins instance\nJenkins jenkins = Jenkins.getInstance()\n\ndef viewName = ''\n\nviewName = 'CIAutoMaintain'\njenkins.addView(new ListView(viewName))\nmyView = hudson.model.Hudson.instance.getView(viewName)\nfor(item in ['CleanOldArtifact', 'CreateTestEnv']) {\n    myView.doAddJobToView(item)\n}\n\n// save current Jenkins state to disk\njenkins.save()\n\n// Set default view\nView welcome_view = jenkins.getView('CIAutoMaintain')\nView primary_view = jenkins.getPrimaryView()\njenkins.setPrimaryView(welcome_view)\n"
  },
  {
    "path": "jenkins.security.QueueItemAuthenticatorConfiguration.xml",
    "content": "<?xml version='1.1' encoding='UTF-8'?>\n<jenkins.security.QueueItemAuthenticatorConfiguration>\n  <authenticators>\n    <org.jenkinsci.plugins.authorizeproject.GlobalQueueItemAuthenticator plugin=\"authorize-project@1.3.0\">\n      <strategy class=\"org.jenkinsci.plugins.authorizeproject.strategy.TriggeringUsersAuthorizationStrategy\"/>\n    </org.jenkinsci.plugins.authorizeproject.GlobalQueueItemAuthenticator>\n  </authenticators>\n</jenkins.security.QueueItemAuthenticatorConfiguration>\n"
  },
  {
    "path": "jenkinsfile-finally.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkinsfile-finally.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:43>\n//-------------------------------------------------------------------\nnode {\n  try {\n    def seconds = readFile(\"/tmp/test.txt\")\n\n      echo \"seconds begin\"\n      echo seconds\n      echo \"seconds done\"\n      parallel firstBranch: {\n      // do something\n      build job: 'SleepAnHour', parameters: [string(name: 'sleep_seconds', value: seconds)]\n    }, secondBranch: {\n      // do something else\n      build job: 'SleepTwoHours', parameters: [string(name: 'sleep_seconds', value: seconds)]\n        },\n         failFast: true\n      }\n  finally {\n    echo \"finally\"\n      }\n}\n"
  },
  {
    "path": "jenkinsfile-parallelly.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkinsfile-parallelly.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:45>\n//-------------------------------------------------------------------\nstage('stage1') {\n    echo 'Hello World'\n}\n\nstage('stage2') {\n    parallel firstBranch: {\n        // do something\n         build 'dennyjob1'\n    }, secondBranch: {\n        // do something else\n        build job: 'dennyjob2', parameters: [string(name: 'env1', value: 'value3')]\n    },\n    failFast: true\n}\n\nstage('stage3') {\n   build 'dennyjob3'\n}\n"
  },
  {
    "path": "jenkinsfile-pass-parameter.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkinsfile-pass-parameter.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:48>\n//-------------------------------------------------------------------\nnode {\n  def seconds = readFile(\"/tmp/test.txt\")\n\n    echo \"seconds begin\"\n    echo seconds\n    echo \"seconds done\"\n    parallel firstBranch: {\n    // do something\n    build job: 'SleepAnHour', parameters: [string(name: 'sleep_seconds', value: seconds)]\n  }, secondBranch: {\n    // do something else\n    build job: 'SleepTwoHours', parameters: [string(name: 'sleep_seconds', value: seconds)]\n      },\n       failFast: true\n    }\n"
  },
  {
    "path": "jenkinsfile-sequentially.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkinsfile-sequentially.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:50>\n//-------------------------------------------------------------------\nstage('stage1') {\n    echo 'Hello World'\n}\n\n\nstage('stage2') {\n   build 'dennyjob1'\n}\n\nstage('stage3') {\n   build job: 'dennyjob2', parameters: [string(name: 'env1', value: 'value3')]\n}\n"
  },
  {
    "path": "jenkinsfile-timeout-retry.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkinsfile-timeout-retry.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:44:04>\n//-------------------------------------------------------------------\n// https://jenkins.io/doc/pipeline/tour/running-multiple-steps/\nJenkinsfile (Declarative Pipeline)\npipeline {\n    agent any\n    stages {\n        stage('Deploy') {\n            steps {\n                retry(3) {\n                    sh './flakey-deploy.sh'\n                }\n\n                timeout(time: 3, unit: 'MINUTES') {\n                    sh './health-check.sh'\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "json-file.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: json-file.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:52:56>\n//-------------------------------------------------------------------\n// https://gist.github.com/keyle/723181f3a9a59a3f7652\n\npackage utils\n\nimport groovy.json.JsonBuilder\nimport groovy.json.JsonSlurper\n\nclass HDD {\n\n    static save(Object content, String filePath) {\n        new File(filePath).write(new JsonBuilder(content).toPrettyString())\n    }\n\n    static Object load(String filePath) {\n        return new JsonSlurper().parseText(new File(filePath).text)\n    }\n}\n"
  },
  {
    "path": "keep-going-with-errors.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: keep_going_with_errors.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Description :\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:44:11>\n//-------------------------------------------------------------------\n// https://stackoverflow.com/questions/36852310/show-a-jenkins-pipeline-stage-as-failed-without-failing-the-whole-job\n// Stages with shell commands\ndef tc_list = testsuites.tokenize(',')\n  tc_list.each {\n  try {\n    stage(\"${it}\") {\n      println \"============ Test ${it}\"\n      sh \"mvn com.smartbear.soapui:soapui-maven-plugin:5.1.2:test -Dmdm.test.suite=\\\"${it}\\\"\"\n    }\n  } catch (e) {\n    result = \"FAIL\"\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Stages with jenkins jobs\ntry {\n  stage('end-to-end-tests') {\n    node {\n      def e2e = build job:'end-to-end-tests', propagate: false\n        result = e2e.result\n        if (result.equals(\"SUCCESS\")) {\n        } else {\n          sh \"exit 1\" // this fails the stage\n        }\n    }\n  }\n } catch (e) {\n  result = \"FAIL\" // make sure other exceptions are recorded as failure too\n    }\n\nstage('deploy') {\n  if (result.equals(\"SUCCESS\")) {\n    build 'deploy'\n    } else {\n       echo \"Cannot deploy without successful build\" // it is important to have a deploy stage even here for the current visualization\n    }\n}\n"
  },
  {
    "path": "kill-queued-jenkins.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: kill-queued-jenkins.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-07 09:53:48>\n//-------------------------------------------------------------------\n// https://gist.github.com/realityforge/c57eb3d1854320d14252ac881fc6cedf\nimport hudson.model.*\n\ndef q = Jenkins.instance.queue\n\nq.items.each {\n  if (it =~ /deploy-to/) {\n    q.cancel(it.task)\n  }\n}\n\n"
  },
  {
    "path": "list-all-jenkins-agent.sh",
    "content": "#!/usr/bin/env bash\n##  @copyright 2019 DennyZhang.com\n## Licensed under MIT \n##   https://www.dennyzhang.com/wp-content/mit_license.txt\n##\n## File: list-all-jenkins-agent.sh\n## Author : Denny <https://www.dennyzhang.com/contact>\n## Description : List all trouble shooting traces for each Jenkins agent\n## --\n## Created : <2019-08-30>\n## Updated: Time-stamp: <2019-08-30 14:41:22>\n##-------------------------------------------------------------------\n#!/usr/bin/env bash\n# set -o errexit\nset -o pipefail\nset -o nounset\n\njenkins_url=${1?}\njenkins_credential=${2?}\nvm_user=${3?}\nvm_pass=${4?}\nfor agent_name in $(curl \"$jenkins_url/computer/api/json\" | jq -r .computer[].displayName | grep -v master); do\n    ip=$(curl -u \"$jenkins_credential\" -d \"script=println InetAddress.localHost.hostAddress\" \\\n              \"$jenkins_url/computer/$agent_name/scriptText\" 2>/dev/null | sed -e 's/^[ \\t]*//' | sed -e '/^$/d')\n    echo \"agent_name: $agent_name, ip: $ip\"\n    for command in \"cat /proc/loadavg\" \"docker version | grep '^ Version:'\" \"df -h /var/lib\"; do\n        sshpass -p \"$vm_pass\" ssh -o LogLevel=error -o StrictHostKeyChecking=no \"$vm_user@$ip\" \"$command\"\n    done\ndone\n\n"
  },
  {
    "path": "list-all-jobs.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: list-all-jobs.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-07 14:14:04>\n//-------------------------------------------------------------------\n// http://paweloczadly.github.io/dev/2014/07/03/jenkins-groovy-script-list-all-jobs\nimport hudson.model.*\n\nhudson.model.Hudson.instance.items.findAll{job -> job}.each {\n    job -> println(\"Job: \" + job.name)\n}\n"
  },
  {
    "path": "logged-in-users.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: logged-in-users.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:53:03>\n//-------------------------------------------------------------------\n// https://gist.github.com/hayderimran7/50cb1244cc1e856873a4\nimport jenkins.model.*\nimport hudson.security.*\n\ndef instance = Jenkins.getInstance()\n\n// logged-in users can do anything\ndef strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()\nstrategy.setAllowAnonymousRead(false)\ninstance.setAuthorizationStrategy(strategy)\n\ninstance.save()\n"
  },
  {
    "path": "loop-map.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: loop-map.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:42:59>\n//-------------------------------------------------------------------\ndef sampleMap = ['Key#1':'Value#1', 'Key#2':'Value#2']\nprintln sampleMap['Key#1']\nnode{\n    // itertate over stages\n    for (key in sampleMap.keySet()){\n        val = \"${sampleMap[key]}\"\n        println key\n        println val\n        stage('Run Key'){\n            println \"Ran ${key}\"\n        }\n\n        stage('Ran Value for that Key'){\n            println \"Ran ${val}\"\n        }\n\n        stage('Clean Up'){\n            println \"Ran Some sort of Cleanup\"\n        }\n    }\n}\n"
  },
  {
    "path": "manage-jenkins-jobs.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: manage-jenkins-jobs.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:53:08>\n//-------------------------------------------------------------------\n// https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-job.groovy\n// Adds a pipeline job to jenkins\nimport jenkins.model.Jenkins\nimport org.jenkinsci.plugins.workflow.job.WorkflowJob\nimport org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition\nimport org.jenkinsci.plugins.workflow.flow.FlowDefinition\nimport hudson.plugins.git.GitSCM\nimport hudson.plugins.git.UserRemoteConfig\nimport com.cloudbees.hudson.plugins.folder.*\n\n// Bring some values in from ansible using the jenkins_script modules wierd \"args\" approach (these are not gstrings)\nString folderName = \"$folderName\"\nString jobName = \"$jobName\"\nString jobScript = \"$jobScript\"\nString gitRepo = \"$gitRepo\"\nString gitRepoName = \"$gitRepoName\"\nString credentialsId = \"$credentialsId\"\n\nJenkins jenkins = Jenkins.instance // saves some typing\n\n// Get the folder where this job should be\ndef folder = jenkins.getItem(folderName)\n// Create the folder if it doesn't exist\nif (folder == null) {\n  folder = jenkins.createProject(Folder.class, folderName)\n}\n\n// Create the git configuration\nUserRemoteConfig userRemoteConfig = new UserRemoteConfig(gitRepo, gitRepoName, null, credentialsId)\n\nbranches = null\ndoGenerateSubmoduleConfigurations = false\nsubmoduleCfg = null\nbrowser = null\ngitTool = null\nextensions = []\nGitSCM scm = new GitSCM([userRemoteConfig], branches, doGenerateSubmoduleConfigurations, submoduleCfg, browser, gitTool, extensions)\n\n// Create the workflow\nFlowDefinition flowDefinition = (FlowDefinition) new CpsScmFlowDefinition(scm, jobScript)\n\n// Check if the job already exists\nObject job = null\njob = folder.getItem(jobName)\nif (job == null) {\n  oldJob = jenkins.getItem(jobName)\n  if (oldJob.getClass() == WorkflowJob.class) {\n    // Move any existing job into the folder\n    Items.move(oldJob, folder)\n  } else {\n    // Create it if it doesn't\n    job = folder.createProject(WorkflowJob, jobName)\n  }\n}\n// Add the workflow to the job\njob.setDefinition(flowDefinition)\n\n// Set the branch somehow\njob.save()\n"
  },
  {
    "path": "master-executors.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: master-executors.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:53:12>\n//-------------------------------------------------------------------\n\nimport hudson.model.*;\nimport jenkins.model.*;\n\nJenkins.instance.setNumExecutors(6)\n"
  },
  {
    "path": "matrix-authorization-strategy.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: matrix-authorization-strategy.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:53:20>\n//-------------------------------------------------------------------\n// http://www.tothenew.com/blog/jenkins-implementing-project-based-matrix-authorization-strategy/\n/*\n   Configure matrix authorization strategy with permissions for users and\n   groups.  This script is idempotent and will only change configuration if\n   necessary.\n\n   Example configuration:\n       authz_strategy_config = [\n           strategy: 'GlobalMatrixAuthorizationStrategy',\n           user_permissions: [\n               anonymous: ['Job Discover'],\n               authenticated: ['Overall Read', 'Job Read', 'View Read'],\n               admin: ['Overall Administer']\n           ]\n       ]\n\n   Available Authorization Strategies:\n       GlobalMatrixAuthorizationStrategy\n       ProjectMatrixAuthorizationStrategy\n\n   Available user permissions:\n       Overall Administer\n       Overall Read\n       Agent Configure\n       Agent Delete\n       Agent Create\n       Agent Disconnect\n       Agent Connect\n       Agent Build\n       Agent Provision\n       Run Delete\n       Run Update\n       Job Create\n       Job Delete\n       Job Configure\n       Job Read\n       Job Discover\n       Job Build\n       Job Workspace\n       Job Cancel\n       SCM Tag\n       Credentials Create\n       Credentials Update\n       Credentials View\n       Credentials Delete\n       Credentials ManageDomains\n       Job Move\n       View Create\n       View Delete\n       View Configure\n       View Read\n       Run Replay\n\n   \"Job ViewStatus\" permission becomes available after installing the\n   embeddable build status plugin.\n */\nimport jenkins.model.*\n\nimport hudson.security.GlobalMatrixAuthorizationStrategy\nimport hudson.security.Permission\nimport hudson.security.ProjectMatrixAuthorizationStrategy\nimport jenkins.model.Jenkins\n\nclass Helper implements Serializable {\n   static String shortName(Permission p) {\n      p.id.tokenize('.')[-2..-1].join(' ')\n\t .replace('Hudson','Overall')\n\t .replace('Computer', 'Agent')\n\t .replace('Item', 'Job')\n\t .replace('CredentialsProvider', 'Credentials')\n   }\n\n   static Map getCurrentPermissions(Map config = [:]) {\n      Map currentPermissions = [:].withDefault { [].toSet() }\n      if(!('getGrantedPermissions' in Jenkins.instance.authorizationStrategy.metaClass.methods*.name.sort().unique())) {\n\t return currentPermissions\n      }\n      Closure merger = { Map nmap, Map m ->\n\t m.each { k, v ->\n\t    nmap[k] += v\n\t }\n      }\n      Jenkins.instance.authorizationStrategy.grantedPermissions.collect { permission, userList ->\n\t userList.collect { user ->\n\t    [ (user): shortName(permission) ]\n\t }\n      }.flatten().each merger.curry(currentPermissions)\n      currentPermissions\n   }\n\n   static boolean isConfigurationEqual(Map config) {\n      Map currentPermissions = getCurrentPermissions(config)\n      Jenkins.instance.authorizationStrategy.class.name.endsWith(config['strategy']) &&\n      !(false in config['user_permissions'].collect { k, v -> currentPermissions[k] == v.toSet() }) &&\n      currentPermissions.keySet() == config['user_permissions'].keySet()\n   }\n\n   static boolean isValidConfig(def config, List<String> validPermissions) {\n      Map currentPermissions = getCurrentPermissions()\n      config instanceof Map &&\n      config.keySet().containsAll(['strategy', 'user_permissions']) &&\n      config['strategy'] &&\n      config['strategy'] instanceof String &&\n      config['strategy'] in ['GlobalMatrixAuthorizationStrategy', 'ProjectMatrixAuthorizationStrategy'] &&\n      config['user_permissions'] &&\n      !(false in config['user_permissions'].collect { k, v ->\n\t k instanceof String &&\n\t (v instanceof List || v instanceof Set) &&\n\t !(false in v.collect {\n\t    validPermissions.contains(it)\n\t })\n      })\n   }\n}\n\nMap<String, Permission> permissionIds = Permission.all.findAll { permission ->\n   List<String> nonConfigurablePerms = ['RunScripts', 'UploadPlugins', 'ConfigureUpdateCenter']\n   permission.enabled &&\n      !permission.id.startsWith('hudson.security.Permission') &&\n      !(true in nonConfigurablePerms.collect { permission.id.endsWith(it) })\n}.collect { permission ->\n   [ (Helper.shortName(permission)): permission ]\n}.sum()\n\n/**\n * MAIN EXECUTION\n */\n\nif(!binding.hasVariable('authz_strategy_config')) {\n   authz_strategy_config = [\n      strategy: 'GlobalMatrixAuthorizationStrategy',\n      user_permissions: [\n\t 'authenticated': ['Overall Read'],\n\t 'zdenny': ['Overall Administer']\n      ]\n   ]\n}\n\nif(!Helper.isValidConfig(authz_strategy_config, permissionIds.keySet().toList())) {\n   println([\n      'Skip configuring matrix authorization strategy because no valid config was provided.',\n      'Available Authorization Strategies:\\n    GlobalMatrixAuthorizationStrategy\\n    ProjectMatrixAuthorizationStrategy',\n      \"Available Permissions:\\n    ${permissionIds.keySet().join('\\n    ')}\"\n   ].join('\\n'))\n   return\n}\n\nif(Helper.isConfigurationEqual(authz_strategy_config)) {\n   println \"Nothing changed.  ${authz_strategy_config['strategy']} authorization strategy already configured.\"\n   return\n}\n\nprintln \"Configuring authorization strategy ${authz_strategy_config['strategy']}\"\n\ndef authz_strategy = Class.forName(\"hudson.security.${authz_strategy_config['strategy']}\").newInstance()\n\n// build the permissions in the strategy\nauthz_strategy_config['user_permissions'].each { user, permissions ->\n   permissions.each { p ->\n      authz_strategy.add(permissionIds[p], user)\n      println \"    For user ${user} grant permission ${p}.\"\n   }\n}\n\n// configure global authorization\nJenkins.instance.authorizationStrategy = authz_strategy\n\n// save settings to persist across restarts\nJenkins.instance.save()\n"
  },
  {
    "path": "multi-line-string.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: multi-line-string.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:43:06>\n//-------------------------------------------------------------------\n// http://grails.asia/groovy-multiline-string\ndef a = \"\"\"test\ntest\ntest\"\"\"\n"
  },
  {
    "path": "print.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: print.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:43:08>\n//-------------------------------------------------------------------\nString message = 'Hello from Groovy'\nprintln message\n"
  },
  {
    "path": "regexp-match.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: regexp-match.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 16:53:27>\n//-------------------------------------------------------------------\n// https://gist.github.com/EwanDawson/2407215\nmatcher = \"Hello world v1.01\" =~ /.* v(\\S*)/\nif (matcher.matches()) version = matcher[0][1]\nassert version == \"1.01\"\n\n// We can make this a little tidier using the 'with' method\nversion = (\"Hello world v1.01\" =~ /.* v(\\S*)/).with { matches() ? it[0][1] : null }\nassert version == \"1.01\"\n"
  },
  {
    "path": "relative-path.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: relative-path.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-01 13:55:52>\n//-------------------------------------------------------------------\n// https://gist.github.com/ysb33r/5804364\ndef root= new File('/usr/share')\ndef full= new File('/usr/share/docs/rpm-4.4')\n\n// Print the relative path of 'full' in relation to 'root'\n// Notice that the full path is passed as a parameter to the root.\ndef relPath= new File( root.toURI().relativize( full.toURI() ).toString() )\n"
  },
  {
    "path": "set-agent-env.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: set-agent-env.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-07 14:07:50>\n//-------------------------------------------------------------------\n// http://paweloczadly.github.io/dev/2014/07/03/jenkins-groovy-script-set-up-java_home-on-each-agent\nimport hudson.slaves.*\n\ndef javaHome = new EnvironmentVariablesNodeProperty(\n    new EnvironmentVariablesNodeProperty.Entry('JAVA_HOME', '/usr/lib/jvm/java-7-oracle-amd64'))\n\nhudson.model.Hudson.instance.slaves.each { it.nodeProperties.add(javaHome) }    \n"
  },
  {
    "path": "slack-notification.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: slack_notification.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Description :\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:44:34>\n//-------------------------------------------------------------------\n// https://stackoverflow.com/questions/39140191/how-to-send-slack-notification-after-jenkins-pipeline-build-failed\n// https://jenkins.io/doc/pipeline/steps/slack/\n// https://jenkins.io/blog/2016/07/18/pipeline-notifications/\nnode(agent_label) {\n   \n   //println testsuites\n   stage('Preparation') {\n      git (branch: 'master',\n           credentialsId: 'github_key',\n           url: 'git@github.com:DennyZhang/fake.git')\n      if (run_deployment_before_test == \"true\") {\n          build job:'DeploySandboxEnv', \n              parameters:[string(name:'initialize_system', value:initialize_system),\n                          string(name:'whether_populatefakedata', value:whether_populatefakedata),\n                          string(name:'whether_populaterealdata', value:whether_populaterealdata)]\n      }\n   }\n   \n   \n  def tc_list = testsuites.tokenize(',')\n     tc_list.each {\n        try {\n            stage(\"${it}\") {\n               println \"============ Test ${it}\"\n               sh \"mvn com.smartbear.soapui:soapui-maven-plugin:5.1.2:test -Dmdm.test.suite=\\\"${it}\\\"\"\n            }\n        } catch (e) {\n            result = \"FAIL\"\n        }\n   }\n\n  stage('CollectResult') {\n      if (result == \"FAIL\") {\n         buildStatus = result\n         def subject = \"${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'\"\n         def summary = \"${subject} (${env.BUILD_URL})\"\n         color = 'RED'\n         colorCode = '#FF0000'\n         slackSend (color: colorCode, message: summary)\n         error(\"Job has failed\")\n      }\n  }\n}\n"
  },
  {
    "path": "split-string.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: split-string.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:43:13>\n//-------------------------------------------------------------------\nString ip_hostname_list = \"\"\" 138.197.192.172  myenv-do-jenkins\n   138.68.254.56  myenv-do-lb-1\n  138.68.254.215  myenv-do-lb-2\n   165.227.8.194  myenv-do-cb-01\n  138.197.215.93  myenv-do-cb-02   \"\"\";\n\ndef l = ip_hostname_list.split(\"\\n\")\nprint l.join(\"a\")\n"
  },
  {
    "path": "string-to-json.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: string-to-json.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-04-29 15:43:15>\n//-------------------------------------------------------------------\nimport groovy.json.JsonSlurper\ndef jsonSlurper = new JsonSlurper()\ndef object = jsonSlurper.parseText('{ \"name\": \"John Doe\" } /* some comment */')\nassert object instanceof Map\nassert object.name == 'John Doe'\nprint object.name\n"
  },
  {
    "path": "timezone.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: timezone.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-02-16 22:04:03>\n//-------------------------------------------------------------------\n// Configure Jenkins java options\n// timezone: Asia/Shanghai, America/New_York, America/Los_Angeles\n// https://www.epochconverter.com/timezones\n// ENV JENKINS_TIMEZONE \"UTC\"\n\ndef env = System.getenv();\nSystem.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', env['JENKINS_TIMEZONE']);\n"
  },
  {
    "path": "validate-kubernetes-cloud.groovy",
    "content": "#!groovy\n//-------------------------------------------------------------------\n// @copyright 2018 DennyZhang.com\n// Licensed under MIT\n// https://www.dennyzhang.com/wp-content/mit_license.txt\n//\n// File: jenkins-kubernetes-cloud.groovy\n// Author : Denny <https://www.dennyzhang.com/contact>\n// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4\n// --\n// Created : <2018-04-20>\n// Updated: Time-stamp: <2019-05-23 22:30:46>\n//-------------------------------------------------------------------\n// https://github.com/carlossg/jenkins-kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java\nimport org.csanchez.jenkins.plugins.kubernetes.*\nimport jenkins.model.*\nimport io.fabric8.kubernetes.client.KubernetesClient;\nimport io.fabric8.kubernetes.client.KubernetesClientException;\ntry {\n    def j = Jenkins.getInstance()\n        def client = j.clouds[0].connect()\n        client.pods().list();\n} catch (KubernetesClientException e) {\n    println(\"Error testing connection %s\" + e.getMessage())\n} catch (Exception e) {\n    println(\"Error testing connection %s\" + e.getMessage())\n}\n"
  }
]