---
title: "Using contexts"
description: "Create and use contexts to secure and share environment variables across projects, and restrict contexts by security group, project or expression."
platform: "Cloud, Server"
doc_version: "Server"
last_updated: "2026-10-26"
---

> For current CircleCI product defaults, deprecated patterns, and Cloud/Server differences, see [AGENTS.md](https://circleci.com/docs/AGENTS.md).
>
> For the complete documentation index and site structure, see [llms.txt](https://circleci.com/docs/llms.txt).

# Using contexts

Contexts provide a mechanism for securing and sharing environment variables across projects. The environment variables are defined as name/value pairs and are injected at runtime. This document describes creating and using contexts in CircleCI.

## Introduction

Manage contexts using the [CircleCI CLI](https://circleci.com/docs/guides/server/toolkit/circleci-cli/), [API](https://circleci.com/docs/api/v2/#tag/Context), or on the **Organization Settings** page of the CircleCI web app. You must be an organization member to view, create, or edit contexts.

Create a context and add your environment variables. You can use the `context` key in the workflows section of a project’s configuration file to give any job(s) access to the environment variables associated with the context. See the [Configuration Reference](https://circleci.com/docs/reference/configuration-reference/#context) page for more information.

> **Image:** Contexts Overview

Figure 1. Diagram showing how contexts are used in a workflow

To use environment variables from a context, the actor running the workflow must be a member of the organization that owns the context and have access to the context. The workflow must also meet any restrictions placed on the context.

Context names must be unique for each VCS organization. The default name for a context is `org-global`. Contexts created with the initial default name of `org-global` will continue to work.

## Quickstart: Create and use a context

Organization members can create contexts, but only organization administrators can restrict them using security groups.

<Tabs>
<Tab title="CLI">

1.  Create a context:
    
    ```shell
    circleci context create <context-name> --org <org-slug>
    ```
    
    The new context appears with security set to `All members`, meaning anyone in your organization can access it at runtime.
    
2.  Add an environment variable to the context:
    
    ```shell
    circleci context secret set <context-name> --name <env-var-name> --value <env-var-value>
    ```
    
3.  To allow a job to access the environment variables stored in a context, add a `context` key to that job’s entry in the [`workflows`](https://circleci.com/docs/reference/configuration-reference/#workflows) section of the `.circleci/config.yml` file. For example, the following gives the `run-tests` job access to variables in the `org-global` and `my-context` contexts:
    
    ```yaml
    version: 2.1
    
    workflows:
      my-workflow:
        jobs:
          - run-tests:
              context:
                - org-global
                - my-context
    
    jobs:
      run-tests:
        docker:
          - image: cimg/base:2020.01
        steps:
          - checkout
          - run:
              name: "echo environment variables from org-global context"
              command: echo $MY_ENV_VAR
    ```

</Tab>
<Tab title="Web app">

1.  In the CircleCI web app, select your org from the org cards on your user homepage.
    
2.  Select **Org** from the sidebar to open your organization settings page.
    
3.  Select **Create Context**, add a unique name for your context and select **Create Context** in the modal to finalize. The new context will appear in a list with security set to `All members` to show that anyone in your organization can access this context at runtime.
    
4.  You can now select any context created in your list to add environment variables. Once you have a context selected, select **Add Environment Variable** to enter the variable name and value. Select **Add Environment Variable** in the modal to finalize.
    
5.  To allow a job to access the environment variables stored in a context, add a context key to that job’s entry in the [`workflows`](https://circleci.com/docs/reference/configuration-reference/#workflows) section of the `.circleci/config.yml` file. For example, in the following example, the `run-tests` job has access to the environment variables set in the `org-global` and `my-context` contexts.
    
    ```yaml
    version: 2.1
    
    workflows:
      my-workflow:
        jobs:
          - run-tests:
              context:
                - org-global
                - my-context
    
    jobs:
      run-tests:
        docker:
          - image: cimg/base:2020.01
        steps:
          - checkout
          - run:
              name: "echo environment variables from org-global context"
              command: echo $MY_ENV_VAR
    ```

</Tab>
</Tabs>

If you move your repository to a new organization, you must also have the context with that unique name set in the new organization.

## Contexts and environment variable constraints

When creating contexts and environment variables, note the following:

*   The context name must be:
    
    *   200 or fewer characters.
        
    *   Must contain at least one non-whitespace character.
        
    *   Must not contain leading, trailing, or vertical whitespace.
        
    
*   The environment variable name must be:
    
    *   300 or fewer characters.
        
    *   Begin with an alpha (a-z, A-Z) or `_` as the first character, and use alphanumeric or `_` for the remaining characters.
        
    
*   An environment variable value must have 32k or fewer characters.
    
*   An empty environment variable is considered valid.
    
*   Each context is limited to 100 environment variables.
    
*   Each configuration file is limited to 100 contexts.
    
*   Each organization is limited to 500 contexts.
    

## Context naming for CircleCI Server

For any VCS enterprise installation that includes multiple organizations, the context names across those organizations must be unique. For example, if your GitHub Enterprise installation is named Kiwi and includes two organizations, you cannot add a context called `deploy` to both organizations. That is, the `deploy` context name cannot be duplicated in two organizations that exist in the same GitHub Enterprise installation for the Kiwi account. Duplicate contexts within an account will fail with an error.

## Combine contexts

You can combine several contexts for a single job by adding them to the context list. Contexts are applied in order, so in the case of overlaps, later contexts override earlier ones. This way, you can scope contexts to be as small and granular as you like.

In the following example, the `deploy` job has access to environment variables from three contexts. If the same variable name exists in more than one context, the value from `env-production` takes precedence as it is listed last:

```yaml
workflows:
  build-deploy:
    jobs:
      - build
      - deploy:
          requires:
            - build
          context:
            - org-global
            - aws-credentials
            - env-production
```

## Restrict a context

Only `github` type organizations support security group restrictions.

CircleCI enables you to restrict contexts at run time in the following ways:

*   Using [security groups](#security-group-restrictions).
    
*   Using [Project restrictions](#project-restrictions).
    
*   Using [Expression restrictions](#expression-restrictions).
    

Only organization administrators may add restrictions to new or existing contexts.

Security groups are your organization’s VCS teams. After a security group is added to a context, only members of that security group who are also CircleCI users may access the context and use the associated environment variables. The default security group is `All members`, and enables any member of the organization who uses CircleCI to use the context.

Organization administrators have read/write access to all projects and have unrestricted access to all contexts.

### Run workflows with a restricted context

To invoke a job that uses a restricted context, every restriction type that is set on the context must pass. Security groups, project restrictions, and expression restrictions combine with logical AND.

#### How restrictions combine

*   **Security groups:** The user who triggered the pipeline must belong to at least one assigned group. The default group `All members` allows any organization member. If you assign more than one named group, membership in any one of those groups is enough (logical OR).
    
*   **Project restrictions:** If you add any project restrictions, the job must run in one of the listed projects (logical OR). If you add none, every project in the organization can use the context.
    
*   **Expression restrictions:** If you add any expression restrictions, every expression must evaluate to `true` (logical AND). If you add none, this check passes.
    

A context with both a security group and a project restriction is available only when both checks pass. Group membership does not bypass a project allowlist. A listed project does not bypass a security group.

If the user running the workflow does not have access to the context, or an expression evaluates to false, the workflow fails with the `Unauthorized` status.

### Approve jobs that use restricted contexts

Adding an [Approval Job](https://circleci.com/docs/reference/configuration-reference/#type) to a workflow gives the option to require manual approval of the use of a restricted context. To restrict running of jobs that are downstream from an approval job, add a restricted context to those downstream jobs, as shown in the example below:

```yaml
version: 2.1

# Jobs declaration for build, test and deploy not displayed

workflows:
  build-test-deploy:
    jobs:
      - build
      - test:
          context: my-restricted-context
          requires:
            - build
      - hold:
          type: approval # presents manual approval button in the UI
          requires:
            - build
      - deploy:
          context: deploy-key-restricted-context
          requires:
            - build
            - hold
            - test
```

In this example, the jobs `test` and `deploy` are restricted. The `deploy` job only runs if the user who approves the `hold` job is a member of the security group assigned to the context _and_ `deploy-key-restricted-context`. When the workflow `build-test-deploy` runs, the jobs `build` and `test` run, then the `hold` job runs and presents a manual approval button in the CircleCI application. _Any_ member of the project can approve this job, but the `deploy` job fails as `unauthorized` if the approver is not part of the restricted context security group.

## Security group restrictions

Restricting the use of contexts using security groups is available for `github` type organizations only. For more information on organization types, see the [Users, Organizations, and Integrations Guide](https://circleci.com/docs/guides/server/permissions-authentication/users-organizations-and-integrations-guide/#organizations).

### Restrict a context to a security group or groups

To use security group context restrictions you must be an organization administrator, and your code must be integrated with CircleCI via the GitHub OAuth app.

<Tabs>
<Tab title="CLI">

1.  Create a new context or use an existing one. To create a new context:
    
    ```shell
    circleci context create <context-name> --org <org-slug>
    ```
    
2.  Add a security group restriction to the context, where `<github-team-name>` is the name of the GitHub team you want to restrict access to:
    
    ```shell
    circleci context restriction create <context-name> --type group --value <github-team-name> --org <org-slug>
    ```
    
    Only members of the specified GitHub team can now use the context in their workflows.
    
3.  Optionally, add environment variables to the context:
    
    ```shell
    circleci context secret set <context-name> --name <env-var-name> --value <env-var-value>
    ```

</Tab>
<Tab title="Web app">

1.  Navigate to **Org**  **Contexts** in the CircleCI web app to see the list of contexts. The default security group is `All members`, and allows all users in the organization to invoke jobs with that context.
    
2.  Select **Create Context** to use a new context, or select the name of an existing context. If you use an existing context, remove the `All members` security group before adding a new one.
    
3.  Select **Add Security Group** button to view the dialog box.
    
4.  Make your choices in the dialog box and then select the **Add Security Group** or **Add Project Restriction** button to finalize. Contexts will now be restricted to the selections you have made.
    
5.  Select **Add Environment Variables** to add environment variables to the context. Fill out your desired name and value in the dialog box, then select **Add Environment Variables** again to finalize. Use of the environment variables for this context is now limited to members of the security groups.
    
6.  Navigate back to **Org**  **Contexts** in the CircleCI app. The security groups appear in the Security column for the context.

</Tab>
</Tabs>

Only members of the selected groups may now use the context in their workflows or add or remove environment variables for the context.

### Make changes to security group context restrictions

Changes to security group restrictions for contexts might not take effect immediately due to caching. To make sure settings are applied immediately, it is best practice for the organization administrator to refresh permissions once the change has been made. The **Refresh Permissions** button can be found at **User Settings**  **Account Integrations**.

### Remove groups from contexts

To make a context available _only_ to the administrators of the organization, you may remove all of the groups associated with a context. All other users will lose access to that context.

### Add and remove users from teams and groups

**GitHub OAuth app users:** CircleCI syncs GitHub team and LDAP groups every few hours. If a user is added or removed from a GitHub team or LDAP group, it can take up to a few hours to update CircleCI records. Access to the context will be removed at that point.

### Add and remove environment variables from restricted contexts

Addition and deletion of environment variables from a restricted context is limited to members of the context groups.

## Project restrictions

CircleCI enables you to restrict secret environment variables by adding project restrictions to contexts. Only Organization Admins may add or remove project restrictions to a new or existing context. After a project restriction is added to a context, only workflows associated with the specified project(s) will have access to the context and its environment variables.

Organization Admins have read/write access to all projects, and have unrestricted access to all contexts.

### Run workflows with a project restricted context

To invoke a workflow that uses a restricted context, the workflow must be part of the project the context is restricted to. If the workflow does not have access to the context, the workflow will fail with the `Unauthorized` status.

### Restrict a context to a project

You must be an **organization admin** to restrict a context though the method detailed below.

<Tabs>
<Tab title="CLI">

1.  Find the ID of the project you want to restrict access to by listing your projects:
    
    ```shell
    circleci project list
    ```
    
    Copy the ID of the project from the output.
    
2.  Add a project restriction to the context using the project ID:
    
    ```shell
    circleci context restriction create <context-name> --type project --value <project-id> --org <org-slug>
    ```
    
    To add restrictions for multiple projects, run the command once for each project ID.
    
3.  To verify the restrictions, list the context details:
    
    ```shell
    circleci context get <context-name>
    ```

</Tab>
<Tab title="Web app">

1.  Navigate to the **Org**  **Contexts** page of your organization in the [CircleCI web app](https://app.circleci.com/). The list of contexts will be visible.
    
2.  Select the name of an existing context, or select **Create Context** if you want to use a new context.
    
3.  Select **Add Project Restriction** to view the dialog box.
    
4.  Select the project name to add to the context, and select **Add**. Use of the context is now limited to the specified project. Currently, multiple projects must be added individually.
    
5.  You can now see a list of the defined project restrictions on the context page.
    
6.  If you have environment variables, they appear on the page. If there are none, you can select **Add Environment Variables** to add them to the context. Then select **Add** to finish. Use of the environment variables for this context is now limited to the specified projects.

</Tab>
</Tabs>

Only workflows under the specified projects may now use the context and its environment variables.

### Remove project restrictions from contexts

You must be an **organization admin** to remove projects from contexts though the method detailed below.

<Tabs>
<Tab title="CLI">

1.  Get the context details to find the restriction ID you want to remove:
    
    ```shell
    circleci context get <context-name>
    ```
    
2.  Delete the restriction using the restriction ID from the output:
    
    ```shell
    circleci context restriction delete <context-name> --restriction-id <restriction-id>
    ```

</Tab>
<Tab title="Web app">

1.  Navigate to **Org**  **Contexts** page in the [CircleCI web app](https://app.circleci.com/). The list of contexts will be visible.
    
2.  Select the name of the existing context for which you would like to modify restrictions.
    
3.  Select **X** next to the project restriction you would like to remove. The project restriction will be removed for the context. If there are no longer any project restrictions for the context, the context and its environment variables are now effectively unrestricted.

</Tab>
</Tabs>

## Expression restrictions

Restrict contexts by setting up _expression restrictions_. Expression restrictions are rules that [Pipeline Values](https://circleci.com/docs/guides/server/orchestrate/pipeline-variables/#pipeline-values) must match. Using expression restrictions allows you to create arbitrary constraints on the circumstances in which a context is available for use. For example, you may have a context containing credentials that are only used for deploying your code from your protected `main` branch:

```
pipeline.git.branch == "main" and not job.ssh.enabled and not (pipeline.config_source starts-with "api")
```

Tabs and new lines are considered whitespace so can be used to break long lines, but have no other significance. For example, the snippet above could also be written:

```
pipeline.git.branch == "main"
and not job.ssh.enabled
and not (pipeline.config_source starts-with "api")
```

You can set up expression restrictions using the context restriction API, or via the Context page (**Org**  **Contexts**  **Expression Restrictions**) in the CircleCI web app.

Rules are expressed in a small language that supports equality checks, numeric comparisons, and boolean `and`, `or`, and `not` operators.

### Set an expression restriction

You must be an organization administrator to set an expression restriction.

Follow these steps to set an expression restriction on a context:

<Tabs>
<Tab title="CLI">

Add an expression restriction to a context, where `<expression>` is a pipeline value expression such as `pipeline.git.branch == "main"`:

```shell
circleci context restriction create <context-name> --type expression --value "<expression>" --org <org-slug>
```

</Tab>
<Tab title="Web app">

. In the [CircleCI web app](https://app.circleci.com/), go to **Organization Settings**  **Contexts**. . Select the context you want to add an expression restriction to. . Select **Add Expression Restriction**. . Enter your expression in the text box and select **Add Expression Restriction** again to confirm.

</Tab>
<Tab title="API">

**Using server?** If you are using CircleCI Server, replace `[https://circleci.com](https://circleci.com)` with your server hostname when interacting with the CircleCI API.

1.  Set up your API authentication. Steps are available in the [API Developers Guide](https://circleci.com/docs/guides/server/toolkit/api-developers-guide/#add-an-api-token).
    
2.  You are going to need your organization ID. In the CircleCI web app select **Org** in the sidebar and copy your "Organization ID" somewhere safe.
    
3.  To get the ID for your context, list your contexts, as follows, substituting your organization ID:
    
    ```shell
    curl --request GET \
      --url 'https://circleci.com/api/v2/context?owner-id=<your-org-ID>&page-token=NEXT_PAGE_TOKEN' \
      --header "Circle-Token: ${CIRCLE_TOKEN}" \
      --header "Accept: application/json" \
      --header "Content-Type: application/json" | jq
    ```
    
4.  Copy the ID for your context from the previous API response.
    
5.  Create your context expression restriction, as follows, substituting your context ID and expression restriction:
    
    ```shell
    curl --request POST \
      --url https://circleci.com/api/v2/context/<your-context-ID>/restrictions \
      --header "Circle-Token: ${CIRCLE_TOKEN}" \
      --header 'content-type: application/json' \
      --data '{"restriction_type":"expression","restriction_value":"<your-expression-restriction>"}'
    ```

</Tab>
</Tabs>

### Examples

Allow the context only on the project’s `main` branch:

```
pipeline.git.branch == "main"
```

Allow the context only on the project’s `main` branch, or branches starting with `integration-test`:

```
pipeline.git.branch == "main" or pipeline.git.branch starts-with "integration-test"
```

Restrict a context to the `main` branch and disallow use in an SSH rerun:

```
pipeline.git.branch == "main" and not job.ssh.enabled
```

### Variables

[Pipeline Values](https://circleci.com/docs/guides/server/orchestrate/pipeline-variables/#pipeline-values) can be used as variables in an expression restriction. The exception to this is that `pipeline.trigger_parameters.*` pipeline values **cannot** be used. [Pipeline Parameters](https://circleci.com/docs/guides/server/orchestrate/pipeline-variables/#pipeline-parameters-in-configuration) **cannot** be used in expression restrictions.

Job-specific variables are also available to use in expressions, as follows:

| name | type | description |
| --- | --- | --- |
| `job.ssh.enabled` | boolean | `true` if SSH is enabled for the job, `false` otherwise |

If an expression references a variable that has no value set in the pipeline, the expression will _fail closed_ and prevent use of the context.

### Errors

Any errors evaluating an expression will _fail closed_ and prevent use of the context. Errors include the following:

*   Using a variable that does not exist.
    
*   Using a non-numeric value as an operand to the numeric comparison operators.
    
*   Using a non-string value as an operand to the starts-with operator.
    

### Operators

The operators you can use are described in the following table. You can also group sub-expressions with parentheses `(`, `)`. as in the example above.

<table><thead><tr><th>Operator type</th><th>Operators</th><th>Description</th></tr></thead><tbody><tr><td>Logical</td><td><code>and</code>, <code>or</code></td><td>These are short-circuiting boolean operators.</td></tr><tr><td>Equality</td><td><code>==</code>, <code>!=</code></td><td>String, numeric, and boolean equality. If the operands are of different types then <code>==</code> will evaluate <code>false</code>, and <code>!=</code> will evaluate <code>true</code>.</td></tr><tr><td>Equality</td><td><code>starts-with</code></td><td>String prefix equality, <code>"hello world" starts-with "hello"</code> evaluates as <code>true</code>. It is an error to use a non-string type as an operand.</td></tr><tr><td>Equality</td><td><code>matches</code></td><td>String pattern matching, <code>"hello world" matches /hello.*/</code> evaluates as <code>true</code>. It is an error to use a non-string type as an operand.</td></tr><tr><td>Numeric comparison</td><td><code>&gt;=</code>, <code>&gt;</code>, <code>⇐</code>, <code>&lt;</code></td><td>Numeric comparisons. It is an error to use a non-numeric type as an operand.</td></tr><tr><td>Negation</td><td><code>not</code></td><td><div><div><p>Boolean negation.</p></div><div><p>Note that <code>not</code> has very high precedence and so binds very tightly. Use sub-expressions to apply <code>not</code> to more complex expressions. For example, with <code>foo</code> being <code>true</code> and <code>bar</code> being <code>false</code>:</p></div><div><ul><li><p><code>not foo and bar</code> evaluates to <code>false</code></p></li><li><p><code>not (foo and bar)</code> evaluates to <code>true</code></p></li></ul></div></div></td></tr></tbody></table>

### Precedence

The following table shows operator precedence table, from weakest to strongest binding.

All operators are left associative. In practice, avoid operator chaining for anything other than `and` or `or`. Evaluation may cause type mismatches for other operators (see [Evaluation](#evaluation)).

| Operator | Associativity |
| --- | --- |
| `or` | left |
| `and` | left |
| `==` `!=` | left |
| `starts-with` |  |
| `>=` `>` `<=` `<` | left |
| `not` `!` |  |

### Literals

#### Numbers

Numeric literals are whole integers (longs). For example, `1` or `768`.

#### Strings

String literals are enclosed within double-quotes `" "`. The `\` character is used to escape an embedded quote, or to escape an embedded `\`.

For example, `"the quick brown fox"`, `"You can embed \" and \\ characters"`

#### Booleans

The boolean literals are `true` and `false`.

### Evaluation

An expression is evaluated to produce a single boolean `true` or `false` value.

Other than the boolean value `false`, all values ultimately evaluate as `true`.

A variable evaluates to the variable’s value. If the variable does not exist then the expression is immediately considered to have evaluated as `false`. In other words, expression evaluation will _fail closed_ when it encounters an unknown variable.

As an expression is evaluated, the result of an operator is effectively embedded "in place" as the evaluation continues. For example, to evaluate the following:

```
pipeline.git.branch == "main"
and not job.ssh.enabled
and not (pipeline.config_source starts-with "api")
```

where the values are:

*   `pipeline.git.branch` is `"main"`.
    
*   `job.ssh.enabled` is `false`.
    
*   `pipeline.config_source` is `"api"`.
    
    1.  Variable lookup: replace `pipeline.git.branch` with its value:
        
        1.  `"main" == "main" and not job.ssh.enabled and not (pipeline.config_source starts-with "api")`
            
        
    2.  Evaluate `"main" == "main"`:
        
        1.  `true and not job.ssh.enabled and not (pipeline.config_source starts-with "api")`
            
        
    3.  Variable lookup: replace `job.ssh.enabled` with its value:
        
        1.  `true and not false and not (pipeline.config_source starts-with "api")`
            
        
    4.  Evaluate `not false`:
        
        1.  `true and true and not (pipeline.config_source starts-with "api")`
            
        
    5.  Evaluate `true and true`:
        
        1.  `true and not (pipeline.config_source starts-with "api")`
            
        
    6.  Variable lookup: replace `pipeline.config_source` with its value:
        
        1.  `true and not ("api" starts-with "api")`
            
        
    7.  Evaluate `("api" starts-with "api")`
        
        1.  `true and not true`
            
        
    8.  Evaluate `not true`:
        
        1.  `true and false`
            
        
    9.  Evaluate `true and false`:
        
        1.  `false`
            
        
    10.  The result is `false`.
         
    

## Delete a context

To delete a context, follow the steps below:

If the context is restricted with a group other than `All members`, you must be a member of that security group to complete this task.

<Tabs>
<Tab title="CLI">

Run the following command, replacing `<context-name>` with the name or ID of the context you want to delete. You can use `circleci context list` to find the name or ID of the context:

```shell
circleci context delete <context-name>
```

</Tab>
<Tab title="Web app">

1.  In the CircleCI web app, go to **Org**  **Contexts**.
    
2.  Select the **X** icon for the context you want to delete. A confirmation dialog appears.
    
3.  Type "DELETE" in the field and then select **Delete Context**. The context and all associated environment variables will be deleted.

</Tab>
</Tabs>

If a _deleted_ context is used in a job, the job will fail and show an error.

## Environment variable usage

Environment variables are used according to a specific precedence order, as follows:

1.  Environment variables declared [Inside a Shell Command](https://circleci.com/docs/guides/server/security/set-environment-variable/#set-an-environment-variable-in-a-shell-command) in a `run` step, for example `FOO=bar make install`.
    
2.  Environment variables declared with the `environment` key [For a `run` Step](https://circleci.com/docs/guides/server/security/set-environment-variable/#set-an-environment-variable-in-a-step).
    
3.  Environment variables set with the `environment` key [For a Job](https://circleci.com/docs/guides/server/security/set-environment-variable/#set-an-environment-variable-in-a-job).
    
4.  Special CircleCI environment variables defined on the [Project Values and Variables](https://circleci.com/docs/reference/variables/#built-in-environment-variables) page.
    
5.  Context environment variables (assuming the user has access to the context).
    
6.  [Project-Level Environment Variables](https://circleci.com/docs/guides/server/security/set-environment-variable/#set-an-environment-variable-in-a-project) set on the **Project Settings** page in the web app.
    

Environment variables declared inside a shell command `run` step, for example `FOO=bar make install`, will override environment variables declared with the `environment` and `contexts` keys. Environment variables added on the contexts page will take precedence over variables added on the **Project Settings** page.

### Add an environment variable to a context

**Using server?** If you are using CircleCI Server, replace `[https://circleci.com](https://circleci.com)` with your server hostname when interacting with the CircleCI API.

<Tabs>
<Tab title="CLI">

To add an environment variable to a context using the CLI, follow these steps:

1.  If you have not already done so, find the right context name that will contain the new environment variable:
    
    ```shell
    circleci context list
    ```
    
2.  Store a new environment variable under that context:
    
    ```shell
    circleci context secret set <context-name> --name <env-var-name> --value <env-var-value>
    ```

</Tab>
<Tab title="API">

To create an environment variable using the API, call the [Add Environment Variable](https://circleci.com/docs/api/v2/#operation/addEnvironmentVariableToContext) endpoint with the appropriate request body. For this request, replace the `context-id` and the `env-var-name` with the ID for the context and the new environment variable name. The request body must include a `value` key containing the plain text secret as a string.

</Tab>
</Tabs>

### Remove an environment variable from a context

Removing an environment variable from a context deletes the environment variable from your account.

**Using server?** If you are using CircleCI Server, replace `[https://circleci.com](https://circleci.com)` with your server hostname when interacting with the CircleCI API.

<Tabs>
<Tab title="CLI">

To remove an environment variable from a context using the CLI, follow these steps:

1.  If you have not already done so, find the context name that contains the environment variable you wish to delete:
    
    ```shell
    circleci context list
    ```
    
2.  Confirm the environment variable exists within that context:
    
    ```shell
    circleci context get <context-name>
    ```
    
3.  Delete the environment variable:
    
    ```shell
    circleci context secret delete <context-name> --name <secret-name>
    ```

</Tab>
<Tab title="API">

To delete an environment variable using the API, call the [Delete environment variable](https://circleci.com/docs/api/v2/#operation/addEnvironmentVariableToContext) endpoint.

For this request, replace the `context-id` and the `env-var-name` with the ID for the context and the environment variable name to update.

</Tab>
</Tabs>

### Rotate environment variables with the CLI or API

Rotation refers to the process of updating a secret’s value without deleting it or changing its name.

Because environment variables can be shared, passed around between employees and teams, and exposed inadvertently, it is good practice to periodically rotate secrets. You can automate this process, for example, running a script when an employee leaves the company, or when a secret may have been compromised.

Context environment variables can be rotated using CircleCI’s CLI or API.

**Using server?** If you are using CircleCI Server, replace `[https://circleci.com](https://circleci.com)` with your server hostname when interacting with the CircleCI API.

<Tabs>
<Tab title="CLI">

To rotate an environment variable using the CLI, follow these steps:

1.  Find the context name that contains the variable you would like to rotate:
    
    ```shell
    circleci context list --org <org-slug>
    ```
    
2.  Find the environment variable to rotate within that context:
    
    ```shell
    circleci context get <context-name>
    ```
    
3.  Update the existing environment variable, replacing `<env-var-name>` with the name of the environment variable you chose in Step 2:
    
    ```shell
    circleci context secret set <context-name> --name <env-var-name> --value <new-value>
    ```

</Tab>
<Tab title="API">

To rotate an environment variable from the API, call the [Update environment variable](https://circleci.com/docs/api/v2/#operation/addEnvironmentVariableToContext) endpoint with the appropriate request body. For this request, replace the `context-id` and the `env-var-name` with the ID for the context and the environment variable name to update. The request body must include a `value` key containing the plain text secret as a string.

</Tab>
</Tabs>

## Secrets masking

Environment variables and contexts may hold project secrets or keys that perform crucial functions for your applications. Secrets masking provides added security within CircleCI by obscuring environment variables in the job output when `echo` or `print` is used.

Secrets masking is applied to environment variables set within **Project Settings** or **Contexts** in the web app.

The value of the environment variable or context will _not_ be masked in the job output if:

*   the value of the environment variable is less than 4 characters
    
*   the value of the environment variable is equal to one of `true`, `True`, `false`, or `False`
    

Secrets masking will only prevent values from appearing in your job output. Invoking a Bash shell with the `-x` or `-o xtrace` options may inadvertently log unmasked secrets (refer to [Using Shell Scripts](https://circleci.com/docs/guides/orchestrate/using-shell-scripts/)). If your secrets appear elsewhere, such as test results or artifacts, they will not be masked. Additionally, values are still accessible to users [Debugging Builds With SSH](https://circleci.com/docs/guides/execute/ssh-access-jobs/).

The secrets masking feature exists as a preventative measure to catch unintentional display of secrets at the output. Best practice is to avoid printing secrets to the output. Secrets masking can be bypassed in many ways, either accidentally or maliciously. For example, any process that reformats the output of a command or script could remove secrets masking.

## Troubleshooting

## See also

*   [Introduction to Environment Variables](https://circleci.com/docs/guides/server/security/env-vars/).
    
*   [Using Workflows to Orchestrate Jobs](https://circleci.com/docs/guides/server/orchestrate/workflows/).