Fabric 使用主机配置文件

Fabric use a host config file

经过大量阅读,我仍然不明白这是如何工作的。例如,如果我有一个像这样的 hosts.yml 配置文件:

hosts.yml:

server1:
  host: serverip
  user: username

我应该如何使用它来创建连接?我不得不将 hosts.yml 重命名为 fabric.yml 以通过上下文变量访问这些数据,例如:

@task
def do(ctx):
    ctx['server1']

它会返回一个 DataProxy,我不能用它来创建连接,或者我在文档中没有找到它

我的另一个问题:如何使用 -H 切换指定在 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

~/.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.envfabfile.py

位于同一目录中