Deploy scripts must be idempotent and deleting existing code folder is the simplest way to achieve this

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-03-02

When I ran the following command to deploy, I noticed they were erratically failing, saying the .env.production file was not available on the system (despite the fact that the file should have already been copied over and sporadically was available when I ran this same script). Look at the code and guess at the issue:

# Executed from the folder `code/docker-jista`
scp -p -r $(pwd) schillerchorchat:webapp

ssh schillerchorchat << EOF
  cd webapp
  mv .env.production .env
  ...
EOF

The first issue I thought of was that mv was not idempotent. On the first run .env.production is available. But on the second, it's already been renamed to .env so of course it's unavailable. So here I could consider using cp instead (messy). Or zoom out and run the command that copies over the .env.production file over every time I re-execute, i.e. make the unit of retrying larger and more cohesive.

The second issue was trickier : The issue was that scp when run the first time put the current dir into ~/webapp on the server. The second time, though, it put it into ~/webapp/docker-jista

The simple fix was to start from scratch each time and avoid this class of errors:

ssh schillerchorchat sudo rm -rf webapp
scp -p -r $(pwd) schillerchorchat:webapp