Problem Statement
Explain Declarative Pipeline syntax in detail. Include agent, stages, steps, post actions, and environment variables with examples.
Explanation
Declarative Pipeline uses structured syntax starting with pipeline block as the root. Agent directive specifies where pipeline or stage executes: agent any runs on any available agent, agent { label 'linux' } runs on agents with 'linux' label, agent none means no global agent (define per stage), agent { docker 'maven:3.8.1' } runs in Docker container. Agent can be defined globally for entire pipeline or per stage for flexibility.
Stages and steps structure the pipeline. Stages block contains multiple stage blocks representing phases of the pipeline (Build, Test, Deploy). Each stage contains steps block with actual commands: sh for shell commands (Unix), bat for Windows batch commands, script for embedded Groovy code. Example:
```groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
}
}
```
Environment variables defined at pipeline level (global) or stage level (local to stage). Use environment block: environment { JAVA_HOME = '/usr/lib/jvm/java-11' }. Access with ${env.VARIABLE} or $VARIABLE. Credentials injected as environment variables using credentials() function: environment { API_KEY = credentials('api-key-id') }.
Post section defines actions after stage or pipeline completes based on status. Conditions include always (always run), success (only if successful), failure (only if failed), unstable (tests failed but build passed), changed (status changed from previous run). Example:
```groovy
post {
success {
echo 'Pipeline succeeded!'
slackSend message: 'Build successful'
}
failure {
echo 'Pipeline failed!'
mail to: 'team@example.com', subject: 'Build Failed'
}
always {
junit '**/target/test-results/*.xml'
cleanWs()
}
}
```
Other directives include options (pipeline-level settings like timestamps, timeout), parameters (build parameters for parameterized builds), triggers (build triggers like cron, pollSCM), tools (automatic tool installation like Maven, JDK), when (conditional stage execution). Understanding Declarative syntax enables writing maintainable, readable pipelines.