经过大量阅读后,我仍然不明白这是如何运作的。例如,如果我有一个hosts.yml配置文件,如下所示:
hosts.yml:
server1:
host: serverip
user: username
我该如何使用它来创建连接?我不得不将hosts.yml重命名为fabric.yml,以通过上下文变量访问这些数据,例如:
@task
def do(ctx):
ctx['server1']
它会返回一个DataProxy,我不能用于创建连接,或者我只是在文档中找不到
我的另一个问题:如何使用-H toggle指定在hosts.yml文件中声明的这些主机?它只适用于我在〜/ .ssh / config文件中创建一个不太好的别名。
我将通过一个示例来回答您这两个问题,其中您读取了一个外部文件(.env文件),该文件存储有关您尝试与特定用户连接的主机的信息。
info.env
内容:
# The hostname of the server you want to connect to
DP_HOST=myserverAlias
# Username you use to connect to the remote server. It must be an existing user
DP_USER=bence
qazxsw poi内容:
~/.ssh/config
现在你Host myserverAlias //it must be identical to the value of DP_HOST in info.env
Hostname THE_HOSTNAME_OR_THE_IP_ADDRESS
User bence //it must be identical to the value of DP_USER in info.env
Port 22
你应该做以下事情
fabfile.py
然后你可以使用以下命令叫你from pathlib import Path
from fabric import Connection as connection, task
import os
from dotenv import load_dotenv
import logging as logger
from paramiko import AuthenticationException, SSHException
@task
def deploy(ctx, env=None):
logger.basicConfig(level=logger.INFO)
logger.basicConfig(format='%(name)s ----------------------------------- %(message)s')
if env is None:
logger.error("Env variable and branch name are required!, try to call it as follows : ")
exit()
# Load the env files
if os.path.exists(env):
load_dotenv(dotenv_path=env, verbose=True)
logger.info("The ENV file is successfully loaded")
else:
logger.error("The ENV is not found")
exit()
user = os.getenv("DP_USER")
host = os.getenv("DP_HOST")
try:
with connection(host=host, user=user,) as c:
c.run('whoami')
c.run('mkdir new_dir')
except AuthenticationException as message:
print(message)
except SSHException as message:
print(message)
:
fabfile.py
确保您的fab deploy -e info.env
与info.env
位于同一目录中