Gitlab Pipeline – environment – What is environment in GitLab CI/CD?

DevOps

MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

The environment keyword in a GitLab CI/CD job definition is used to define and track deployments to specific named environments (like staging, production, or dynamic review environments). It helps you visualize your deployment history, access deployed applications, and manage the lifecycle of these environments.


Example .gitlab-ci.yml with environment:

YAML

# .gitlab-ci.yml

stages:
  - build
  - deploy_review
  - stop_review
  - deploy_staging
  - deploy_production
  - cleanup_staging

default:
  image: alpine:latest

# A simple build job (not directly using 'environment')
build_app:
  stage: build
  script:
    - echo "--- Building Application ---"
    - mkdir -p my_app_build/
    - echo "version_1.0" > my_app_build/app.txt
    - echo "Build complete."
  artifacts:
    paths:
      - my_app_build/
    expire_in: 1 hour

# Job 1: Deploy to a dynamic Review App environment
deploy_review_app:
  stage: deploy_review
  script:
    - echo "--- Deploying Review App for branch: $CI_COMMIT_REF_SLUG ---"
    - echo "App version from build: $(cat my_app_build/app.txt)"
    - echo "Deployed to https://$CI_COMMIT_REF_SLUG.example.com" # Simulate deployment
    - sleep 10
  environment:
    name: review/$CI_COMMIT_REF_SLUG # Dynamic environment name based on branch
    url: https://$CI_COMMIT_REF_SLUG.example.com # Dynamic URL for the review app
    on_stop: stop_review_app # Specifies a job to run when this environment is "stopped"
    auto_stop_in: 2 hours # Automatically triggers 'stop_review_app' after 2 hours of inactivity/age
  rules:
    - if: '$CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH && $CI_COMMIT_BRANCH != "staging"' # Run for feature branches

# Job 2: Stops the Review App environment
stop_review_app:
  stage: stop_review
  script:
    - echo "--- Stopping Review App for branch: $CI_COMMIT_REF_SLUG ---"
    - echo "Cleaning up resources for https://$CI_COMMIT_REF_SLUG.example.com"
  environment:
    name: review/$CI_COMMIT_REF_SLUG # Must match the environment name to stop
    action: stop # This action marks the environment as stopped
  when: manual # Usually, stop jobs are manual or triggered by 'on_stop' or 'auto_stop_in'
  rules:
    - if: '$CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH && $CI_COMMIT_BRANCH != "staging"'

# Job 3: Deploy to Staging environment
deploy_to_staging:
  stage: deploy_staging
  script:
    - echo "--- Deploying to Staging Environment ---"
    - echo "App version from build: $(cat my_app_build/app.txt)"
    - echo "Deployed to https://staging.example.com"
    - sleep 10
  environment:
    name: staging
    url: https://staging.example.com
    # on_stop: stop_staging # You could define a 'stop_staging' job similarly if needed
  rules:
    - if: '$CI_COMMIT_BRANCH == "staging"' # Example: run only for 'staging' branch

# Job 4: Deploy to Production environment (often manual)
deploy_to_production:
  stage: deploy_production
  script:
    - echo "--- Deploying to Production Environment ---"
    - echo "App version from build: $(cat my_app_build/app.txt)"
    - echo "Deployed to https://production.example.com"
    - sleep 15
  environment:
    name: production
    url: https://production.example.com
  when: manual # Production deployments are often manual for control
  rules:
    - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' # Run only for the default branch (e.g., main)

Code language: PHP (php)

Explanation:

  1. environment: Keyword:
    • Used within a job’s definition to declare that this job performs a deployment to a specific environment.
    • It takes a map of sub-keys.
  2. deploy_review_app Job (Dynamic Environment):
    • environment::
      • name: review/$CI_COMMIT_REF_SLUG:
        • (Required) This is the unique name of the environment. Using predefined CI/CD variables like $CI_COMMIT_REF_SLUG (the branch or tag name in a URL-friendly format) allows you to create dynamic environment names. This is very common for “Review Apps” where each feature branch gets its own temporary deployment environment.
      • url: https://$CI_COMMIT_REF_SLUG.example.com:
        • (Optional) A publicly accessible URL for this environment. GitLab will display this URL on the Environments page, merge requests, etc., making it easy to access the deployed application.
      • on_stop: stop_review_app:
        • (Optional) Specifies the name of another job (stop_review_app in this case) that should be run when this environment is “stopped.” An environment can be stopped manually from the GitLab UI, or automatically (e.g., when a branch is deleted, or via auto_stop_in).
      • auto_stop_in: 2 hours:
        • (Optional) If this environment is not re-deployed within “2 hours”, GitLab will automatically trigger the job specified in on_stop (if defined) or simply mark the environment as stopped. This is great for cleaning up temporary review environments.
    • rules:: This job is configured to run only for feature branches (not the default branch or staging), which is typical for review apps.
  3. stop_review_app Job (Stopping an Environment):
    • environment::
      • name: review/$CI_COMMIT_REF_SLUG: This must match the name of the environment that this job is intended to stop.
      • action: stop: This tells GitLab that this job’s purpose is to stop the specified environment. When this job runs successfully, GitLab updates the environment’s status to “stopped.”
    • when: manual: Stop jobs are often manual, allowing users to decide when to tear down an environment. However, they can also be triggered automatically by on_stop from the deployment job or by branch deletion if configured.
  4. deploy_to_staging and deploy_to_production Jobs (Static Environments):
    • These jobs deploy to well-known, static environments (staging and production).
    • name: staging / name: production: Static names.
    • url: Static URLs for these environments.
    • when: manual (for production): It’s a common safety measure to make production deployments a manual step, requiring explicit user action.

Key Concepts and Benefits:

  • Deployment Tracking: GitLab keeps a record of all deployments to each environment. You can see this under Operate > Environments in your project. This includes when each deployment happened, by whom, and the commit SHA.
  • Rollbacks and Re-deploys: From the Environments page, you can easily re-deploy a previous successful deployment to an environment (effectively a rollback if the previous deployment was an older version) or re-run the latest deployment job.
  • Environment-Specific Variables: You can define CI/CD variables in GitLab (Settings > CI/CD > Variables) and scope them to specific environments. This allows you to have different configurations (e.g., database URLs, API keys) for staging vs. production without hardcoding them in your .gitlab-ci.yml.
  • Protected Environments: Production environments can be “protected,” limiting who can deploy to them and which branches/tags can be deployed.
  • Review Apps: Dynamic environments (like review/$CI_COMMIT_REF_SLUG) are a powerful feature for previewing changes from feature branches before merging them.
  • Cleanup (on_stop, action: stop, auto_stop_in): These features help manage the lifecycle of temporary environments, ensuring resources are cleaned up.
  • Visualizations: The environment URL is shown in merge requests if a review app is deployed, making it easy for reviewers to access and test the changes.

Using the environment keyword provides significant benefits for managing and visualizing your deployment processes, making your CI/CD pipeline more robust and transparent.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x