How to set up automated environment tasks

Goal

To have one more more environments automatically backed up through backups triggered without manual intervention.

Assumptions

  • Access to a project hosted on Platform.sh
  • Your project account has administrator rights
  • Knowledge on using the project web interface or the Platform.sh CLI
  • CLI tool set up in the environment, as described in this how-to

Problems

The backup process is not automated and requires a manual trigger using the CLI or web interface.

Steps

1. Check the CLI tool is correctly installed in the environment

After logging in with SSH in the environment, you should be able to run platform and see the welcome prompt, together with a list of your projects.

2. Add a cron for automated environment backups

Edit your .platform.app.yaml file and add the backup command in a cron. Example:

crons:
    auto_backup:
        # The cron task will run everyday at 4 am (UTC)
        spec: '0 4 * * *'
        cmd: |
            if [ "$PLATFORM_BRANCH" = master ]; then
                 platform backup:create --yes --no-wait
            fi

The PLATFORM_BRANCH variable check ensures automatic backups are done only on the master environment. The --yes flag skips user interaction for the backup command. Ensure the --no-wait parameter is added to the command, in order to make the operation non-blocking (otherwise, your site will be down until the backup operation is completed).

3. Add a cron for automated SSL certificate renewal

The provided Let’s Encrypt certificates have to be renewed every 3 months. The renewal is done automatically on every deployment, but if you do not deploy that often it is possible to have the SSL certificate expire. In order to ensure this does not happen, you can configure a cron job to automatically redeploy your environment. If there are no code changes, this will happen very fast and ensure your SSL certificate is refreshed.

To do this, you need to edit your .platform.app.yaml just like before and add a cron job like in this example:

crons:
    auto_renewcert:
        # Force a redeploy at 10 am (UTC) on the 1st and 15th of every month.
        spec: '0 10 1,15 * *'
        cmd: |
            if [ "$PLATFORM_BRANCH" = master ]; then
                platform redeploy --yes --no-wait
            fi

Like above, PLATFORM_BRANCH variable check ensures the redeployment is done only on the master environment.

Conclusion

After setting up the CLI tool in the environment, we learned how to use it in order to trigger various maintenance tasks for the project.