Switching user in Fabric

后端 未结 3 366
迷失自我
迷失自我 2021-01-01 15:41

I have a problem when using Fabric to mimic my SSH workflow to deploy my web application.

Here\'s my usual flow of commands when I SSH to a server:

  1. SS
相关标签:
3条回答
  • 2021-01-01 16:14

    First of all, you should use sudo when executing commands under another user. Second, workon sets environment variables for current shell. Since fabric invokes new shell for every command, you should run workon rhino_env in every command, where you need virtualenv (i.e. as prefix). With this edits yor code should look like this:

    env.user = 'root'
    
    @roles('web')
    def deploy():
        dev_path = '/srv/web/prod'
        app_path = '/srv/web/prod/rhino'
        workon = 'workon rhino_env; '
        with settings(warn_only=True):
            run('kill -9 `cat /srv/web/run/rhino/rhino.pid`')
            puts('Stopped rhino...')
        with cd(app_path):
            sudo('git reset --hard HEAD', user='web')
            puts('Discarded all untracked and modified files')
            sudo('git checkout master', user='web')
            sudo('git pull origin master', user='web')
            users = run('users')
            puts('Output from `users` command: %s' % users)
    
            with prefix(workon):
                sudo('build_assets -m build', user='web')
        with cd(dev_path):
            run('chown -R web:ebalu rhino')
    
        with cd(app_path):
            sudo('./run', user='web')
    
        pid = run('cat /srv/web/run/rhino/rhino.pid')
        puts('Rhino started again with pid: %s.' % pid)
    
    0 讨论(0)
  • 2021-01-01 16:21

    The way I achieve this is with

    from fabric.api import settings
    
    with settings(user='otheruser'):
        ...
    

    You will be prompted for the password of otheruser, though only once. So it is not equivalent so sudo su otheruser, where root logs in to the user account without a password, but is is a simple way to switch between users in your script, only typing each password once

    0 讨论(0)
  • 2021-01-01 16:25

    One possible solution is to use the sudo operation instead of changing the remote user with su.

    0 讨论(0)
提交回复
热议问题