Sobes.tech
Middle

How do you encrypt variables in CI?

sobes.tech AI

Answer from AI

I encrypt variables using the built-in features of the CI system. Each CI system, whether it is GitLab CI/CD, GitHub Actions, or Jenkins, has functions for securely storing secrets. These variables are accessible only at certain stages of the build pipeline and are not displayed in logs.

For example, in GitLab CI:

  • Environment Variables: You can save variables at the group or project level. They are marked as "protected" and "masked". "Protected" variables are used only in protected branches and tags, "masked" hide the value in logs if it fully matches.

    # .gitlab-ci.yml
    # Access to variable via environment
    script:
      - echo $MY_SECRET_VARIABLE
    
  • HashiCorp Vault: Integration with an external secrets storage, such as HashiCorp Vault. GitLab CI can authenticate with Vault and retrieve secrets during pipeline execution.

    # .gitlab-ci.yml
    variables:
      VAULT_SERVER: "https://vault.example.com"
      VAULT_AUTH_ROLE: "gitlab-ci"
      VAULT_AUTH_PATH: "auth/kubernetes"
      VAULT_SECRETS: |
        MY_SECRET_KEY: vault/path/to/secret:key
    script:
      - echo $MY_SECRET_KEY # Variable is automatically loaded from Vault
    

In GitHub Actions:

  • Secrets: You can store secrets at the repository or organization level. They are accessible in workflows via ${{ secrets.MY_SECRET }}. Values are not displayed in logs and cannot be retrieved via API after being saved.

    # .github/workflows/main.yml
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
        - name: Use secret
          run: echo ${{ secrets.MY_SECRET }}
    

In Jenkins:

  • Credentials Plugin: Allows storing various types of credentials (username/password, secret text, SSH key) in encrypted form. They can be accessed in Jenkinsfile or through the graphical interface.

    // Jenkinsfile (Declarative Pipeline)
    pipeline {
        agent any
        stages {
            // During the build process where variables are used, they are usually available as environment variables.
            stage('Use Secret') {
                steps {
                    withCredentials([string(credentialsId: 'my-secret-id', variable: 'MY_VAR')]) {
                        sh 'echo $MY_VAR'
                    }
                }
            }
        }
    }
    

General principles:

  • Minimize scope: Secrets are available only at the stages and environments where they are needed.
  • Mask logs: Secret values are hidden in the pipeline execution logs.
  • Role separation: Only authorized users or systems can add/change secrets.
  • Use external storage: For more complex scenarios and centralized secret management, Vault or similar solutions are used.