| #!groovy |
| import io.jenkins.plugins.casc.ConfigurationAsCode |
| |
| @NonCPS |
| Boolean testConfig(String cascPath) { |
| def casc = ConfigurationAsCode.get() |
| def form |
| Boolean result = true |
| try { |
| form = casc.doCheckNewSource(cascPath) |
| } catch (Exception e) { |
| result = false |
| message = e.toString() |
| } finally { |
| if (form) { |
| println form.kind |
| println form.message.split('<')[0] |
| if (form.kind.toString() != 'OK') { |
| result = false |
| } |
| } |
| } |
| return result |
| } |
| |
| @NonCPS |
| void applyConfig(String cascPath) { |
| ConfigurationAsCode.get().configure(cascPath) |
| } |
| |
| node('master') { |
| Boolean doApply = false |
| String cascPath = env.WORKSPACE |
| |
| if (env.GERRIT_EVENT_TYPE == 'ref-updated') { |
| doApply = true |
| cascPath = ConfigurationAsCode.get().getStandardConfig()[0] ?: "${env.HOME}/casc" |
| } |
| |
| stage('SCM checkout') { |
| String refSpec = env.GERRIT_REFSPEC ?: env.GERRIT_REFNAME |
| String gitUrl = "ssh://${env.GERRIT_HOST}:${env.GERRIT_PORT}/${env.GERRIT_PROJECT}" |
| echo "Checking out git repository from ${env.GERRIT_PROJECT} @ ${refSpec}" |
| |
| dir(cascPath) { |
| checkout([ |
| $class: 'GitSCM', |
| branches: [[ |
| name: 'FETCH_HEAD', |
| ]], |
| userRemoteConfigs: [[ |
| url: gitUrl, |
| refspec: refSpec, |
| credentialsId: env.GIT_CREDENTIALS_ID, |
| ]], |
| extensions: [[ |
| $class: 'WipeWorkspace', |
| ]], |
| ]) |
| } |
| } |
| |
| stage('Test configuration') { |
| if (! testConfig(cascPath) ) { |
| currentBuild.result = 'FAILURE' |
| throw new RuntimeException ('Fail') |
| } |
| } |
| |
| if (doApply) { |
| stage('Apply configuration') { |
| applyConfig(cascPath) |
| } |
| } |
| } |