Reputation: 13
I'm trying to deploy my Docker Image to the server via GitLab CI. I have set variables inside yml file and I am connecting to my server via SSH. Is it possible to automatically use variables inside the yml file or do I have to pass them one by one to SSH?
also, I would like to know if there is a better way to deploy this other than my way.
deploy:
image: alpine
variables:
#this may be overridden by parent pipeline, or it will be latest
my_nginx: registry.gitlab.com/myprofile/nginx:latest
before_script:
- apk add openssh-client
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
script:
- scp -o StrictHostKeyChecking=no docker-compose.yml $HOST:~
- >
ssh -o StrictHostKeyChecking=no $HOST "
echo "$CI_JOB_TOKEN" | docker login -u "$CI_REGISTRY_USER" $CI_REGISTRY --password-stdin;
cd ~;
my_nginx=$my_nginx
docker-compose pull;
docker-compose up -d --remove-orphans;
docker image prune;"
services:
nginx:
container_name: my-nginx
image: $my_nginx
restart: unless-stopped
ports:
- 80:80
Upvotes: 1
Views: 1154
Reputation: 985
Docker out of the box can connect to a remote Docker Daemon using SSH. So no need to copy docker-compose.yaml
or forward environment variables.
All you need is to set the DOCKER_HOST
variable to point to the SSH uri of your remote docker daemon.
deploy:
image: alpine
variables:
#this may be overridden by parent pipeline, or it will be latest
my_nginx: registry.gitlab.com/myprofile/nginx:latest
DOCKER_HOST: ssh://$HOST # format is ssh://user@host
before_script:
- apk add openssh-client
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
script:
- echo "$CI_JOB_TOKEN" | docker login -u "$CI_REGISTRY_USER" $CI_REGISTRY --password-stdin;
docker-compose pull;
docker-compose up -d --remove-orphans;
docker image prune;"
Upvotes: 5