let say we want to setup for staging environment
- vps server
- create file
.gitlab-ci.yml
in root directory add this line
stages:
- Deploy
deploy-staging:
image: willhallonline/ansible:2.15.2-alpine-3.18
stage: Deploy
script:
- apk add --update openssh-client bash
- eval $(ssh-agent -s)
- bash -c 'ssh-add <(echo "$PROJECT_KEY")'
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
- ansible-playbook -i hosts staging.yml
only:
- master
when: on_success
-
you need to add new variable
$PROJECT_KEY
to your gitlab project settings -> ci/cd -> variables -> add new variable and paste your server ssh private key , make sure to uncheck protect variable -
create file
staging.yml
in root directory, you can put any linux command underansible.builtin.shell: |
, example :
---
- name: Deploy latest code from branch master to staging
hosts: staging
become: no
tasks:
- name: pull latest code from branch master
ansible.builtin.shell: |
cd /home/ubuntu/site-docker/projects
git pull origin master
- name: rebuild docker image backend
ansible.builtin.shell: |
cd /home/suitmedia/site-docker
docker compose build php
- name: up docker container service
ansible.builtin.shell: |
cd /home/suitmedia/ksei-docker
docker compose up -d
- name: clean up unused docker images
ansible.builtin.shell: |
docker image prune -f
- create file
hosts
, this file contain server ip addr, user and environment, example :
[staging]
192.168.1.1 ansible_user=root