GitLabCiPushingWrites

6th September 2017 at 2:16pm
.gitlab-ci.yml Git GitLab

This example .gitlab-ci.yml configuration runs a single job (README.md).

It executes a simple Perl script yaml2mdtable.pl, which reads an input YAML file foobar.yaml to autogenerate the README.md markdown file.

It then commits and pushes this change back to the GitLab repository.

An SSH private key is defined as a secret variable through the Settings > CI/CD Pipelines web interface in GitLab, and the public part of the SSH key is stored as a deployment key Settings > Repository > Deploy Keys section of the same web UI.

---

variables:
  # Debug and tracing.
  #CI_DEBUG_TRACE: "true"
  #GIT_CURL_VERBOSE: "1"
  #GIT_DEBUG_LOOKUP: "1"
  #GIT_TRACE: "1"
  #GIT_TRACE_PACKET: "1"
  #GIT_TRANSLOOP_DEBUG: "1"
  #GIT_TRANSPORT_HELPER_DEBUG: "1"

  # ssh_deploy_key is defined under Settings > CI/CD Pipelines > Secret Variables.
  temporary_branch: "gitlab-ci-README.md"
  GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no -i .ssh/id_rsa-gitlab-ci"

  # Clone rather than fetch so we have a completely clean workspace without
  # any previous temporary_branch left over from past CI runs.
  GIT_STRATEGY: clone

# Push autogenerated changes back to the repository.
# See https://gitlab.com/gitlab-org/gitlab-ce/issues/18106 for example and
# discussion on how this is achieved.

README.md:
  image: perl:latest
  stage: build

  before_script:
    # Install YAML module for yaml2mdtable.pl script.
    - curl -sSL http://cpanmin.us | perl - App::cpanminus
    - cpanm YAML

  script:
    # Prepare git for pushing back to repository.
    - mkdir -pvm 0700 .ssh
    - echo "$ssh_deploy_key" > .ssh/id_rsa-gitlab-ci
    - chmod 0400 .ssh/id_rsa-gitlab-ci
    - git checkout -b "$temporary_branch"
    - git config --global user.email $(git --no-pager show -s --format='%ae' HEAD)
    - git config --global user.name $(git --no-pager show -s --format='%an' HEAD)
    - git remote set-url --push origin $(perl -pe 's#.*@(.+?(\:\d+)?)/#git@\1:#' <<< $CI_REPOSITORY_URL)

    # Generate README.md from YAML file.
    - ./yaml2mdtable.pl -i foobar.yaml -o README.md

    # Push modified README.md back to repository. (Always return true even
    # if there are no changes to commit and push).
    - git commit -m "Autogenerated markdown represenation of foobar.yaml at revision $CI_COMMIT_SHA [skip ci]" README.md || true
    - git push origin "$temporary_branch:$CI_COMMIT_REF_NAME" || true

  after_script:
    - rm -Rfv .ssh