
Module 2 Lesson 2: The .gitlab-ci.yml Structure
Master the syntax of automation. Learn the basic anatomy of a GitLab CI configuration file, including global settings, job definitions, and hidden keys.
Module 2 Lesson 2: The .gitlab-ci.yml Structure
The .gitlab-ci.yml file is the brain of your pipeline. If it has a typo, the pipeline dies. If it's well-structured, your life as a developer becomes 10x easier.
1. The Global Block
At the top of the file, you define settings that apply to every job in the pipeline.
# Use this image for every job unless specified otherwise
image: node:18
# Define the order of the phases
stages:
- build
- test
- deploy
# Define variables available to all scripts
variables:
DATABASE_URL: "postgres://prod:5432"
2. The Job Block
A "Job" is a list of commands that a Runner will execute.
# The name of the job
my-test-job:
stage: test # Which phase does it belong to?
image: python:3 # Override the global image
script:
- echo "Running tests..."
- pytest tests/
3. The "Hidden" Jobs (Extensions)
You can create a "Base" job that doesn't run, but can be copied by other jobs using the extends keyword. Use a . prefix to hide it.
.base-setup:
script:
- apt-get update
- apt-get install -y curl
job-1:
extends: .base-setup
script:
- !reference [.base-setup, script] # Run the base script first
- curl google.com
4. Why YAML?
YAML (Yet Another Markup Language) was chosen because it's human-readable. Unlike JSON, it doesn't have thousands of curly braces {}. However, YAML is whitespace-sensitive.
- 1 extra space can break your whole pipeline.
- Always use a "Linter" (Module 2, Lesson 5) before pushing.
Visualizing the YAML Structure
graph TD
Root[.gitlab-ci.yml] --> Global[Global Settings]
Root --> Jobs[Job Definitions]
Global --> Image[image: node:18]
Global --> Stages[stages: build, test, deploy]
Global --> Vars[variables: KEY=VALUE]
Jobs --> Job1[my-test-job]
Jobs --> Job2[build-job]
Jobs --> Hidden[.base-setup]
Job1 --> Stage1[stage: test]
Job1 --> Script1[script: commands]
Exercise: The Structure Audit
- Look at the Global Block in Section 1. If I add a job without a
stagekeyword, which stage will it run in by default? (Research: GitLab default stages). - Identify the 3 main parts of a Job Block.
- Why is it better to define
image: node:18at the top of the file rather than inside every single job? - Write a simple YAML block that defines a variable called
APP_NAMEwith the value"My Awesome App".
Summary
The .gitlab-ci.yml is your "Infrastructure as Code." By mastering its structure, you gain the power to define complex software delivery logic in a way that is readable, version-controlled, and easy for your teammates to understand.
Next Lesson: The building blocks: Jobs, stages, and scripts.