Making CircleCI 2.0 Environment Variables Behave

CircleCI 2 environment variables don’t behave as you would expect, or as documented so here are a few workarounds.

Use in caching

The CircleCI 2 documentation states that it should be possible to use the {{ .Environment.variableName }} as a cache key. What it fails to mention is that only works with CircleCI provided environment variables, it does not work with ones set either using your CircleCI config or computed ones set in code such as

      - run:
          name: Configure env
          command: 'export CACHE_DATE=$(date +%F)' >> $BASH_ENV

The work around is to write your variable to a file then perform a checksum on that. This particular sample will give you a cache that expires at midnight every day.

      - run:
          # Print the env var to a file is a hack until CircleCI fix their env var handling
          name: Configure env
          command: echo $(date +%F) > ~/.cache-date.txt
      - restore_cache:
            - data-cache-{{ checksum "~/.cache-date.txt" }}

Use in Apache and PHP

Some of our code behaves subtly different in the CI environment to bypass caching and what not. I would’ve expected both the CircleCI environment variables and the configured ones to be passed through to Apache, the reality is none are passed through. This fix to this is to write them into an config file.

version: 2
    working_directory: ~/repo
      - image: circleci/php:5.6-apache
      - run:
          name: Configure Apache
          command: |
            sudo touch /etc/apache2/envvars
            sudo chmod 0777 /etc/apache2/envvars
            echo 'export CI="TRUE"' >> /etc/apache2/envvars
            echo 'export CIRCLECI="TRUE"' >> /etc/apache2/envvars
            sudo service apache2 restart