> ## Documentation Index
> Fetch the complete documentation index at: https://www.1password.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Load secrets into the environment

export const CodeResult = ({children, resultLang, wrap, expandable}) => {
  const parseChildren = () => {
    let language = "text";
    let codeContent = "";
    const extractText = node => {
      if (typeof node === "string") {
        return node;
      }
      if (Array.isArray(node)) {
        return node.map(extractText).join("");
      }
      if (node?.props?.children) {
        return extractText(node.props.children);
      }
      return "";
    };
    const extractLanguage = node => {
      if (!node) return null;
      if (node.props?.className) {
        const className = node.props.className;
        const langMatch = className.match(/language-(\w+)/);
        if (langMatch) {
          return langMatch[1];
        }
      }
      if (node.props?.["data-language"]) {
        return node.props["data-language"];
      }
      if (node.props?.language) {
        return node.props.language;
      }
      return null;
    };
    if (typeof children === "string") {
      codeContent = children;
    } else if (Array.isArray(children)) {
      codeContent = extractText(children);
      for (const child of children) {
        const detectedLang = extractLanguage(child);
        if (detectedLang) {
          language = detectedLang;
          break;
        }
      }
    } else if (children?.props) {
      const detectedLang = extractLanguage(children);
      if (detectedLang) {
        language = detectedLang;
      }
      codeContent = extractText(children);
    }
    const parts = codeContent.split("#code-result");
    if (parts.length < 2) {
      return {
        command: codeContent.trim(),
        result: null,
        language,
        defaultOpen: false
      };
    }
    const resultText = parts[1].trim();
    const defaultOpen = resultText.startsWith("open");
    const cleanResult = defaultOpen ? resultText.slice(4).trim() : resultText;
    return {
      command: parts[0].trim(),
      result: cleanResult,
      language,
      defaultOpen
    };
  };
  const {command, result, language, defaultOpen} = parseChildren();
  const [isOpen, setIsOpen] = useState(defaultOpen);
  if (!result) {
    return children;
  }
  return <div className="codeblock_accordion not-prose mb-4">
      {}
      <div className="[&>*]:!mb-0 [&>*]:!rounded-b-none">
        <CodeBlock language={language} children={command} wrap={wrap} expandable={expandable} />
      </div>

      {}
      <div className="see_results_container border-t-0 bg-gray-100/80 dark:bg-gray-800/80 overflow-hidden" style={{
    marginTop: "-0.25rem"
  }}>
        <button onClick={() => setIsOpen(!isOpen)} className="w-full px-4 py-2.5 flex items-center gap-1 text-left text-[14px] font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-200/60 dark:hover:bg-gray-700/60 transition-all duration-150" aria-expanded={isOpen}>
          {isOpen ? <Icon icon="caret-down" size="14" iconType="solid" /> : <Icon icon="caret-right" size="14" iconType="solid" />}

          <span>See result...</span>
        </button>

        {isOpen && <div className="[&>*]:!mt-0 [&>*]:!rounded-t-none border-t border-[var(--op-border-ui)] dark:border-[var(--op-border-ui-dark)]">
            <CodeBlock language={resultLang || language} children={result} wrap={wrap} expandable={expandable} />
          </div>}
      </div>
    </div>;
};

With [`op run`](/cli/reference/commands/run/), you can provide your project secrets directly from 1Password to an application or script as environment variables at runtime. You can use `op run` with [1Password Environments](/environments), environment variables set to [secret references](/cli/secret-references), or a combination of both.

1Password CLI loads the specified secrets, then runs the provided command in a subprocess with the secrets made available as environment variables only for the duration of the process. This allows you to avoid hardcoding any plaintext secrets and quickly switch between different sets of secrets for different development contexts.

## Choose your configuration

1Password CLI provides multiple methods to load your project secrets:

* **[1Password Environments (beta)](/environments)** allow you to create Environments in 1Password that contain all your environment variables for a specific workflow. You can share Environments with your team and create separate Environments for each project, application, or development context (like staging or production).

* **[Secret references](/cli/secret-references)** are URIs that point to where a secret is stored in your 1Password account. A secret reference uses the names or unique identifiers of the vault, item, section, and field where the secret is stored in 1Password. You can set environment variables to secret references on the command line or use secret references in your `.env` files. Secret references require more manual setup than 1Password Environments to switch between different sets of environment variables for different contexts, or create shared team workflows.

* **Hybrid approach**: You can use `op run` to load variables from a 1Password Environment alongside secret references from `.env` files or exported environment variables.

<Tip>
  Authenticate with a [1Password Service Account](/service-accounts/) to follow the [principle of least privilege](/cli/best-practices/). You can scope service account access to specific vaults and 1Password Environments so that processes in your authorized terminal session can only access secrets required for a given purpose.
</Tip>

<Warning>
  You should assume that processes on your computer can access the environment of other processes run by the same user. Be aware of this when supplying secrets through environment variables.
</Warning>

## Requirements

<Tabs queryString="workflow-type" groupId="workflow">
  <Tab value="environment" title="1Password Environment (beta)">
    1. [Sign up for 1Password.](https://1password.com/pricing/password-manager)
    2. [Install the latest beta build of 1Password CLI](https://app-updates.agilebits.com/product_history/CLI2#beta), version `2.33.0-beta.02` or later.
  </Tab>

  <Tab value="secret-references" title="Secret references">
    Before you can load secrets into the environment, you'll need to:

    1. [Sign up for 1Password.](https://1password.com/pricing/password-manager)
    2. [Install 1Password CLI.](/cli/get-started#step-1-install-1password-cli)
  </Tab>
</Tabs>

## Step 1: Store your project secrets in 1Password

<Tabs queryString="workflow-type" groupId="workflow">
  <Tab value="environment" title="1Password Environment (beta)">
    To store your project secrets in a 1Password Environment, [follow the steps to create an Environment](/environments), then import a `.env` file or manually add your environment variables.
  </Tab>

  <Tab value="secret-references" title="Secret references">
    To use secret references, save your project secrets as items in a vault in your 1Password account.

    Then follow the instructions to create secret references for each item using your preferred method:

    * [With the 1Password desktop app](/cli/secret-reference-syntax#with-the-1password-desktop-app): Copy secret references from the app.
    * [With 1Password for VSCode](/vscode#get-values): Insert secret references from 1Password as you edit code.
    * [With 1Password CLI](/cli/secret-reference-syntax#with-1password-cli): Get secret references for one or multiple fields with `op item get`.
    * Use the [secret reference syntax rules](/cli/secret-reference-syntax#syntax-rules) to write secret references manually.
  </Tab>
</Tabs>

## Step 2: Pass the secrets to the application

<Tabs queryString="workflow-type" groupId="workflow">
  <Tab value="environment" title="1Password Environment (beta)">
    To pass your environment variables from 1Password to an application or script:

    1. Open the 1Password app and navigate to **Developer** > **Environments**.
    2. Select the Environment where your project secrets are stored, then select **Manage environment** > **Copy environment ID**.
    3. Use `op run --` with the command for starting the application or script. 1Password will run the provided command in a subprocess with the secrets made available as environment variables for the duration of the process.

       ```shell theme={null}
       op run --environment <environmentID> -- <command>
       ```

       For example:

       ```shell theme={null}
       op run --environment blgexucrwfr2dtsxe2q4uu7dp4 -- ./my-script.sh
       ```
  </Tab>

  <Tab value="secret-references" title="Secret references">
    <h3>Step 1: Map secret references to environment variables</h3>

    To pass secrets to an application or script using `op run` and [secret references](/cli/secret-references), you must first map the secret references to the appropriate environment variables. To do this, you can set environment variables to secret references using an environment file or export them on the command line.

    <Tabs queryString="secret-reference-options" groupId="secret-reference-options">
      <Tab value="env-files" title="Environment file">
        Environment (`.env`) files allow you to define multiple environment variables as secret references with `KEY=VALUE` statements separated by a newline.

        To use an environment file with `op run`, add key-value pairs for each of your project secrets with the value set to a [secret reference](/cli/secret-references). For example:

        ```shell title="prod.env" theme={null}
        AWS_ACCESS_KEY_ID="op://development/aws/Access Keys/access_key_id"
        AWS_SECRET_ACCESS_KEY="op://development/aws/Access Keys/secret_access_key"
        ```

        <Accordion title="Environment file syntax rules">
          The `.env` file parsing engine follows the following rules:

          * Environment variables are defined as `KEY=VALUE` statements separated by a newline.

          * Variables can span multiple lines if they are enclosed in either `'` or `"`:

            ```
            MY_VAR = "this is on the first line
            and this is on the second line"
            ```

          * Empty lines are skipped.

          * Lines beginning with `#` are treated as comments. Comments can also be placed inline after `KEY=VALUE` statements.

          * Empty values become empty strings. For example, `EMPTY=` will set the environment variable `EMPTY` to the empty string.

          * If a value is surrounded by single or double quotes, these quotes do not end up in the evaluated value. So `KEY="VALUE"` and `KEY='VALUE'` both evaluate to `KEY` and `VALUE`.

          * Occurrences of `$VAR_NAME` or `${VAR_NAME}` are replaced with their respective value from the environment.

          * A variable defined in a .env file can be referred to later in the same file:

            ```
            SOME_VAR = value
            OTHER_VAR = ${SOME_VAR}
            ```

          * Special characters can be escaped with `\`. For example, `MY_VAR = "\$SOME_VAR that is not actually replaced."` results in the following value for MY\_VAR: `$SOME_VAR that is not actually replaced.`.

          * Inner quotes are maintained, so `JSON={"foo":"bar"}` evaluates to `JSON` and `{"foo":"bar"}`.

          * Variables do not get replaced in values that are enclosed in single quotes. So `KEY='$SOME_VAR'` evaluates to `KEY` and `$SOME_VAR`.

          * Template syntax can be used in the `VALUE` to inject secrets. The `KEY` can only contain template variables.

          * Template parsing is performed after `.env` file parsing, so you cannot use the former to construct the latter.

          * Leading and trailing whitespace of both `KEY` and `VALUE` segments are ignored, so `KEY = VALUE` is parsed the same as `KEY=VALUE`.

          * Single and double quoted values maintain both leading and trailing whitespace, so `KEY=" some value "` evaluates to `KEY` and <code> some value </code>.

          * These files should use UTF-8 character encoding.
        </Accordion>

        ### Optional: Differentiate between environments

        <Tip>
          If you need to pass secrets for multiple environments, we recommend using 1Password Environments instead of secret references. 1Password Environments allow you to more easily organize, share, and pass environment variables for multiple contexts.
        </Tip>

        If you have different sets of secrets for different environments, like staging and production, you can check a single environment file into source control and include a variable within the secret references to represent the context. You can then set the variable to the appropriate context when you pass the file to `op run`.

        To use this approach, you must organize your project secrets in 1Password into different vaults for each environment, with each item's fields structured in the same way. For example: `dev/mysql/password` and `prod/mysql/password`.

        Then, include an externally set variable (`$VARIABLE_NAME`) in place of the vault name for each secret reference in your environment file.

        For example, in the following environment file, `$APP_ENV` is the externally set environment variable. It can be set to `dev` or `prod` to load secrets from either the `dev` vault or the `prod` vault in 1Password.

        ```shell title="app.env" theme={null}
        MYSQL_DATABASE = "op://$APP_ENV/mysql/database"
        MYSQL_USERNAME = "op://$APP_ENV/mysql/username"
        MYSQL_PASSWORD = "op://$APP_ENV/mysql/password"
        ```
      </Tab>

      <Tab value="export" title="Command line">
        You can individually export environment variables as [secret references](/cli/secret-reference-syntax/) from the command line.

        For example, to set the variable `GITHUB_TOKEN` to a secret reference URI that points to the `personal_token` field within a `credentials` section in a `GitHub` item:

        <Tabs groupId="shells">
          <Tab value="bash-zsh-sh" title="Bash, Zsh, sh" default>
            ```shell theme={null}
            export GITHUB_TOKEN=op://development/GitHub/credentials/personal_token
            ```
          </Tab>

          <Tab value="fish" title="fish" default>
            ```shell theme={null}
            set -x GITHUB_TOKEN op://development/GitHub/credentials/personal_token
            ```
          </Tab>

          <Tab value="powershell" title="PowerShell" default>
            ```powershell theme={null}
            $Env:GITHUB_TOKEN = "op://development/GitHub/credentials/personal_token"
            ```
          </Tab>
        </Tabs>
      </Tab>
    </Tabs>

    <h3>Step 2: Pass the resolved secret references to the application</h3>

    <Tabs queryString="secret-reference-options" groupId="secret-reference-options">
      <Tab value="env-files" title="Environment file">
        To use an environment file with `op run`, specify the path to the environment file using the `--env-file` flag:

        ```shell theme={null}
        op run --env-file="./prod.env" -- aws
        ```

        If you structured your environment file to load secrets for multiple environments, make sure to also set the variable for the vault (in the example below, `APP_ENV`).

        For example, to pass secrets from the `dev` vault to an application running in the development environment:

        <Tabs groupId="shells">
          <Tab value="bash-zsh-sh-fish" title="Bash, Zsh, sh, fish" default>
            ```shell theme={null}
            APP_ENV=dev op run --env-file="./app.env" -- myapp deploy
            ```
          </Tab>

          <Tab value="powershell" title="PowerShell">
            1. Set the `$APP_ENV` variable:

               ```powershell theme={null}
               $ENV:APP_ENV = "dev"
               ```

            2. Run `op run` with the environment file:

               ```powershell theme={null}
               op run --env-file="./app.env" -- myapp deploy
               ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab value="export" title="Command line">
        If you exported environment variables as secret references on the command line, use `op run --` with the command to start the application or script. 1Password will run the provided command in a subprocess with the secrets made available as environment variables for the duration of the process.

        ```shell theme={null}
        op run -- <command>
        ```

        For example:

        ```shell theme={null}
        op run -- gh
        ```

        <Tip>
          **Expand variables in a subshell**

          When you reference a variable like `$MY_VAR` in the same command where you call `op run`, your shell expands `$MY_VAR` before `op run` can substitute the secret reference. For example, a command like the following will pass the secret reference URI instead of the secret value from 1Password:

          ```shell theme={null}
          MY_VAR=op://vault/item/field op run --no-masking -- echo "$MY_VAR"
          ```

          To make sure `op run` substitutes the secret before the variable expands, run the command to expand the variable in a subshell:

          <CodeResult>
            ```shell theme={null}
            MY_VAR=op://vault/item/field op run --no-masking -- sh -c 'echo "$MY_VAR"'
            #code-result open
            skdjfs7dyrwhk4jhref
            ```
          </CodeResult>
        </Tip>
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

<Tip>
  **Use both methods together**

  You can load environment variables from an Environment in combination with secret references from a `.env` file or flag. For example:

  ```shell theme={null}
  op run --environment <ID> --env-file="./extra-secrets.env" -- <command>
  ```
</Tip>

## Next step: Run in production

Now that the application works locally, choose how to load your secrets in production or CI/CD:

* **[1Password Service Account](/service-accounts/use-with-1password-cli)**: Automate access with a service account token. Service accounts support both secret references and 1Password Environments.
* **[1Password Connect Server](/connect/cli/)**: Best for self-hosting within your own infrastructure. Connect only supports secret references and does not currently support 1Password Environments.

## Learn more

* [Use 1Password Service Accounts with 1Password CLI](/service-accounts/use-with-1password-cli)
* [Use 1Password Connect Server with 1Password CLI](/connect/cli#continuous-integration-ci-environments)
* [Load secrets into config files](/cli/secrets-config-files/)
* [Secret reference syntax](/cli/secret-reference-syntax/)
* [Template syntax](/cli/secrets-template-syntax/)
* [Workflow: Secure your deployments](/get-started/secure-deployment)
