Google what you don’t know. Try the Stack Overflow most upvoted answer. Type history in the command line, copy the steps that worked.
Let’s face it, we as engineers we don’t know all the answers, and most of the time we google them. It works because is a brute force method: we search, we try, we search, we try until we succeed.
We are compiling recipes, that soon will be old. We are not gaining any wisdom from the underlying principles of what we are doing in each step.
So let’s elaborate a bit more on the steps involved in a “Production Runbook for Deploying Python scripts in Ubuntu.“
- sudo apt install git
- git config –global user.name “Your Servername”
- git config –global user.email “email@example.com”
- cat .ssh/id_rsa.pub
- git clone firstname.lastname@example.org:user/repo.git
- git checkout v1.0.0
- sudo -H vim /etc/environment
- pip3 install -r requirements.txt
- python3 repo/script.py
Step #1: GIT is not just a versioning tool, it is a communication tool. Make sure your script is uploaded to a git repo. Follow the GitFlow: create a new branch for your changes, then a PR, have someone to review it, merge it into master, then create a release.
You need to deploy a release tag in your server, not master, not a branch.
Steps #2-5: Your server needs permission to access your git repo. Create a new SSH key, and then to go your repo Settings, Deploy Keys section, and add the id_rsa.pub.
The id_rsa in your private key and should remain in your server. The id_rsa.pub is the public key that you can share with other people and services so they can encrypt messages just for you.
Steps #6-7: As I mentioned in Step #2, now you can pull the code from your repo, and checkout a specific version of your script. Don’t make code changes in the server, and don’t checkout branches.
Steps #8: if your script is using environment variables, here is the place where you can put them. The vars can include API tokens and DB credentials. You could encrypt the credentials and have your python script to decrypt them.
The only way to protect this file is restricting the folder permissions and the user who will run the script.
Step #9-10: now the fun part, install all the python libraries, and run the script. I’m assuming you are not using a root account. Create a new user in the server to run your script (see Step #8.)
By all means, follow and update this 10 step runbook; but go deep, read books like “Mastering Ubuntu Server,” there is a lot to learn from deploying a simple script.