Gitlab CI/CD + Static

Example

image: node:16-alpine

stages:
  - build
  - deploy

# build
build_dev:
  stage: build
  only:
    - dev
  script:
    - echo "$DOTENV" > .env
    - npm ci
    - npm run build
  cache:
    key:
      files:
        - package-lock.json
      prefix: npm
    paths:
      - node_modules/
  artifacts:
    paths:
      - dist/
    expire_in: 1 hour
  environment:
    name: dev
  tags:
    - docker

# deploy
deploy_dev:
  stage: deploy
  only:
    - dev
  before_script:
    - apk update && apk add --no-cache rsync openssh-client
    # - eval $(ssh-agent -s)
    - mkdir -m 700 -p ~/.ssh
    - echo "$SSH_WEB_PRIVATE_KEY" > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - ssh-keyscan -t rsa 127.0.0.1 >> ~/.ssh/known_hosts
    - echo -e "StrictHostKeyChecking no" >> ~/.ssh/config
  script:
    - rsync -rav --delete dist/ user@127.0.0.1:/path/
  environment:
    name: dev
    url: https://dev.example.com
  tags:
    - docker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

SSH key

Private key already added to WEB group in gitlab, just use SSH_WEB_PRIVATE_KEY

Copy public key to server

ssh-copy-id -i ~/.ssh/id_rsa_gitlab.pub user@host
1

.env

Create a custom variableopen in new window with environment-specific variables.

Use environments for dev/staging/production

Add to .gitlab-ci.yml deploy script

script:
  # ...
  - echo "$DOTENV" > .env
  # Deploy project
1
2
3
4