Skip to content

Instantly share code, notes, and snippets.

@jhonoryza
Created January 8, 2024 07:12
Show Gist options
  • Save jhonoryza/418f8ee2f6ba93f19c49bc60011ce39c to your computer and use it in GitHub Desktop.
Save jhonoryza/418f8ee2f6ba93f19c49bc60011ce39c to your computer and use it in GitHub Desktop.
deploy laravel apps using gitlab ci/cd with ansible docker image

let say we want to setup for staging environment

Requirement

  • vps server

Step

  • 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 under ansible.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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment