thelfter
thelfter

Reputation: 155

Fabric use a host config file

After a lot of reading I still don't understand how this really works. For example If I have a hosts.yml configuration file like this:

hosts.yml:

server1:
  host: serverip
  user: username

How should I use this to create a Connection? I had to rename the hosts.yml to fabric.yml to get access these data, through the context variable, e.g:

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

And it will give back a DataProxy, that I can't use for create connection, or I just didn't find in the documentation

My another problem: how is it possible to specify these hosts declared in the hosts.yml file with -H toggle? It only works if I create an alias in the ~/.ssh/config file which is not so great at all.

Upvotes: 2

Views: 1816

Answers (1)

Peshmerge
Peshmerge

Reputation: 1060

I will answer you both questions by giving an example where you read an external file(.env file) which store information about the host you are trying to connect to with a specific user.

info.env content:

# 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 contnet:

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

Now in you fabfile.py you should do the following

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)

Then you can call you fabfile.py using the following command:

fab deploy -e info.env 

Make sure your info.env resides in the same directory as your fabfile.py

Upvotes: 1

Related Questions