LoginSignup
14
10

More than 5 years have passed since last update.

.gitlab-ci.yml ジョブ事例集

Last updated at Posted at 2018-10-09

npm を使ったGitLab CIプロジェクトで使っている秘伝のタレをご紹介します。

参考

package.json が編集された時だけ npm install する

ビルドの度に npm install しているとビルドに余計な時間がかかるので、package.json が編集された時だけ、 node_modules/ をクリアして npm install します。

variables:
  DEST_DIR: dest/

build:prod:
  stage: build
  dependencies: []
  script:
    - mkdir -p .cache
    - npm config set cache $CI_PROJECT_DIR/.cache/npm --global
    - yarn config set cache-folder $CI_PROJECT_DIR/.cache/yarn
    - >
      (test -d node_modules/ && diff .cache/package.json package.json > /dev/null 2>&1) ||
      (rm -fr node_modules/ &&
        (test -f yarn.lock && yarn install) ||
        (test -f package-lock.json && npm ci) ||
        npm install
      )
    - npm run build
    - cp -p package.json .cache/
  cache:
    paths:
      - .cache/
      - node_modules/
  artifacts:
    paths:
      - $DEST_DIR

画像ファイルのフォーマットを確認する

「拡張子が.jpgなのに中身がPNGだった」等の事故が起きないよう、画像ファイルの拡張子と中身が一致しているかを確認します。
また、JPEGファイルの色がCMYKだったという事故が起きないよう、RGBかGrayscaleかどうかも確認します。
RubyとImageMagickが必要です。

variables:
  DEST_DIR: dest/

test:image_format:
  stage: test
  script:
    - find "$DEST_DIR" -type f -name '*.jpg' | xargs identify -format '%i %m\n' | ruby -ne 'BEGIN{$e=0}; unless /JPEG\s*$/ then print; $e=1 end; END{exit $e}'
    - find "$DEST_DIR" -type f -name '*.png' | xargs identify -format '%i %m\n' | ruby -ne 'BEGIN{$e=0}; unless /PNG\s*$/ then print; $e=1 end; END{exit $e}'
    - find "$DEST_DIR" -type f -name '*.svg' | xargs identify -format '%i %m\n' | ruby -ne 'BEGIN{$e=0}; unless /SVG\s*$/ then print; $e=1 end; END{exit $e}'
    - find "$DEST_DIR" -type f -name '*.ico' | xargs identify -format '%i %m\n' | ruby -ne 'BEGIN{$e=0}; unless /ICO\s*$/ then print; $e=1 end; END{exit $e}'
    - find "$DEST_DIR" -type f -name '*.jpg' | xargs identify -format '%i %r\n' | ruby -ne 'BEGIN{$e=0}; unless /(sRGB|Gray)\s*$/ then print; $e=1 end; END{exit $e}'

SSH + rsyncでファイルをコピーする

ビルドをDockerで動かしている場合など、ジョブのscriptにrsyncを仕込むだけだと、そんなコピー先ホストなんてシラネと言われてしまうので、お膳立てをしてからrsyncします。

variables:
  DEST_DIR: dist/
  STAGE_HOST: rsyncコピー先ホスト名
  STAGE_USER: SSHリモートユーザー名
  STAGE_PATH: /path/to/rsync/コピー先/ディレクトリ

deploy:stage:
  stage: deploy
  script:
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - touch ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - ssh-keyscan $STAGE_HOST >> ~/.ssh/known_hosts
    - ssh $STAGE_USER@$STAGE_HOST mkdir -p "$STAGE_PATH"
    - rsync -av -e ssh --delete --checksum "$DEST_DIR" $STAGE_USER@$STAGE_HOST:"$STAGE_PATH"
  only:
    variables:
      - $SSH_PRIVATE_KEY

参考

14
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
10