Search code examples
gitlab-ci

Assign a File Variable a value from CI/CD Variable


I have a Gitlab Pipelin that establish a SSH connection to a Server. For that purpose I created a CI/CD file variable containing the SSH_KEY, which works perfectly.

Now we have additional requirement to connect to other servers, which are using other SSH keys, so I don't want to rewrite the whole code again for every server, so I though I can give at the start of the pipeline which Server to connect, then it should use dedicated ssh key, like SSH_KEY_1, SSH_KEY_2, etc from CI / CD variables.

So it will look like the following,

deploy:
  stage: deploy
  before_script:    
    - 'chmod 600 $SSH_KEY'
  script:
    - 'ssh -o StrictHostKeyChecking=no -i ${SSH_KEY} -l user 10.x.x.x "ls -al"'

and when I trigger the pipeline, I would configure SSH_KEY to be SSH_KEY_1, so like

SSH_KEY=$SSH_KEY_1

but it seems Gitlab has disabled the feature of assigning file variables to other file variables...

https://about.gitlab.com/blog/2023/02/13/impact-of-the-file-type-variable-change-15-7/

Then I though, may be I can give name of the Key instead of a variable and Gitlab can evaluate that

SSH_KEY = 'SSH_KEY_1'

but I can't make that work also.

I can understand their security concerns but I don't want to produce the same code 100 times, if I have to connect 100 different Servers with SSH.

May be there is an obvious solution but I can't see it, any suggestions?


Solution

  • The feature is not disabled. The only difference is that, instead of copying the value of the file variable to the other variable, it will copy the path. Therefore, the problem is the way you trigger the pipeline (manual, api, etc.). Having more info about that can help to resolve the issue. But there are two simple solutions.

    • You can use variable value as another variable name (your second solution), therefore in the pipeline, you set SSH_KEY = 'SSH_KEY_1' and then in your file, you have:

       deploy:
         stage: deploy
         before_script:
          | -
          export MY_SSH="${!SSH_KEY}"
          chmod 600 $MY_SSH
         script:
          - 'ssh -o StrictHostKeyChecking=no -i ${MY_SSH} -l user 10.x.x.x "ls -al"'
      
    • The easiest way is to add them all to ssh-agent:

      deploy:
        stage: deploy
        before_script:
         | -
         eval `ssh-agent`
         chmod 600 $SSH_KEY_1
         chmod 600 $SSH_KEY_2
         chmod 600 $SSH_KEY_3
         ssh-add ${SSH_KEY_1}
         ssh-add ${SSH_KEY_2}
         ssh-add ${SSH_KEY_3}
        script:
          - 'ssh -o StrictHostKeyChecking=no -l user 10.x.x.x "ls -al"'
      

    But note that it is not ideal way, since all the keys are tried on all the servers where you want are connecting. You can add the configuration of keys in ~/.ssh/config.