How to make Fabric ignore offline hosts in the env.hosts list?

前端 未结 4 1291
旧时难觅i
旧时难觅i 2021-02-14 02:44

This is related to my previous question, but a different one.

I have the following fabfile:

from fabric.api import *

host1 = \'192.168.200.181\'
offli         


        
4条回答
  •  鱼传尺愫
    2021-02-14 03:33

    Based on Matthew's answer, I came up with a decorator that accomplishes just that:

    from __future__ import with_statement
    from paramiko import Transport
    from socket import getdefaulttimeout, setdefaulttimeout
    from fabric.api import run, cd, env, roles
    
    
    roledefs = {
        'greece': [
            'alpha',
            'beta'
        ],
        'arabia': [
            'kha',
            'saad'
        ]
    }
    
    env.roledefs = roledefs
    
    
    def if_host_offline_ignore(fn):
        def wrapped():
            original_timeout = getdefaulttimeout()
            setdefaulttimeout(3)
            try:
                Transport((env.host, int(env.port)))
                return fn()
            except:
                print "The following host appears to be offline: " + env.host
            setdefaulttimeout(original_timeout)
        return wrapped
    
    
    @roles('greece')
    @if_host_offline_ignore
    def hello_greece():
        with cd("/tmp"):
            run("touch hello_greece")
    
    
    @roles('arabia')
    @if_host_offline_ignore
    def hello_arabia():
        with cd("/tmp"):
            run("touch hello_arabia")
    

    It is especially useful when you have multiple hosts and roles.

提交回复
热议问题