w3tc_environment_variables

Persistent W3 Total Cache Config in Elastic Beanstalk

I stumbled upon a problem with the W3 Total Cache plugin for WordPress when I have been deploying to Elastic Beanstalk. I’d followed my usual routine for installing/activating a plugin:

  1. Add plugin to locally checked out code repo and commit.
  2. Push back to origin.
  3. Let CircleCI handle the deployment.
  4. Activate the plugin via the WordPress admin dashboard
  5. Perform plugin-specific config.

Everything seemed to be working well: assets were being stored in S3 and served via CloudFront. However, following a deploy, I noticed assets ceased to be correctly served from the CDN.

After some digging, I realised that the W3TC plugin writes out it’s configuration to a sub-directory of the WordPress installation, specifically wp-content/w3tc-config. This isn’t ideal when deploys wipe away local changes and servers can be terminated and replaced in an instant!

Strangely, I was unable to find any guides online for how to solve this problem. AWS’ own guide on installing WordPress on Elastic Beanstalk suggests this odd workflow:

  • Install the W3TC plugin via the WordPress admin dashboard.
  • Activate and configure W3TC via the WordPress admin dashboard.
  • Download the application code from the application server.
  • Create a new code release and upload to the Elastic Beanstalk application environment.

I reached out on Twitter to see if anybody could provide an answer, and an ex-colleague had this answer for me:

He also shared these words of wisdom:

With that in mind, I started looking at automating W3TC with WP-CLI. Turns out it does have some WP-CLI integrations, but nothing related to configuration management.

So, after much deliberation, I settled upon my own solution to the problem by adapting AWS’ own guide:

  1. Install the W3TC plugin via the WordPress admin dashboard.
  2. Activate and configure W3TC via the WordPress admin dashboard.
  3. Download the W3TC plugin config into the local copy of the repository.
  4. Edit the wp-content/w3tc-config/master.php file so that configuration values are pulled from server environment variables, e.g.:

    'cdn.cf.key' => $_SERVER['W3TC_AWS_ACCESS_KEY_ID'],
    'cdn.cf.secret' => $_SERVER['W3TC_AWS_SECRET_ACCESS_KEY'],
    'cdn.cf.bucket' => $_SERVER['W3TC_CF_BUCKET_NAME'],
    'cdn.cf.id' => $_SERVER['W3TC_CF_DISTRIBUTION_ID'],
    'cdn.cf.cname' => array(
    0 => $_SERVER['W3TC_CF_DISTRIBUTION_CNAME'],
    )
  5. Configure the necessary environment variables in the Elastic Beanstalk application environment.
  6. Commit the new config files to the repo and push back to origin.
  7. Let CircleCI handle the deploy.

As you can see from the gist, I’ve only started by configuring the CDN component of the module, but the method could be extended to configure other components.