[英]Environment Variables in Fabric2
我正在使用 Python 3.6 和 Fabric 2.4。 我正在使用 Fabric 通過 SSH 連接到服務器並運行一些命令。 我需要為遠程服務器上運行的命令設置一個環境變量。 文檔表明這樣的事情應該有效:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.run("command_to_execute", env={"KEY": "VALUE"})
但這不起作用。 像這樣的事情也應該是可能的:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.config.run.env = {"KEY": "VALUE"}
c.run("command_to_execute")
但這也行不通。 我覺得我錯過了一些東西。 任何人都可以幫忙嗎?
正如 Fabric 網站上所述:
其根本原因通常是因為 SSH 服務器通過非常有限的 shell 調用運行非交互式命令:/path/to/shell -c "command"(例如 OpenSSH)。 以這種方式運行時,大多數 shell 不被認為是交互式 shell 或登錄 shell; 然后這會影響加載哪些啟動文件。
您在此頁面鏈接上閱讀了更多信息
因此,您嘗試執行的操作不起作用,解決方案是傳遞要顯式設置的環境變量:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.config.run.env = {"KEY": "VALUE"}
c.run('echo export %s >> ~/.bashrc ' % 'ENV_VAR=VALUE' )
c.run('source ~/.bashrc' )
c.run('echo $ENV_VAR') # to verify if it's set or not!
c.run("command_to_execute")
我可以通過設置inline_ssh_env=True
,然后顯式設置 env 變量來做到這一點,例如:
with Connection(host=hostname, user=username, inline_ssh_env=True) as c:
c.config.run.env = {"MY_VAR": "this worked"}
c.run('echo $MY_VAR')
你可以試試:
@task
def qa(ctx):
ctx.config.run.env['counter'] = 22
ctx.config.run.env['conn'] = Connection('qa_host')
@task
def sign(ctx):
print(ctx.config.run.env['counter'])
conn = ctx.config.run.env['conn']
conn.run('touch mike_was_here.txt')
並運行:
fab2 qa sign
創建Connection
對象時,請嘗試添加inline_ssh_env=True
。
引用文檔:
是否將環境變量作為前綴“內聯”發送到命令字符串(
export VARNAME=value && mycommand here
),而不是嘗試通過 SSH 協議本身提交它們(這是默認行為)。 如果遠程服務器具有受限制的AcceptEnv
設置(這是常見的默認設置),則這是必要的。
根據官方文檔的那部分, Connection
對象的connect_kwargs
屬性旨在替換env
dict。 我使用它,它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.