DevOps / GitLab CI Basics Interview Questions
What is the 'script', 'before_script', and 'after_script' keywords and how do they differ?
These three keywords define the shell commands that run during a job. They execute in sequence but have different scopes and failure behaviour.
| Keyword | When it runs | Fails the job if it fails? | Scope |
|---|---|---|---|
| before_script | Before the main script | Yes | Can be set globally or per-job |
| script | The job's main work | Yes | Per-job only (required) |
| after_script | After script (and before_script) | No (always runs) | Can be set globally or per-job |
# Global before_script runs before every job's script default: before_script: - echo "Global setup" build-job: stage: build before_script: - echo "Job-specific setup (overrides global)" # overrides the default script: - npm ci - npm run build after_script: - echo "Cleanup - always runs even if script fails"
Key behaviours:
before_scriptdefined in a job overrides (not appends to) the globalbefore_scriptafter_scriptruns in a separate shell context fromscript- environment variable changes made inscriptare not visible inafter_scriptafter_scriptruns even when the job fails or times out, making it ideal for cleanup tasks
More Related questions...