Zum Inhalt

CircleCI Cheatsheet

Installation

Plattform Befehl
Linux (curl) curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/master/install.sh \ | bash
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 \ | bash
Windows (Chocolatey) choco install circleci-cli
Windows (Scoop) scoop install circleci
Verify Installation circleci version
Initial Setup circleci setup
Update CLI circleci update

Grundlegende Befehle

Befehl Beschreibung
circleci config validate Validate your .circleci/config.yml file
circleci config validate -c path/to/config.yml Validiere eine bestimmte Konfigurationsdatei
circleci config process .circleci/config.yml Prozess und Erweiterung der Konfiguration (Auflösung von Orbs)
circleci local execute Führen Sie einen Job lokal mit Docker aus
circleci local execute --job job-name Einen bestimmten Job lokal ausführen
circleci follow Alle gefolgten Projekte auflisten
circleci follow github/org/repo Einem bestimmten Projekt folgen
circleci project info github/org/repo Projektinformationen abrufen
circleci pipeline run github/org/repo Einen neuen Pipeline auslösen
circleci pipeline run github/org/repo --branch develop Pipeline auf bestimmtem Branch auslösen
circleci pipeline list github/org/repo Liste der neuesten Pipelines für ein Projekt
circleci pipeline get <pipeline-id> Details zu einer bestimmten Pipeline abrufen
circleci build list github/org/repo Liste der neuesten Builds für ein Projekt
circleci build get <build-number> Informationen zu einem bestimmten Build abrufen
circleci build cancel <build-number> Einen laufenden Build abbrechen

Erweiterte Nutzung

Befehl Beschreibung
circleci pipeline run github/org/repo --parameters '{"key":"value"}' Pipeline mit Parametern auslösen
circleci local execute --env VAR1=value1 --env VAR2=value2 Lokal mit Umgebungsvariablen ausführen
circleci context list github org-name Alle Kontexte für eine Organisation auflisten
circleci context create github org-name context-name Neuen Kontext erstellen
circleci context show github org-name context-name Kontextdetails anzeigen
circleci context delete github org-name context-name Kontext löschen
circleci context env-var list github org-name context-name Umgebungsvariablen in einem Kontext auflisten
circleci context env-var store github org-name context-name VAR_NAME Umgebungsvariable im Kontext speichern
circleci orb list Alle verfügbaren öffentlichen Orbs auflisten
circleci orb search <query> Suche nach Orbs nach Schlüsselwort
circleci orb info namespace/orb@version Detaillierte Informationen über einen Orb abrufen
circleci orb source namespace/orb@version Den Quellcode einer Orb anzeigen
circleci orb create namespace/orb Erstelle einen neuen Orb
circleci orb publish path/to/orb.yml namespace/orb@dev:first Entwicklungsversion eines Orb veröffentlichen
circleci orb publish promote namespace/orb@dev:first patch Orb zur Produktion befördern (Patch-Version)
circleci orb validate path/to/orb.yml Validiere eine Orb-Konfiguration
circleci api graphql-query --query '{ me { id name } }' GraphQL API-Abfrage ausführen
circleci api get /me REST API GET-Anfrage senden
circleci diagnostic Führen Sie Diagnosechecks für die CLI-Einrichtung durch
circleci config pack src/ > orb.yml Pack Orb-Quelldateien in eine einzelne YAML-Datei

Konfiguration

Grundlegende Konfigurationsdateistruktur

Die CircleCI-Konfigurationsdatei befindet sich .circleci/config.ymlin Ihrem Repository-Stammverzeichnis.

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

Docker Executor-Konfiguration

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

Machine Executor-Konfiguration

jobs:
  build:
    machine:
      image: ubuntu-2204:2023.04.2
      docker_layer_caching: true
    resource_class: large
    steps:
      - checkout
      - run: docker build -t myapp .

Verwendung von Orbs

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

Workflow-Filter und Planung

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

Parallelität und Test-Splitting

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

Ressourcenklassen

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

Häufige Anwendungsfälle

Anwendungsfall 1: Multi-Stage Node.js Anwendungs-Pipeline

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

Anwendungsfall 2: Docker-Image-Erstellung und -Push

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

Anwendungsfall 3: Paralleles Testen mit Test-Splitting

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

Anwendungsfall 4: Bedingter Workflow mit Parametern

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

Anwendungsfall 5: Monorepo mit Pfadfilterung

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

continue-config.yml:

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

Best Practices

  • Orbs für häufige Aufgaben verwenden: Nutzen Sie CircleCI Orbs für standardisierte Integrationen (AWS, Docker, Slack), um die Konfigurationskomplexität und Wartungslast zu reduzieren.

  • Caching strategisch implementieren: Zwischenspeichern von Abhängigkeiten mit Prüfsummen-basierten Schlüsseln ({{ checksum "package-lock.json" }}), um Builds zu beschleunigen und gleichzeitig sicherzustellen, dass der Cache ungültig wird, wenn sich Abhängigkeiten ändern.

  • Ressourcenklassen optimieren: Wählen Sie geeignete Ressourcenklassen für jeden Job; verwenden Sie kleinere Instanzen für einfache Aufgaben und reservieren Sie größere Instanzen für rechenintensive Operationen wie Kompilierung oder komplexe Tests.

  • Docker Layer Caching aktivieren: Für Jobs, die Docker-Images erstellen, aktivieren Sie

Note: Some sections were left untranslated as they seem to be placeholders or code snippets. I've maintained the structure and formatting as requested.docker_layer_caching: trueum Buildzeiten durch Wiederverwendung unveränderter Ebenen signifikant zu reduzieren. circleci tests splitTests für parallele Ausführung aufteilen: Verwenden Sie --split-by=timingsum Tests über parallele Container basierend auf historischen Ausführungszeiten zu verteilen und die Effizienz zu maximieren. persist_to_workspaceBuildartefakte mithilfe von attach_workspacezu speichern, anstatt in nachfolgenden Jobs neu zu erstellen, um Zeit zu sparen und Konsistenz zu gewährleisten. circleci config validateImplementieren Sie Workflow-Filter: Verwenden Sie Branch- und Tag-Filter, um zu steuern, wann Jobs ausgeführt werden, um unnötige Bereitstellungen zu verhindern und Credits zu schonen und gleichzeitig die Sicherheit zu gewährleisten. circleci local executeSpeichern Sie Geheimnisse in Kontexten: Verwalten Sie sensible Anmeldeinformationen in CircleCI-Kontexten anstelle von Projekt-Umgebungsvariablen für bessere Sicherheit, Zugriffssteuerung und Wiederverwendbarkeit über Projekte hinweg.

Problem Lösung
"Config file not found" error Ensure .circleci/config.yml exists in repository root. Run circleci config validate to check file location and syntax.
Local execution fails with Docker errors Verify 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 validation Run 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 push Verify 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 fails Ensure persist_to_workspace in upstream job completes successfully. Verify root and paths match between persist and attach. Check job dependencies in workflow.
Cache not restoring Verify 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 CLI Re-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 working Ensure 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 errors Increase resource_class to large or xlarge. Optimize memory-intensive operations. Check for memory leaks in application code.
Context environment variables not available Verify 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 fails Verify 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 haltund Testjobs lokal mit aus, bevor Sie sie übertragen, um Syntaxfehler und Konfigurationsprobleme frühzeitig zu erkennen.

Fehlerbehebung