laprof
laprof

Reputation: 1344

How to pull a docker container on AWS EC2 instance via gitlab-ci?

I wanna deploy a docker container with gitlab-ci to AWS EC2 via ssh, but I don't know how to login to the gitlab registry. I've already tried using CI_BUILD_TOKEN and I tried to login with a secret password variable, both didn't work.

So I can't login to the registry to pull the docker container from gitlab. How do I change the Docker login command to make the login successful?

image: docker:latest
...
deploy:
  stage: deploy
  script:
    - echo "$EC2_SSH_KEY" > "key.pem"
    - chmod 600 key.pem
    - apk update && apk add openssh
    - ssh -tt -i "key.pem" -o StrictHostKeyChecking=no [email protected] 'sudo docker login -u gitlab-ci-token -p "$CI_BUILD_TOKEN" $CI_REGISTRY'

Upvotes: 0

Views: 419

Answers (1)

Martin Löper
Martin Löper

Reputation: 6649

According to the Gitlab permission model guide [1], you are using the correct approach. However your quoting might prevent the shell from performing variable expansion.

GitLab provides a list of attributes in the .gitlab-ci.yml file and their corresponding variable expansion mechanism. The script definition which you are using has the expansion place set to Script execution shell [2]. Thus, the Execution shell environment section [3] of the doc applies. It states:

This is an expansion that takes place during the script execution. How it works depends on the used shell (bash/sh/cmd/PowerShell).

The correct formatting [4] of the last script line for most of the Unix shells should be:

ssh -tt -i "key.pem" -o StrictHostKeyChecking=no [email protected] "sudo docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY"

References

[1] https://docs.gitlab.com/ee/user/project/new_ci_build_permissions_model.html#container-registry
[2] https://docs.gitlab.com/ee/ci/variables/where_variables_can_be_used.html#gitlab-ciyml-file
[3] https://docs.gitlab.com/ee/ci/variables/where_variables_can_be_used.html#execution-shell-environment
[4] https://unix.stackexchange.com/questions/425561/shell-script-how-to-expand-a-variable-into-quotes

Upvotes: 2

Related Questions