Skip to main content

Managing Contexts

1. Understanding Context Purpose

Context Type Description Use Case
Environment Variables Variables that are available to all jobs in a workflow and can be set at the project or pipeline level. Storing sensitive data like API keys or configuration values that are needed across multiple jobs.
Workflows Define how jobs are orchestrated and executed, including dependencies and parallelism. Running multiple jobs in sequence or parallel based on conditions or triggers.
Parameters Inputs that can be passed to a pipeline or job, allowing for dynamic behavior. Customizing pipeline execution based on input values such as branch names or tags.
Artifacts Files or data that are generated during a job and can be stored for later use. Storing build outputs, logs, or test results for access after job completion.
Caching Stores and reuses files between builds to speed up the build process. Reducing build times by caching dependencies or other frequently used files.

Example: Setting Environment Variables

version: 2.1
jobs:
  build:
    docker:
      - image: circleci/node:16
    environment:
      NODE_ENV: production
      API_KEY: <value>
Note: Environment variables set at the project level are accessible to all pipelines within that project.
Warning: Never hardcode sensitive values in configuration files. Use CircleCI's encrypted environment variables or context features to manage secrets securely.

2. Creating Contexts

Example: Define a context with environment variables

version: 2.1
contexts:
  my-context:
    environment:
      API_KEY: "secret-key-123"
      DATABASE_URL: "postgres://user:pass@localhost/db"
Property Description Values
contexts Defines a set of contexts that can be reused across jobs Object with context names as keys
environment Environment variables available in the context Object with key-value pairs
Note: Contexts are defined at the project level and can be reused across multiple jobs or workflows.
Warning: Environment variables defined in contexts are not encrypted by default. Use CircleCI's encrypted environment variables for sensitive data.

3. Adding Variables to Contexts

Variable Type Description Usage Notes
env Environment variables available in the job context env.VARIABLE_NAME Accessible in all steps of a job
context Custom context variables defined in CircleCI configuration context.VARIABLE_NAME Must be defined in the config file or via API
parameters Parameters passed to a CircleCI orb or workflow parameters.VARIABLE_NAME Used in orb configuration and workflow definitions

Example: Setting Environment Variables in a Job

jobs:
  build:
    steps:
      - run:
          name: Set Environment Variable
          command: |
            echo "export MY_VAR=value" >> $BASH_ENV

Example: Using Context Variables in a Pipeline

jobs:
  build:
    steps:
      - run:
          name: Use Context Variable
          command: echo $CONTEXT_VAR
Note: Variables set in a job's environment are available to all subsequent steps within that job.
Warning: Ensure sensitive variables are marked as masked to prevent exposure in logs.

4. Using Contexts in Workflows

Property Description Usage
context Name of the context to use context: my-context
name Unique identifier for the context name: my-context
values Key-value pairs of context variables values: { key1: value1, key2: value2 }

Example: Using Context in a Workflow

version: 2.1
jobs:
  build:
    docker:
      - image: circleci/node:16
    steps:
      - checkout
      - run:
          name: Use Context Variables
          command: echo $API_KEY
workflows:
  version: 2
  main:
    jobs:
      - build:
          context: my-context
Note: Contexts are scoped to the workflow and can be reused across jobs.
Warning: Ensure sensitive variables are properly encrypted in context values.

5. Using Multiple Contexts

CircleCI allows you to define and use multiple contexts to manage different sets of environment variables, AWS credentials, and other configuration values across various projects or workflows. Contexts provide a way to centralize configuration and improve security by avoiding the need to hardcode sensitive data in your configuration files.

Context Name Description Usage
project-context Default context for project-specific configurations Applied automatically to all jobs in the project
staging-context Configuration for staging environments Used in jobs targeting staging servers
production-context Configuration for production environments Used in jobs targeting production servers

Example: Defining Contexts in CircleCI Configuration

version: 2.1
contexts:
  project-context:
    environment:
      ENV: "development"
      DB_URL: "postgres://localhost:5432/mydb"
  staging-context:
    environment:
      ENV: "staging"
      DB_URL: "postgres://staging-server:5432/mydb"
  production-context:
    environment:
      ENV: "production"
      DB_URL: "postgres://prod-server:5432/mydb"

jobs:
  build:
    docker:
      - image: circleci/node:16
    context: project-context
    steps:
      - checkout
      - run: echo "Building in $ENV environment"

  deploy-staging:
    docker:
      - image: circleci/node:16
    context: staging-context
    steps:
      - checkout
      - run: echo "Deploying to staging"

  deploy-production:
    docker:
      - image: circleci/node:16
    context: production-context
    steps:
      - checkout
      - run: echo "Deploying to production"
Note: Contexts are defined at the project level in CircleCI and can be referenced by job names. Each context can contain environment variables, AWS credentials, SSH keys, and other configuration values that are injected into the job's runtime environment.
Warning: Ensure that sensitive data is not exposed in logs or configuration files. Use CircleCI's encrypted environment variables and context features to protect sensitive information.

6. Restricting Context Access

Permission Description Scope Notes
context.read Read access to context variables Project-level Allows viewing and using context values in config
context.write Write access to context variables Project-level Allows creating/updating context values
context.delete Delete access to context variables Project-level Allows removing context values from project

Example: Setting Context Permissions

version: 2.1
jobs:
  build:
    steps:
      - run:
          name: Set Context Value
          command: |
            circleci env set MY_VAR "value"
      - run:
          name: Use Context Value
          command: |
            echo $MY_VAR
Note: Context access is controlled via project settings and requires appropriate permissions to manage.
Warning: Setting context variables with sensitive data should be done carefully to avoid exposing credentials.

7. Managing Context Permissions

Permission Description Scope Notes
context.read Read access to context variables Project-level Allows reading context values but not modifying them
context.write Write access to context variables Project-level Allows creating, updating, and deleting context variables
context.delete Delete access to context variables Project-level Allows deletion of existing contexts

Example: Setting Context Permissions via API

curl -X POST https://circleci.com/api/v2/project/<VCS>/<ORG>/<PROJECT>/context \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d '{"name": "my-context", "permissions": [{"type": "context.read", "scope": "project"}]}'
Note: Context permissions are managed at the project level and can be configured via the CircleCI API or UI.

8. Rotating Context Secrets

Property Description Values Notes
context.name Name of the context circleci-context Must be unique within the organization
secret.name Name of the secret api-key Used to reference the secret in configuration
secret.value Value of the secret (encrypted) abc123xyz Rotated with new value when updated

Example: Rotating a Context Secret

circleci context update-secret \
  --context-name circleci-context \
  --secret-name api-key \
  --secret-value new-api-key-123
Note: Rotating secrets in CircleCI requires the user to have appropriate permissions on the context and secret.
Warning: Ensure that any jobs or workflows using the secret are updated to use the new value after rotation.

9. Using Context Restrictions

Restriction Type Description Usage
context.restrictions Defines which contexts can be used in a pipeline context.restrictions: ['production', 'staging']
context.restrictions.allow Explicitly allows specific contexts context.restrictions.allow: ['production']
context.restrictions.deny Prevents specific contexts from being used context.restrictions.deny: ['development']

Example: Restricting Contexts in a Pipeline

version: 2.1
jobs:
  build:
    docker:
      - image: circleci/node:16
    steps:
      - checkout
      - run: npm test

workflows:
  version: 2
  build-and-test:
    jobs:
      - build:
          context:
            - production
            - staging
          context.restrictions:
            allow: [production]
Note: Context restrictions apply to all jobs in a workflow that use context variables.

10. Auditing Context Usage

Context Field Description Usage Example Notes
context.name Name of the context "production-deploy" Used to identify the context in logs and UI
context.description Human-readable description of the context "Deployment credentials for production" Helps in understanding the purpose of the context
context.variables List of environment variables in the context ["API_KEY", "DB_URL"] Variables are accessible in jobs using context.variables
context.created_at Timestamp when the context was created "2024-05-10T12:00:00Z" Used for tracking and compliance
context.updated_at Timestamp when the context was last updated "2024-06-15T14:30:00Z" Indicates recent changes to the context

Example: Retrieving Context Variables

circleci context get production-deploy

Example: Listing All Contexts

circleci context list
Note: Contexts are scoped to the organization and can be shared across projects.
Warning: Ensure that sensitive variables are not exposed in logs or public documentation.

Was this article helpful?