发布于 2015-10-05 04:26:56 | 653 次阅读 | 评论: 0 | 来源: 网络整理

Fabric 中有一个简单但是必不可少的部分叫做“环境”:它是 Python 字典的子类,既用作设置,也用于任务间数据空间共享。

目前,环境字典 fabric.state.env 是作为全局的单例实现的,为方便使用也包含在 fabric.api 中。 env 中的键通常也被称为“环境变量”。

运行环境即设置

Fabric 的大部分行为可以通过修改 env 变量,例如 env.hosts ,来控制(已经在 入门导览 中见过)。其他经常需要修改的环境变量包括:

  • user :Fabric 在建立 SSH 连接时默认使用本地用户名,必要情况下可以通过修改 env.user 来设置。 Execution model 文档中还介绍了如何为每个主机单独设置用户名。

  • password :用来显式设置默认连接或者在需要的时候提供 sudo 密码。如果没有设置密码或密码错误,Fabric 将会提示你输入

  • warn_only:布尔值,用来设置 Fabric 是否在检测到远程错误时退出。访问 Execution model 以了解更多关于此行为的信息。

除了这些以外还有很多其它环境变量, 环境变量完整列表 文档的底部提供了完整的列表。

The settings context manager

很多时候,只需要临时修改 env 变量来修改指定设置很有必要。Fabric 提供了会话管理器 ~fabric.context_managers.settings 上下文管理器,接受一个或多个键/值对参数,用于修改其代码块内部的 env

在下面的几种情况下 warn_only 设置非常有必要。需要设置环境变量应用的范围,你可以参照下面 contrib exists 函数的简化版,使用 settings(warn_only=True)

from fabric.api import settings, run

def exists(path):
    with settings(warn_only=True):
        return run('test -e %s' % path)

查看 上下文管理器 API 文档以了解关于 ``~fabric.context_managers.settings` 和其它类似工具的细节。

环境即状态共享

入前面所提,env 对象是字典的子类,所以你的 fabfile 代码也可以在这里保存信息。有些时候,比如对于一次运行的多个任务间保存状态,会很有用。

注解

env 的这种用法很有历史渊源,在早期版本中 fabfile 不是纯 Python,因此环境是任务间通信的唯一方式。而现在,你可以直接调用其他任务或子功能,并维护模块级别的状态共享。

在未来的版本,Fabric 将变得线程安全,env 将可能成为保持全局状态的唯一简单/安全的方式。

其他考虑

env 虽然是 dict 的子类,但它也做了些修改,以支持属性访问的方式进行读/写,这在前面也有所体现。换句话说, .host_stringenv['host_string'] 的作用是完全一样的。我们感觉属性访问通常可以少打一些打字,同时能增强代码的可读性,所以这也是推荐的与 env 交互的方式。

作为字典在其他方面也很有用,例如,需要往字符串中插入多个环境变量时,通过 Python 基于 dict 的字符串格式化显得尤其方便。“普通”的字符串格式化是这样的:

print("Executing on %s as %s" % (env.host, env.user))

使用字典格式化字符串更加简短,可读性也更好:

print("Executing on %(host)s as %(user)s" % env)

环境变量完整列表

以下是所有预定义(或在 Fabric 运行时定义)的环境变量的完整列表。它们中的大部分都可以直接操作,但最好还是使用 context_managers ,可以通过 settings 或特定的上下文管理器,如 cd

需注意的是它们中的大部分可以通过 fab 的命令行参数来设置,详细文档参见 fab 选项和参数 。合适的时候也可以使用交叉引用。

参见

--set

abort_exception

Default: None

通常情况下,Fabric 处理错误的方式是先打印错误信息至 stderr,然后调用 sys.exit(1)。这项设置提供覆盖这个默认行为(即设置 env.abort_exceptionNone )。

它接受一个接受单个字符串变量(需要打印的错误信息)的可调用对象,并返回一个异常实例。这样 Fabric 就会抛出该异常,而非 退出系统 (如 sys.exit 所做)

大部分情况下,你可以简单地将它设置为一个异常类,因为它完美地符合了上面的要求(可调用、接受一个字符串、返回一个异常实例)。例如: env.abort_exception = MyExceptionClass

abort_on_prompts

Default: False

当这个值为 True 时,Fabric 将以非交互模式运行。此模式下,任何需要提示用户输入(如提示输入密码、询问连接到哪个主机、fabfile 中触发的 prompt 等等)时,都会调用 abort 。这就保证 Fabric 会话总是明确地中止,而不是在某些意外的情况下傻傻地等待用户输入。

1.1 新版功能.

all_hosts

Default: []

由 fab 设置的当前正在执行命令的主机列表。仅用于显示信息。

always_use_pty

Default: True

设置为 False 时, ~fabric.operations.run`/`~fabric.operations.sudo` 的行为会和使用 ``pty=False 参数调用一样。

参见

--no-pty

1.0 新版功能.

colorize_errors

Default False

设置为 True 时,终端输出的错误信息会显示为红色,警告信息则是洋红色,以突出它们的显示。

1.7 新版功能.

combine_stderr

Default: True

使 SSH 层合并远程程序的 stdout 和 stderr 流输出,以避免它们在打印时混在一起。查看 Combining stdout and stderr 来了解为什么需要这个功能,以及它的实际效果。

1.0 新版功能.

command

Default: None

fab 设置的正在执行的命令名称(例如,执行 $ fab task1 task2 命令,当执行 task1 时, env.command 会被设置为 “task1” ,然后设置为 “task2” )。仅供显示。

command_prefixes

Default: []

通过 prefix 来修改,并会附加在由 run/sudo 执行的命令前面。

1.0 新版功能.

command_timeout

Default: None

远程命令的超时时间,单位为秒。

1.6 新版功能.

connection_attempts

Default: 1

Fabric 连接一台新服务器的重试次数。出于向后兼容的目的,它默认只尝试连接一次。

1.4 新版功能.

cwd

Default: ''

当前工作目录,用于 cd 上下文管理器保持状态。

dedupe_hosts

Default: True

去除合并后的主机列表中的重复项,以保证一个主机只会出现一次。(例如,在同时使用 @hosts@roles ,或 -H 和 -R 的时候。)

设置为 False 时不会去除重复项,这将允许用户显式地在同一台主机上将一个任务(并行地,当然也支持串行)运行多次。

1.5 新版功能.

disable_known_hosts

Default: False

如果为 ``True `` ,SSH 层将不会加载用户的 know-hosts 文件。这样可以有效地避免当一个“已知主机”改变了 key、但仍然有效时(比如 EC2 这样的云服务器中)的异常。

eagerly_disconnect

Default: False

设置为 True 时, fab 会在每个独立任务完成后关闭连接,而不是在整个运行结束后。这有助于避免大量无用的网络会话堆积,或因每个进程可打开的文件限制,或网络硬件的限制而引发问题。

注解

激活时,断开连接地信息会贯穿你的输出信息始终,而非最后。这一点可能会在以后的版本中得到改进。

effective_roles

Default: []

fab 设置的当前正在执行命令的角色列表。仅供显示。

1.9 新版功能.

exclude_hosts

Default: []

指定一个主机串列表, fab 执行期间会跳过列表中的主机。通常通过 --exclude-hosts/-x 来设置。

1.1 新版功能.

fabfile

Default: fabfile.py

fab 在加载 fabfile 时查找的文件名。要指定特定的 fabfile 文件,需要使用该文件的完整路径。显然,这个参数不可能在 fabfile 中设置,但可以将它设置在 .fabricrc 文件中,或者通过命令行参数来设置。

gateway

Default: None

允许通过指定主机创建 SSH 驱动的网关。它的值应该是一个普通的 Fabric 主机串,和 env.host_string 中使用的一样。当它被设置时,新创建的连接将会通过这个远程 SSH 连接到最终的目的地。

1.5 新版功能.

参见

--gateway

host_string

Default: None

指定 Fabric 在执行 runput 等命令时使用的用户/主机/端口。 fab 在与已设置的主机列表交互时设置这个值,将 Fabric 作为库使用时也可以手动设置它。

forward_agent

Default: False

值为 True 时允许本地 SSH 代理连接远程终端时跳转(forwarding)。

1.4 新版功能.

host

Default: None

Set to the hostname part of env.host_string by fab. For informational purposes only.

hosts

Default: []

The global host list used when composing per-task host lists.

keepalive

Default: 0 (i.e. no keepalive)

An integer specifying an SSH keepalive interval to use; basically maps to the SSH config option ServerAliveInterval. Useful if you find connections are timing out due to meddlesome network hardware or what have you.

参见

--keepalive

1.1 新版功能.

key

Default: None

A string, or file-like object, containing an SSH key; used during connection authentication.

注解

The most common method for using SSH keys is to set key_filename.

1.7 新版功能.

key_filename

Default: None

May be a string or list of strings, referencing file paths to SSH key files to try when connecting. Passed through directly to the SSH layer. May be set/appended to with -i.

linewise

Default: False

Forces buffering by line instead of by character/byte, typically when running in parallel mode. May be activated via --linewise. This option is implied by env.parallel – even if linewise is False, if parallel is True then linewise behavior will occur.

1.3 新版功能.

local_user

A read-only value containing the local system username. This is the same value as user‘s initial value, but whereas user may be altered by CLI arguments, Python code or specific host strings, local_user will always contain the same value.

no_agent

Default: False

If True, will tell the SSH layer not to seek out running SSH agents when using key-based authentication.

0.9.1 新版功能.

参见

--no_agent

no_keys

Default: False

If True, will tell the SSH layer not to load any private key files from one’s $HOME/.ssh/ folder. (Key files explicitly loaded via fab -i will still be used, of course.)

0.9.1 新版功能.

参见

-k

parallel

Default: False

When True, forces all tasks to run in parallel. Implies env.linewise.

1.3 新版功能.

password

Default: None

The default password used by the SSH layer when connecting to remote hosts, and/or when answering sudo prompts.

passwords

Default: {}

This dictionary is largely for internal use, and is filled automatically as a per-host-string password cache. Keys are full host strings and values are passwords (strings).

警告

If you modify or generate this dict manually, you must use fully qualified host strings with user and port values. See the link above for details on the host string API.

1.0 新版功能.

path

Default: ''

Used to set the $PATH shell environment variable when executing commands in run/sudo/local. It is recommended to use the path context manager for managing this value instead of setting it directly.

1.0 新版功能.

pool_size

Default: 0

Sets the number of concurrent processes to use when executing tasks in parallel.

1.3 新版功能.

prompts

Default: {}

The prompts dictionary allows users to control interactive prompts. If a key in the dictionary is found in a command’s standard output stream, Fabric will automatically answer with the corresponding dictionary value.

1.9 新版功能.

port

Default: None

Set to the port part of env.host_string by fab when iterating over a host list. May also be used to specify a default port.

real_fabfile

Default: None

Set by fab with the path to the fabfile it has loaded up, if it got that far. For informational purposes only.

remote_interrupt

Default: None

Controls whether Ctrl-C triggers an interrupt remotely or is captured locally, as follows:

  • None (the default): only open_shell will exhibit remote interrupt behavior, and run/sudo will capture interrupts locally.
  • False: even open_shell captures locally.
  • True: all functions will send the interrupt to the remote end.

1.6 新版功能.

rcfile

Default: $HOME/.fabricrc

Path used when loading Fabric’s local settings file.

reject_unknown_hosts

Default: False

If True, the SSH layer will raise an exception when connecting to hosts not listed in the user’s known-hosts file.

system_known_hosts

Default: None

If set, should be the path to a known_hosts file. The SSH layer will read this file before reading the user’s known-hosts file.

参见

SSH 行为

roledefs

Default: {}

Dictionary defining role name to host list mappings.

roles

Default: []

The global role list used when composing per-task host lists.

shell

Default: /bin/bash -l -c

Value used as shell wrapper when executing commands with e.g. run. Must be able to exist in the form <env.shell> "<command goes here>" – e.g. the default uses Bash’s -c option which takes a command string as its value.

skip_bad_hosts

Default: False

If True, causes fab (or non-fab use of execute) to skip over hosts it can’t connect to.

1.4 新版功能.

skip_unknown_tasks

Default: False

If True, causes fab (or non-fab use of execute) to skip over tasks not found, without aborting.

ssh_config_path

Default: $HOME/.ssh/config

Allows specification of an alternate SSH configuration file path.

1.4 新版功能.

ok_ret_codes

Default: [0]

Return codes in this list are used to determine whether calls to run/sudo/sudo are considered successful.

1.6 新版功能.

sudo_prefix

Default: "sudo -S -p '%(sudo_prompt)s' " % env

The actual sudo command prefixed onto sudo calls’ command strings. Users who do not have sudo on their default remote $PATH, or who need to make other changes (such as removing the -p when passwordless sudo is in effect) may find changing this useful.

参见

The sudo operation; env.sudo_prompt

sudo_prompt

Default: "sudo password:"

Passed to the sudo program on remote systems so that Fabric may correctly identify its password prompt.

参见

The sudo operation; env.sudo_prefix

sudo_user

Default: None

Used as a fallback value for sudo‘s user argument if none is given. Useful in combination with settings.

参见

sudo

tasks

Default: []

Set by fab to the full tasks list to be executed for the currently executing command. For informational purposes only.

timeout

Default: 10

Network connection timeout, in seconds.

1.4 新版功能.

use_shell

Default: True

Global setting which acts like the shell argument to run/sudo: if it is set to False, operations will not wrap executed commands in env.shell.

use_ssh_config

Default: False

Set to True to cause Fabric to load your local SSH config file.

1.4 新版功能.

user

Default: User’s local username

The username used by the SSH layer when connecting to remote hosts. May be set globally, and will be used when not otherwise explicitly set in host strings. However, when explicitly given in such a manner, this variable will be temporarily overwritten with the current value – i.e. it will always display the user currently being connected as.

To illustrate this, a fabfile:

from fabric.api import env, run

env.user = 'implicit_user'
env.hosts = ['host1', 'explicit_user@host2', 'host3']

def print_user():
    with hide('running'):
        run('echo "%(user)s"' % env)

and its use:

$ fab print_user

[host1] out: implicit_user
[explicit_user@host2] out: explicit_user
[host3] out: implicit_user

Done.
Disconnecting from host1... done.
Disconnecting from host2... done.
Disconnecting from host3... done.

As you can see, during execution on host2, env.user was set to "explicit_user", but was restored to its previous value ("implicit_user") afterwards.

注解

env.user is currently somewhat confusing (it’s used for configuration and informational purposes) so expect this to change in the future – the informational aspect will likely be broken out into a separate env variable.

version

Default: current Fabric version string

Mostly for informational purposes. Modification is not recommended, but probably won’t break anything either.

参见

--version

warn_only

Default: False

Specifies whether or not to warn, instead of abort, when run/sudo/local encounter error conditions.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务