首页 > 解决方案 > gitlab CI不同的SSL密钥用于不同的服务器部署,如何?

问题描述

我有一个包含以下内容的 gitlab-ci.yml:

before_script:
    # Setup SSH deploy keys
    - which ssh-agent || ( apt-get install -qq openssh-client )
    - eval $(ssh-agent -s)
    - bash -c 'ssh-add <(echo "$KEY1")'
    - bash -c 'ssh-add <(echo "$KEY2")'
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan ec2-xxx-xxx-xxx-xx1.eu-west-2.compute.amazonaws.com >> ~/.ssh/known_hosts
    - ssh-keyscan ec2-xx-xxx-xxx-xx2.eu-west-2.compute.amazonaws.com >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

// more stuff that tests the code

staging:
    type: deploy
    script:
        - shell/deploy_s_staging_ci.sh
    only:
        - tags
            - s_staging

我的环境存储了 $KEY1 和 $KEY2。

我的本地部署 shell 脚本的最后一行是这样的:

scp -v -i "~/.ssh/example.pem" s_etl_deploy.tgz  \
ec2-user@ec2-xxx-xxx-xxx-xxx.eu-west-2.compute.amazonaws.com:/home/ec2-user/etl/

这如何改变以在 gitlb CI docker runner 中获取特定的 SSL 密钥,比如说 KEY1,以便在 scp 命令中使用它?

标签: gitlab-cigitlab-ci-runner

解决方案


您可能应该可以在两个键之间进行选择。例如,使用变量允许实现该目标。

.use_ssh_key:
  before_script:
    # Setup SSH deploy keys
    - which ssh-agent || ( apt-get install -qq openssh-client )
    - eval $(ssh-agent -s)
    - bash -c 'ssh-add <(echo "$KEY_TO_USE")'
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan ec2-xxx-xxx-xxx-xx1.eu-west-2.compute.amazonaws.com >> ~/.ssh/known_hosts
    - ssh-keyscan ec2-xx-xxx-xxx-xx2.eu-west-2.compute.amazonaws.com >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

// more stuff that tests the code

staging:
  extends: .use_ssh_key
  variables:
    KEY_TO_USE: $KEY1
  type: deploy
  script:
    - shell/deploy_s_staging_ci.sh
  only:
    - tags
        - s_staging

然后您可以扩展该配置,并根据您的工作定义 KEY_TO_USE。


推荐阅读