Trigger pipeline whenever code is pushed to a specific branch

Problem:

Hello everyone, I’m working on constructing a pipeline that utilizes SSH keys and is branch-specific. I have two branches, namely ‘dev’ and ‘prod.’ Depending on the branch, I aim to deploy my application on a virtual machine using SSH commands. The pipeline runs successfully when no rules are added to a specific branch, but encounters failures when rules are applied to that branch.

  • Pipeline with rules

  • Pipeline without rules:

GitLab CI Configuration (.gitlab-ci.yaml):

image: ubuntu:latest

stages:
  - dev
  - prod

variables:
  PRIVATE_KEY: "$PRIVATE_KEY"

dev-environment:
  stage: dev
  variables:
    HOSTNAME: "DEV-IP-ADDRESS"
    USER_NAME: "dev"
  rules:
    - if: '$CI_COMMIT_BRANCH == "dev"'
      when: always
  script:
    - apt-get update -y
    - apt-get install openssh-client -y
    - echo -e "$PRIVATE_KEY" > private_key
    - chmod 600 private_key
    - ssh -o StrictHostKeyChecking=no -i private_key $USER_NAME@$HOSTNAME 'mkdir dev'

prod-environment:
  stage: prod
  variables:
    HOSTNAME: "PROD-IP-ADDRESS"
    USER_NAME: "prod"
  rules:
    - if: '$CI_COMMIT_BRANCH == "prod"'
      when: always
  script:
    - apt-get update -y
    - apt-get install openssh-client -y
    - echo -e "$PRIVATE_KEY" > private_key
    - chmod 600 private_key
    - ssh -o StrictHostKeyChecking=no -i private_key $USER_NAME@$HOSTNAME 'mkdir prod'

Hey there,

I would suggest checking your PRIVATE_KEY variable configuration. It could be it’s configured as Protected - which means it is available only on protected branches and not the other ones, which could be leading to error in loading it.

2 Likes

Thank you, Paula. Yes, the PRIVATE_KEY variable was configured as protected, which was causing the pipeline to fail.

2 Likes