Fabric使用主机配置文件

时间:2019-02-14 15:17:29

标签: python invoke fabric

大量阅读后,我仍然不明白这是如何工作的。例如,如果我有一个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 文件中创建一个别名时,该别名才真正起作用。

1 个答案:

答案 0 :(得分:0)

我将通过举一个示例来回答您两个问题,在该示例中,您将读取一个外部文件(.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位于同一目录