1

I am using fabric to automate some deployment stuff. Below is a sample of the code I used:

run(f"sudo -H -u www-data bash -c 'rm -r project_name' ")
run(f"sudo -H -u www-data bash -c '/opt/www-data/project-name/bin/pip install -r requirements.txt' ")

run("sudo systemctl stop gunicorn")
run("sudo systemctl start gunicorn")

Everytime each line of code was ran, the terminal ask for my user password, is there a way I can enter the password just once?

Edit: I am using python3 and the essence of the script was to run the commands on a different user, rather than my own.

Update:

I achieved this by running fabric with "-I" param.

fabric -I deploy

4 Answers4

0

Using run is not the ideal way to achieve this.

fabric.operations.sudo(*args, **kwargs) is something that can be used to achieve what you are attempting. Please be careful with sudo :)

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
0

Every run() invocation is a separate shell, as would be a sudo() invocation. The sudo credentials are per shell, so they are gone every time.

A quick and dirty way would be to lump all commands into one sudo invocation.

A nicer way would be to have a sudoers file on the target host(s) and give each user the required privileges to run particular commands without entering a password.

9000
  • 39,899
  • 9
  • 66
  • 104
0

You can create a fab script like below and then iterate over the host list you want to run the commands because you can passwd username and password in the script itself so to avoid password invocation:

# testCheck.py
#!/usr/bin/python2.7
import sys
from fabric.api import *
env.skip_bad_hosts=True
env.command_timeout=160
env.user = 'user_name'
env.shell = "/bin/sh -c"
env.warn_only = True
env.password = 'user_password'
def readhost():
    env.hosts = [line.strip() for line in sys.stdin.readlines()]

def hosts():
  with settings(warn_only=True):

      output=sudo("ls -l /myfolder",shell=False)


# cat hostfile.txt| | /usr/local/bin/fab readhost -f testCheck.py hosts -P -z 5

OR supplying password at command line
# cat hostfile.txt | /usr/local/bin/fab readhost -f testCheck.py --password=your_pass hosts -P -z 5


--> argument "-P" refers to  parallel execution method
--> argument "-z" refres to the number of concurrent processes to use in parallel mode

exapmle hostfile.txt:

server1
server2
server3
server4

Hope this will help.

Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
0

If you are using ssh keys, then set the fabric environment variable key_filename:

env.key_filename='/path/to/key.pem'

# set the following as well
env.user='username'
env.host='hostaddr'

It will ask you for the password only one time.
Have a look at this question regarding avoid to enter any sudo password when using fabric.

Evhz
  • 8,852
  • 9
  • 51
  • 69