skip to Main Content

I have created a stage in GitLab to build a container only if Dockerfile in repository is modified, but it runs every time I run the pipeline manually, following is the code in .gitlab-ci.yml.

stages:
    - build_base_container
    - build

build_base_container:
  stage: build_base_container
  image: docker:latest
  services:
    - docker:dind

  script:
    - |
      docker login registry.gitlab.com -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD}
      docker build -t $CI_REGISTRY_IMAGE .      
      docker push $CI_REGISTRY_IMAGE
      docker logout ${CI_REGISTRY_PASSWORD}
  rules:
    - changes: 
      - dockerfile

This stage should only run if Dockerfile is modified not in any other condition.

2

Answers


  1. Chosen as BEST ANSWER

    Found a simple solution as mentioned below.

    rules:
        - if: $CI_PIPELINE_SOURCE == "push"
          changes:
            - dockerfile
          when: always
    

    Now it run only if there is a push event which was exactly my requirement.


  2. This is a known behavior as mentioned in the doc: https://docs.gitlab.com/ee/ci/yaml/index.html#ruleschanges

    A manual pipeline is not a push event, which means your rule will always evaluate to true when running a new pipeline manually.

    Maybe you can consider running this pipeline on a tag?

    buld_base_container:
      only:
        refs:
          - tags
    

    Or with the rules syntax:

    buld_base_container:
      rules:
        - if: '$CI_COMMIT_TAG =~ /^v.+/'
          when: on_success
    

    You can then add a tag to the commit you change the Dockerfile:

    git tag v1.0.0
    git push --tags
    

    With a tag, you can also tag your image instead of using latest each time.

    Hope it helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search