如何使SSH会话易于重用,而不是为每个任务创建一个新会话



我的公司防火墙策略在同一源和目标之间每分钟60秒只允许20个连接。

正因为如此,这出有把握的戏过了一段时间就悬了。

我希望多个任务使用同一个ssh会话,而不是创建新的会话。为此,我在本地文件夹ansible.cfg以及命令行中设置了以下pipelining = True

cat /opt/automation/startservices/ansible.cfg
[defaults]
host_key_checking = False
gathering = smart
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=600s
control_path = %(directory)s/%%h-%%r
pipelining = True
ANSIBLE_SSH_PIPELINING=0 ansible-playbook -i /opt/automation/startservices/finalallmw.hosts /opt/automation/startservices/va_action.yml -e '{ dest_host: myremotehost7 }' -e dest_user=oracle

这个剧本太大了,不能在这里共享,但正是这个任务循环,由于60秒内有20多个ssh连接,所以它挂起了。

- name: Copying from "{{ inventory_hostname }}" to this ansible server.
synchronize:
src: "{{ item.path }}"
dest: "{{ playbook_dir }}/homedirbackup/{{ inventory_hostname }}/{{ dtime }}/"
mode: pull
copy_links: yes
with_items:
- "{{ to_copy.files }}"

设置了流水线设置后,我的游戏在连接20次后仍然挂起。

以下是剧本设置:

hosts: "{{ groups['dest_nodes'] | default(groups['all']) }}"
user: "{{ USER | default(dest_user) }}"
any_errors_fatal: True
gather_facts: false
tags: always
vars:
ansible_host_key_checking: false
ansible_ssh_extra_args: -o StrictHostKeyChecking=no  -o ConnectionAttempts=5

到目前为止,在这个帖子上发布建议,问题仍然存在。下面是我的本地目录ansible.cfg

$ cat /opt/automation/startservices/ansible.cfg
# config file for ansible -- http://ansible.com/
# ==============================================
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
[defaults]
host_key_checking = False
roles_path = roles/
gathering = smart
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=1200s  -o ControlPath=~/.ansible/cp/%r@%h:%p
[persistent_connection]
control_path_dir = ~/.ansible/cp
$

对于所有任务都使用同一个ssh会话,并且管道在这里不起作用的问题,你能提出任何解决方案吗?

首先:pipelining = True不会执行您想要的操作。它减少了网络操作的数量,但没有减少ssh连接的数量。查看文档以了解更多信息
Imho,它仍然是一个好东西,因为它会加快你的剧本。

您想要使用的是";持久控制模式";这是OpenSSH保持连接打开的一个特征。

例如,您可以在ansible.cfg:中执行此操作

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=1200

这将使连接保持打开状态1200秒。

问题不在于运行模块的ansible控制器(即将必要的临时AnsibleZ文件复制到目标并执行它们-您在ansible.cfg中已经有了使用主会话的正确选项(,而在于synchronize模块本身,它需要生成自己的ssh连接,以便在相关服务器之间传输文件目标。

最新的synchronize模块版本现在是ansible.posix集合的一部分,并且最近获得了两个选项,它们将帮助您解决在使用rsync时将主会话的使用应用于模块本身的问题。

  • ssh_multiplexing: yes
  • use_ssh_args: yes

尽管可以在ansible 2.9中安装此集合以覆盖旧的库存模块版本(该版本没有这些选项(,但我强烈建议您使用ansible 2.10或2.11版本。我个人喜欢的ansible安装方法是通过pip,因为它可以让你在任何操作系统上为任何数量(虚拟(环境中的任何用户安装任何ansible版本。

关于pip,版本控制已经改变了(而且非常混乱(

  • ansible现在是一个具有独立版本控制的元包
  • 常见的可解析二进制文件(ansibleansible-playbook……(打包在ansible-core中,其版本与运行ansible -v时获得的版本相对应
  • ansible包默认安装一组集合(如果我没有错的话,包括ansible.posix集合(

=>要获得ansible -v => 2.10,您需要安装ansible pip软件包3.x

=>要获得ansible -v => 2.11,您需要安装ansible pip包4.x

在继续之前,您必须删除当前环境中通过pip安装的任何以前的版本。

最新更新