Python fabric to shell script

Mazhar Ahmed
The Devs Tech
Published in
2 min readApr 15, 2020

Previously in Automate boring stuffs, Python Fabric we saw how to automate the deployments using Python Fabric. But today, we are going to learn how to do the similar thing using just the shell script.

Simple life of a programmer is a dream

The reason for using shell script is that, you don’t need anything to run it. It can be run without any hassle and any package installation. Let’s see a simple fabfile.py from the previous article.

from fabric import Connectiontry:
print("Connecting to server")
conn = Connection(
host="ec2-x-x-x-x-region.compute.amazonaws.com",
user="ec2-user",
connect_kwargs={
"key_filename": "x-x-x-x.pem",
}
)
print("Successfully connected")
# TODO: write your commands here
print("Deployment was successful")
except Exception as e:
print("Deployment was unsuccessful.\nError:\n")
print(e)

So, here we are connecting to the host and running some commands. Let’s do the similar using shell script.

#!/bin/bash
ssh ec2-user@ec2-x-x-x-x-region.compute.amazonaws.com -i x-x-x-x.pem '
echo Successfully connected
# TODO: write your commands here
echo Deployment was successful
'

You may wonder that if you need to run any command with a sudo what to do! It’s also simple if you use -s flag with sudo like:

#!/bin/bash
ssh ec2-user@ec2-x-x-x-x-region.compute.amazonaws.com -i x-x-x-x.pem '
echo Successfully connected
echo {:your-password} | sudo -S service nginx restart
echo Deployment was successful
'

For the last couple of days I’m simplifying the deployments for my team and I came up with writing all the deployment code to a file in the server named deploy.sh in the home folder and deploy like this:

ssh -p port user@server -i ssh-key.pem './deploy.sh'

Now my team can deploy anything anywhere from just one command without even installing anything.

Thanks a lot, that’s all for today. In the next tutorial we will see many more things to do with shell script and python fabric.

--

--