@contextmanager
def shell_env(**env_vars):
    orig_shell = env['shell']
env_vars_str = ' '.join('{0}={1}'.format(key, value) for key, value in
    list(env_vars.items()))
env['shell'] = '{0} {1}'.format(env_vars_str, orig_shell)
yield
env['shell'] = orig_shell

def my_task():
    with prefix('echo FOO1=$FOO1, FOO2=$FOO2, FOO3=$FOO3'):
        with shell_env(FOO1='BAR1', FOO2='BAR2', FOO3='BAR3'):
            run('env | grep BAR')
Best way to add an environment variable in fabric?