Amazon EFS: Changing Wordpress upload directory to

2019-08-24 10:45发布

问题:

I have multiple AWS EC2 instances which are updated from a Git repository via CodeDeploy. However, since keeping the wp-content/uploads folder in Git is messy and hard to maintain, I'm instead trying to move all uploads to a directory which I have mounted as an EFS filesystem. That way I should be able to share the uploads between multiple EC2 instances.

However, now I'm running into a new problem; there's no way for me to set the WP uploads folder to be outside of the WP root.

WordPress is located at /opt/bitnami/apps/wordpress/htdocs, which is also where our domain points. The EFS system is mounted to /home/bitnami/efs. Since the EFS directory is located outside of the WP root there's no way for me to link to it.

I have gotten this to work using a symlink directing the default wp-content/uploads folder to my desired path; however, this doesn't really solve my issue since I can't rely on the symlink to not be overwritten during CodeDeploy deployments.

So my questions are as follows:

  1. Is it possible to have this setup work without using a symlink, so I can make deployments without worrying about by uploads being affected?

  2. If a symlink is the only/best way to make this work, is there any way to add the symlink to the git repository, or any other way to make absolutely sure it persists during CodeDeploy deployments?

回答1:

You can directly mount your EFS to /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads to avoid symlinks.

In your appspec.yml add two hooks:

hooks:
    BeforeInstall:
      - location: /deploy/BeforeInstall.sh
        timeout: 3000
        runas: root
    AfterInstall:
      - location: /deploy/AfterInstall.sh
        timeout: 3000
        runas: root

Then create directory deploy and two files in it BeforeInstall.sh and AfterInstall.sh

BeforeInstall.sh unmount the EFS if its mounted

#!/bin/bash
if mount | grep /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads > /dev/null; then
    sudo umount /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads
fi

Then mount EFS again via AfterInstall.sh after deployment

#!/bin/bash
sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 fs-fxxxxxx.efs.us-west-2.amazonaws.com:/ /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads

Note: You can also mount entire wp-contents directory, not just uploads folder, so that update in themes and plugins also get reflected in other EC2s automatically.

Also, symlink is a better solution, so you don't have to ever worry about accidentally removing the EFS mount during deployment if umount ever fails. You can just recreate symlink again after deployment using AfterInstall hook and add code in file AfterInstall.sh

#!/bin/bash
ln -s /home/bitnami/efs /opt/bitnami/apps/wordpress/htdocs/wp-content/uploads