Parallelism and Shell Commands1
举一个例子
这里我们要使用 Ansible 的命令行工具来重启 Atlanta 组中所有的 web 服务器,每次重启10个.
我们先设置 SSH-agent,将私钥纳入其管理:
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa如果不想使用 ssh-agent, 想通过密码验证的方式使用 SSH,可以在执行ansible命令时使用 --ask-pass(-k)选项, 但这里建议使用 ssh-agent.
现在执行如下命令,这个命令中,atlanta是一个组,这个组里面有很多服务器,”/sbin/reboot”命令会在atlanta组下 的所有机器上执行.这里ssh-agent会fork出10个子进程(bash),以并行的方式执行reboot命令.如前所说“每次重启10个” 即是以这种方式实现:
$ ansible atlanta -a "/sbin/reboot" -f 10在执行 /usr/bin/ansible 时,默认是以当前用户的身份去执行这个命令.如果想以指定的用户执行 /usr/bin/ansible, 请添加 “-u username”选项,如下:
$ ansible atlanta -a "/usr/bin/foo" -u username如果想通过 sudo 去执行命令,如下:
$ ansible atlanta -a "/usr/bin/foo" -u username --sudo [--ask-sudo-pass]如果你不是以 passwordless 的模式执行 sudo,应加上 --ask-sudo-pass (-K)选项,加上之后会提示你输入 密码.使用 passwordless 模式的 sudo, 更容易实现自动化,但不要求一定要使用 passwordless sudo.
也可以通过–sudo-user (-U)选项,使用 sudo 切换到其它用户身份,而不是 root(译者注:下面命令中好像写掉了–sudo):
$ ansible atlanta -a "/usr/bin/foo" -u username -U otheruser [--ask-sudo-pass]Note
在有些比较罕见的情况下,一些用户会受到安全规则的限制,使用 sudo 切换时只能运行指定的命令.这与 ansible的 no-bootstrapping 思想相悖,而且 ansible 有几百个模块,在这种限制下无法进行正常的工作. 所以执行 ansible 命令时,应使用一个没有受到这种限制的账号来执行.One way of doing this without sharing access to unauthorized users would be gating Ansible with Ansible Tower, which can hold on to an SSH credential and let members of certain organizations use it on their behalf without having direct access.
以上是关于 ansible 的基础.如果你还没阅读过 patterns 和 groups,应先阅读 Patterns .
学员评价