Ben174
Ben174

Reputation: 3904

Fabric - Run a command locally before and after all tasks complete

I'm attempting to announce deployment start and end in my fabric script. Feels like this should be easy, but for the life of me I can't figure out how to do it.

env.hosts = ['www1', 'www2', 'www3', 'www4']


def announce_start(): 
    # code to connect to irc server and announce deployment begins
    pass


def announce_finish(): 
    # code to connect to irc server and announce deployment finishes
    pass


def deploy():
    # actual deployment code here
    pass

Here's what I've tried:

If I make my deploy task contain 'announce_start' and 'announce_finish'. It will attempt to run all those tasks on each server.

def deploy(): 
    announce_start()
    # actual deployment code here
    announce_finish()

If I decorate announce_start() and announce_end() with @hosts('localhost'), it runs it on localhost, but still four times. One for each host.

As I was typing this, I finally got it to work by using the decorator @hosts('localhost') on announce_start/end and the fab command:

fab announce_start deploy announce_end

But this seems a bit hacky. I'd like it all wrapped in a single deploy command. Is there a way to do this?

Upvotes: 4

Views: 1643

Answers (1)

Qiang Jin
Qiang Jin

Reputation: 4467

You can use fabric.api.execute, e.g.

def announce_start(): 
    # code to connect to irc server and announce deployment begins
    pass

def announce_finish(): 
    # code to connect to irc server and announce deployment finishes
    pass

@hosts(...)
def deploy_machine1():
    pass

@hosts(...)
def deploy_machine2():
    pass

def deploy():
    announce_start()
    execute(deploy_machine1)
    execute(deploy_machine2)
    announce_finish()

and then just invoke fab deploy

Upvotes: 4

Related Questions