首页

    我的gitlab CI/CD配置

    标签:gitlab-CI-CD

    .gitlab-ci.yml

    image: docker:stable
    
    stages:
      - build
      - release
      - deploy
    
    variables:
      CACHE_IMAGE_URL: blog:cache
      BUILD_IMAGE_URL: blog:$CI_COMMIT_SHA
      RELEASE_IMAGE_URL: blog:latest
    
    build:
      stage: build
      script:
        - docker pull $CACHE_IMAGE_URL || true
        - tar -cf source.tar nginx.conf lua src gulpfile tags*
        - docker build --cache-from $CACHE_IMAGE_URL -f ./dockerfile/build_stage -t $BUILD_IMAGE_URL -t $CACHE_IMAGE_URL .
        - docker push $CACHE_IMAGE_URL
      tags:
        - docker
    
    release:
      stage: release
      script:
        - docker build -f ./dockerfile/release_stage --build-arg BUILD_IMAGE_URL=$BUILD_IMAGE_URL -t $RELEASE_IMAGE_URL .
        - docker push $RELEASE_IMAGE_URL
        - docker rmi $BUILD_IMAGE_URL
      tags:
        - docker
      only:
        - master
      allow_failure: false
    
    deploy:
      stage: deploy
      script:
        - ansible-playbook deploy/deploy.yml -i deploy/hosts --extra-vars "user=$deploy_user"
      tags:
        - shell
      only:
        - master
    

    dockerfile

    • build stage
    FROM node:8.11.3-alpine
    WORKDIR /build
    
    ADD package.json /tmp/package.json
    RUN cd /tmp && npm install --only=production \
        && cp -a /tmp/node_modules /build
    
    ADD source.tar /build
    RUN ./node_modules/.bin/gulp --gulpfile ./gulpfile/prod.js \
        && mv blog/html/index.html blog \
        && mv blog/html/tags.html blog \
        && mv tags.json blog \
        && mv title_path.json blog \
        && rm -r node_modules src build gulpfile* /tmp
    
    • release stage
    ARG BUILD_IMAGE_URL
    FROM $BUILD_IMAGE_URL as build
    
    FROM registry.gitlab.com/love_little_fat_cat/docker-openresty:latest
    COPY --from=build /build/nginx.conf /usr/local/openresty/nginx/conf
    COPY --from=build /build/lua /root/lua
    COPY --from=build /build/blog /root/blog
    

    deploy.yml

    ---
    - hosts: server
      remote_user: "{{user}}"
      tasks:
        - name: make sure target dir exists
          file:
            path: "blog"
            state: directory
            recurse: yes
        - name: copy k8s yaml
          copy:
            src: ../k8s.yaml
            dest: ./blog/k8s.yaml
    
        - name: kubernetes deploy
          command: /usr/bin/kubectl apply -f ~/blog/k8s.yaml
          register: out
        - debug: var=out.stderr_lines
        - debug: var=out.stdout_lines
    
        - name: kubernetes force pull
          when: out.stdout.find('configured')==-1
          command: /usr/bin/kubectl patch deployment blog -p {\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"{{ansible_date_time.epoch}}\"}}}}}
          register: out
        - debug: var=out.stderr_lines
        - debug: var=out.stdout_lines
    

    不定期更新