Template

Child Pipeline with Run Keyword

Use the run: keyword to define child pipelines inline, with parallel matrix strategies and OIDC identity tokens.

Best for monorepos with orthogonal build targets and child pipeline orchestration.

stages:
  - setup
  - build
  - test
  - deploy

variables:
  REGISTRY: registry.example.com

# Setup job that generates child pipeline config artifact
prepare_artifacts:
  stage: setup
  image: alpine:3.21
  script:
    - mkdir -p configs
    - |
      cat > configs/service-frontend.yml << 'YAML'
      stages:
        - build
        - test
      frontend_build:
        stage: build
        image: node:22-alpine
        script:
          - npm ci
          - npm run build -- --target frontend
        artifacts:
          paths:
            - dist/frontend/
      frontend_test:
        stage: test
        image: node:22-alpine
        needs:
          - frontend_build
        script:
          - npm run test -- --ci --coverage --target frontend
      YAML
    - |
      cat > configs/service-api.yml << 'YAML'
      stages:
        - build
        - test
      api_build:
        stage: build
        image: node:22-alpine
        script:
          - npm ci
          - npm run build -- --target api
        artifacts:
          paths:
            - dist/api/
      api_test:
        stage: test
        image: node:22-alpine
        needs:
          - api_build
        script:
          - npm run test -- --ci --coverage --target api
      YAML
  artifacts:
    paths:
      - configs/

# Run child pipelines using dynamically generated configs (GitLab 17.3+)
build_frontend:
  stage: build
  needs:
    - prepare_artifacts
  run:
    file: configs/service-frontend.yml

build_api:
  stage: build
  needs:
    - prepare_artifacts
  run:
    file: configs/service-api.yml

# Parallel matrix across child pipeline results
deploy_staging:
  stage: deploy
  image: alpine:3.21
  needs:
    - build_frontend
    - build_api
  id_tokens:
    OIDC_TOKEN:
      aud: https://staging.example.com
  variables:
    TARGETS: frontend api
  parallel:
    matrix:
      - SERVICE: frontend
        PORT: "3000"
      - SERVICE: api
        PORT: "4000"
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
  script:
    - echo "Deploying $SERVICE on port $PORT"
    - echo "Staging URL: https://$SERVICE.staging.example.com"
    - echo "Using OIDC token for authentication"
  environment:
    name: staging/$SERVICE
    url: https://$SERVICE.staging.example.com