折腾:
【未解决】Fabric 2中如何实现Fabric 1中的rsync_project去实现同步代码以实现项目代码部署
期间,需要先去搞清楚:
如何在Fabric 2中,用Connection连接远程服务器后,cd目录后,执行新的命令, 比如pwd
参考之前Fabric 1:
from fabric.api import env, cd, put env.hosts = [' [email protected] ', ] env.password = '111111' def hello(): with cd('/var/www/'): put('/tmp/myapp-0301.tar.gz', 'myapp.tar.gz')
cd后,好像需要用with,然后才可以针对于新目录操作
试了试:
@task def deploy(context): remoteConn = Connection(host=RemoteHost, user=RemoteUser) # print(remoteConn) seperatorLine() print("Following command run in local:") context.run('pwd') # context.run('ls') seperatorLine() print("Following command run in remote server:") remoteConn.run('uname -a') remoteConn.run('pwd') remoteConn.run('ls') with remoteConn.run('cd %s' % RemotePathRoot): remoteConn.run('pwd', echo=True)
结果出错:
Traceback (most recent call last): File "/Users/crifan/Library/Python/2.7/bin/fab", line 11, in <module> sys.exit(program.run()) File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/program.py", line 335, in run self.execute() File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/program.py", line 491, in execute executor.execute(*self.tasks) File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/executor.py", line 129, in execute result = call.task(*args, **call.kwargs) File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/tasks.py", line 128, in __call__ result = self.body(*args, **kwargs) File "/Users/crifan/Downloads/fabfile.py", line 24, in deploy with remoteConn.run('cd %s' % RemotePathRoot): AttributeError: __exit__
好像:
中有解释?
需要自己把:
@task def deploy(c): c.run("cd /path/to/application") c.run("./update.sh")
改为:
def deploy(c): c.run("cd /path/to/application && ./update.sh")
此处改为:
remoteConn.run('cd %s && pwd && ls -lha' % RemotePathRoot)
输出:
/root/xxx_20180101/nlp/test_fabric total 12K drwxr-xr-x 2 root root 4.0K Aug 17 13:56 . drwxr-xr-x 5 root root 4.0K Aug 17 13:52 .. -rw-r--r-- 1 root root 2.7K Aug 17 16:41 fabfile.py
【总结】
Fabric 2中,不直接支持远端cd后继续执行命令,因为:
每个Fabric的run都是一个独立的session
解决办法(不完美的workaround)是:
cd后的命令,改为 &&连接,比如:
remoteConn.run('cd /xxx/xxx && pwd && ls -lha')
要么是尽量不要cd,而使用绝对路径,比如:
c.run("/path/to/application/update.sh")