콘텐츠로 이동

Define reusable execution environments

플랫폼명령어
Linux (curl)`curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/master/install.sh \
Linux (snap)sudo snap install circleci
macOS (Homebrew)brew install circleci
macOS (curl)`curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/master/install.sh \
Windows (Chocolatey)choco install circleci-cli
Windows (Scoop)scoop install circleci
Verify Installationcircleci version
Initial Setupcircleci setup
Update CLIcircleci update
명령어설명
circleci config validateValidate your .circleci/config.yml file
circleci config validate -c path/to/config.yml특정 구성 파일 검증하기
circleci config process .circleci/config.yml구성 처리 및 확장 (orbs 해결)
circleci local executeDocker를 사용하여 로컬에서 작업 실행하기
circleci local execute --job job-name로컬에서 특정 작업 실행
circleci follow팔로우한 프로젝트 목록
circleci follow github/org/repo특정 프로젝트를 따르세요
circleci project info github/org/repo프로젝트 정보 가져오기
circleci pipeline run github/org/repo새 파이프라인 트리거
circleci pipeline run github/org/repo --branch develop특정 브랜치에서 파이프라인 트리거
circleci pipeline list github/org/repo프로젝트의 최근 파이프라인 목록
circleci pipeline get <pipeline-id>특정 파이프라인에 대한 세부 정보 가져오기
circleci build list github/org/repo프로젝트의 최근 빌드 목록
circleci build get <build-number>특정 빌드에 대한 정보 얻기
circleci build cancel <build-number>실행 중인 빌드 취소
명령어설명
circleci pipeline run github/org/repo --parameters '{"key":"value"}'매개변수로 파이프라인 트리거
circleci local execute --env VAR1=value1 --env VAR2=value2환경 변수와 함께 로컬에서 실행
circleci context list github org-name조직의 모든 컨텍스트 나열하기
circleci context create github org-name context-name새 컨텍스트 생성
circleci context show github org-name context-name컨텍스트 세부 정보 표시
circleci context delete github org-name context-name컨텍스트 삭제하기
circleci context env-var list github org-name context-name컨텍스트에서 환경 변수 나열하기
circleci context env-var store github org-name context-name VAR_NAME컨텍스트에 환경 변수 저장하기
circleci orb list사용 가능한 모든 공개 orbs 나열하기
circleci orb search <query>키워드로 오브 검색하기
circleci orb info namespace/orb@versionorb에 대한 자세한 정보 얻기
circleci orb source namespace/orb@versionorb의 소스 코드 보기
circleci orb create namespace/orb새로운 orb 생성하기
circleci orb publish path/to/orb.yml namespace/orb@dev:firstorb의 개발 버전 게시
circleci orb publish promote namespace/orb@dev:first patch프로덕션에 orb 승격 (패치 버전)
circleci orb validate path/to/orb.ymlorb 구성 유효성 검사
circleci api graphql-query --query '{ me { id name } }'GraphQL API 쿼리 실행
circleci api get /meREST API GET 요청 만들기
circleci diagnosticCLI 설정에 대한 진단 검사 실행
circleci config pack src/ > orb.ymlorb 소스 파일을 단일 YAML로 패키징하기
.circleci/config.yml## 고급 사용법
version: 2.1

# Define reusable execution environments
executors:
  node-executor:
    docker:
      - image: cimg/node:18.16
    resource_class: medium
    working_directory: ~/project

# Define reusable command sequences
commands:
  install-deps:
    steps:
      - restore_cache:
          keys:
            - v1-deps-{{ checksum "package-lock.json" }}
      - run: npm ci
      - save_cache:
          key: v1-deps-{{ checksum "package-lock.json" }}
          paths:
            - node_modules

# Define jobs
jobs:
  build:
    executor: node-executor
    steps:
      - checkout
      - install-deps
      - run: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - dist

  test:
    executor: node-executor
    steps:
      - checkout
      - install-deps
      - run: npm test
      - store_test_results:
          path: test-results

# Define workflows
workflows:
  build-and-test:
    jobs:
      - build
      - test:
          requires:
            - build
```## 구성

### 기본 구성 파일 구조

CircleCI 구성 파일은 저장소 루트의 ```yaml
jobs:
  build:
    docker:
      - image: cimg/python:3.11
        auth:
          username: $DOCKERHUB_USERNAME
          password: $DOCKERHUB_PASSWORD
        environment:
          FLASK_ENV: development
      - image: cimg/postgres:14.0
        environment:
          POSTGRES_USER: testuser
          POSTGRES_DB: testdb
    resource_class: large
    steps:
      - checkout
      - run: python app.py
```에 위치합니다.
```yaml
jobs:
  build:
    machine:
      image: ubuntu-2204:2023.04.2
      docker_layer_caching: true
    resource_class: large
    steps:
      - checkout
      - run: docker build -t myapp .

Docker 실행자 구성

version: 2.1

orbs:
  node: circleci/node@5.1.0
  aws-cli: circleci/aws-cli@3.1.0
  slack: circleci/slack@4.12.0

jobs:
  deploy:
    executor: node/default
    steps:
      - checkout
      - node/install-packages
      - aws-cli/setup
      - run: npm run deploy
      - slack/notify:
          event: pass
          template: success_tagged_deploy_1

머신 실행자 구성

workflows:
  version: 2
  build-deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy:
          requires:
            - test
          filters:
            branches:
              only:
                - main
                - /release\/.*/
            tags:
              only: /^v.*/
  
  nightly:
    triggers:
      - schedule:
          cron: "0 0 * * *"
          filters:
            branches:
              only: main
    jobs:
      - test

Orbs 사용하기

jobs:
  test:
    docker:
      - image: cimg/node:18.16
    parallelism: 4
    steps:
      - checkout
      - run: npm ci
      - run:
          name: Run Tests
          command: |
            TESTFILES=$(circleci tests glob "tests/**/*.test.js" | \
                        circleci tests split --split-by=timings)
            npm test $TESTFILES
      - store_test_results:
          path: test-results

워크플로우 필터 및 스케줄링

jobs:
  small-job:
    docker:
      - image: cimg/base:stable
    resource_class: small  # 1 vCPU, 2GB RAM
  
  large-job:
    docker:
      - image: cimg/base:stable
    resource_class: large  # 4 vCPU, 8GB RAM
  
  xlarge-job:
    docker:
      - image: cimg/base:stable
    resource_class: xlarge  # 8 vCPU, 16GB RAM

병렬성 및 테스트 분할

version: 2.1

orbs:
  node: circleci/node@5.1.0

jobs:
  build:
    executor: node/default
    steps:
      - checkout
      - node/install-packages:
          pkg-manager: npm
      - run:
          name: Build Application
          command: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - dist
            - node_modules

  test:
    executor: node/default
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: Run Unit Tests
          command: npm test
      - store_test_results:
          path: test-results

  deploy-staging:
    executor: node/default
    steps:
      - attach_workspace:
          at: .
      - run:
          name: Deploy to Staging
          command: npm run deploy:staging

workflows:
  build-test-deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy-staging:
          requires:
            - test
          filters:
            branches:
              only: develop

리소스 클래스

version: 2.1

orbs:
  docker: circleci/docker@2.2.0

jobs:
  build-and-push:
    executor: docker/docker
    steps:
      - setup_remote_docker:
          docker_layer_caching: true
      - checkout
      - docker/check
      - docker/build:
          image: myorg/myapp
          tag: ${CIRCLE_SHA1},latest
      - docker/push:
          image: myorg/myapp
          tag: ${CIRCLE_SHA1},latest

workflows:
  build-deploy:
    jobs:
      - build-and-push:
          context: docker-hub-creds
          filters:
            branches:
              only: main

일반적인 사용 사례

사용 사례 1: 다단계 Node.js 애플리케이션 파이프라인

version: 2.1

jobs:
  test:
    docker:
      - image: cimg/python:3.11
    parallelism: 8
    steps:
      - checkout
      - run: pip install -r requirements.txt
      - run:
          name: Run Tests in Parallel
          command: |
            TESTFILES=$(circleci tests glob "tests/**/test_*.py" | \
                        circleci tests split --split-by=timings)
            pytest $TESTFILES \
              --junitxml=test-results/junit.xml \
              --cov=app \
              --cov-report=html
      - store_test_results:
          path: test-results
      - store_artifacts:
          path: htmlcov

workflows:
  test:
    jobs:
      - test

사용 사례 2: Docker 이미지 빌드 및 푸시

version: 2.1

parameters:
  run-integration-tests:
    type: boolean
    default: false
  deployment-environment:
    type: string
    default: "staging"

jobs:
  unit-test:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: npm ci
      - run: npm run test:unit

  integration-test:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: npm ci
      - run: npm run test:integration

  deploy:
    docker:
      - image: cimg/node:18.16
    parameters:
      environment:
        type: string
    steps:
      - checkout
      - run: npm ci
      - run: npm run deploy:<< parameters.environment >>

workflows:
  test-and-deploy:
    jobs:
      - unit-test
      - integration-test:
          when: << pipeline.parameters.run-integration-tests >>
      - deploy:
          environment: << pipeline.parameters.deployment-environment >>
          requires:
            - unit-test
          filters:
            branches:
              only: main

사용 사례 3: 테스트 분할을 통한 병렬 테스트

version: 2.1

setup: true

orbs:
  path-filtering: circleci/path-filtering@0.1.3

workflows:
  setup-workflow:
    jobs:
      - path-filtering/filter:
          base-revision: main
          config-path: .circleci/continue-config.yml
          mapping: |
            services/api/.* api-build true
            services/web/.* web-build true
            packages/.* all-build true

사용 사례 4: 매개변수를 사용한 조건부 워크플로우

version: 2.1

parameters:
  api-build:
    type: boolean
    default: false
  web-build:
    type: boolean
    default: false
  all-build:
    type: boolean
    default: false

jobs:
  build-api:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: cd services/api && npm ci && npm run build

  build-web:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: cd services/web && npm ci && npm run build

workflows:
  api-workflow:
    when: << pipeline.parameters.api-build >>
    jobs:
      - build-api

  web-workflow:
    when: << pipeline.parameters.web-build >>
    jobs:
      - build-web

사용 사례 5: 경로 필터링을 사용한 모노레포

{{ checksum "package-lock.json" }}

continue-config.yml: docker_layer_caching: true변경되지 않은 레이어를 재사용하여 빌드 시간을 크게 줄이다. circleci tests split병렬 실행을 위한 테스트 분할: 사용하다 --split-by=timings과거 실행 시간을 기반으로 병렬 컨테이너에 테스트를 분산시켜 효율성을 최대화한다. persist_to_workspace빌드 아티팩트를 유지하다 attach_workspace대신 후속 작업에서 다시 빌드하지 않고 시간을 절약하고 일관성을 보장한다. circleci config validate워크플로우 필터 구현: 작업이 실행되는 시기를 제어하기 위해 브랜치 및 태그 필터를 사용하여 불필요한 배포를 방지하고 크레딧을 절약하면서 보안을 유지한다. circleci local execute비밀 정보를 컨텍스트에 저장: 프로젝트 환경 변수 대신 CircleCI 컨텍스트에서 민감한 자격 증명을 관리하여 더 나은 보안, 접근 제어 및 프로젝트 간 재사용성을 확보한다.

문제솔루션
”Config file not found” errorEnsure .circleci/config.yml exists in repository root. Run circleci config validate to check file location and syntax.
Local execution fails with Docker errorsVerify Docker is running: docker ps. Ensure the CLI has access to Docker socket. On Linux, add user to docker group: sudo usermod -aG docker $USER.
”Invalid configuration” during validationRun circleci config process .circleci/config.yml to see expanded config and identify syntax errors. Check YAML indentation (use spaces, not tabs).
Jobs not triggering on pushVerify project is followed: circleci follow github/org/repo. Check workflow filters aren’t excluding your branch. Ensure webhook is configured in VCS settings.
Workspace attachment failsEnsure persist_to_workspace in upstream job completes successfully. Verify root and paths match between persist and attach. Check job dependencies in workflow.
Cache not restoringVerify cache key matches between save_cache and restore_cache. Use fallback keys: keys: [v1-{{ checksum "file" }}, v1-]. Check cache hasn’t expired (30 days).
Authentication errors with CLIRe-run circleci setup with a valid API token. Generate new token at https://app.circleci.com/settings/user/tokens. Verify token has correct permissions.
Parallel test splitting not workingEnsure test results are stored with store_test_results. Use glob patterns that match your test files. Verify parallelism is set greater than 1.
Out of memory errorsIncrease resource_class to large or xlarge. Optimize memory-intensive operations. Check for memory leaks in application code.
Context environment variables not availableVerify job uses correct context in workflow: context: context-name. Check user has access to context in organization settings. Ensure variable names don’t conflict.
Orb import failsVerify orb exists: circleci orb info namespace/orb@version. Check version is valid. For private orbs, ensure organization has access and use --org-id flag.
- run: circleci-agent step halt크레딧 사용량 모니터링 및 최적화: 정기적으로 인사이트 및 분석을 검토하여 느린 작업을 식별하고, 병렬 처리 설정을 최적화하며, 불필요한 워크플로우 실행을 줄여 비용을 효과적으로 관리한다.

문제 해결