1

Although it seems counterintuitive, I would like to execute an always statement when a conditional is met. In my pipeline, my post statement should always destroy my AWS CloudFormation Stack if a variable is set to true. Below is the post statement which is not correct.

post{
    always {
        when {
            expression { DeleteStack == 'true'}
        }
        stage("Delete All Stacks") {               
            steps {
                script {
                    withAWS(region:'us-west-2', credentials:'jenkins-deploy') {
                        def outputs = cfnDelete(
                            stack:"${CFTBatchStackName}", 
                            pollInterval:1000)
                    }
                    withAWS(region:'us-west-2', credentials:'jenkins-deploy') {
                        def outputs = cfnDelete(
                            stack:"${CFTVPCStackName}", 
                            pollInterval:1000)
                    }
                    withAWS(region:'us-west-2', credentials:'jenkins-deploy') {
                    def outputs = cfnDelete(
                        stack:"${CFTSelfDeleteName}", 
                        pollInterval:1000)
                    }
                }
            }
        }
    }
}

Can I achieve this using a declarative pipeline?

2 Answers 2

2

According to the documentation, the when directive is only allowed inside a stage. You have to use the script directive if you want to use conditional statements:

post {
  always {
    script {
      if (DeleteStack == 'true') {
        // Destroy what you want !
      }
    }
  }
}
0

I'm not aware of any way to do what you want with Declarative, but it certainly is possible with Scripted:

try {
  // your Pipeline code here
} finally {
  if (!DeleteStack) { return }

  [
    CFTBatchStackName,
    CFTVPCStackName,
    CFTSelfDeleteName,
  ].each { stack->
    withAWS(region:'us-west-2', credentials:'jenkins-deploy') {
      def outputs = cfnDelete(
        stack: stack,
        pollInterval: 1000,
      )
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.