Skip to content

Instantly share code, notes, and snippets.

@realdimas
Last active April 24, 2020 01:48
Show Gist options
  • Save realdimas/f0177f6371b00cc0776a8892f19487c2 to your computer and use it in GitHub Desktop.
Save realdimas/f0177f6371b00cc0776a8892f19487c2 to your computer and use it in GitHub Desktop.
Manual reset_connection via local SSH invocation for Ansible v2.5.0 … v2.5.5 (fixed in v2.5.6)
# As of Ansible 2.5.2 reset_connection meta function is broken
# (see https://github.com/ansible/ansible/issues/27520)
# Below is reimplementation of reset_connect via local ssh command invocation
# Requires Ansible 2.5+ (config lookup plugin) and OpenSSH 5.9+ ("-O stop" command)
# *Update*
# Fixed in v2.5.6
# https://github.com/ansible/ansible/blob/stable-2.5/changelogs/CHANGELOG-v2.5.rst#bugfixes-9
- name: Reset persistent connection to host
local_action:
module: "command ssh -o ControlPath={{ control_path }}
-O stop {{port_arg}} {{user_arg}} {{ host }}"
vars:
host: "{{ hostvars[inventory_hostname]['ansible_host'] |
default(inventory_hostname) }}"
port: "{{ hostvars[inventory_hostname]['ansible_port'] |
default('None') }}"
user: "{{ hostvars[inventory_hostname]['ansible_user'] |
default('None') }}"
port_arg: "{{ '-o Port=' ~ port if port != 'None' else '' }}"
user_arg: "{{ '-o User=' ~ user if user != 'None' else '' }}"
connection_string_hash: "{{ [host, port, user] | join('-') |
hash('sha1') | truncate (10, False, '', 0) }}"
control_path_dir: "{{ lookup('config', 'ANSIBLE_SSH_CONTROL_PATH_DIR') |
default('~/.ansible/cp', True)}}"
control_path: "{{ lookup('config', 'ANSIBLE_SSH_CONTROL_PATH') |
default('', True) |
replace('%(directory)s', control_path_dir) |
replace('%%', '%') |
default(control_path_dir ~ '/' ~ connection_string_hash, True) }}"
@rockandska
Copy link

rockandska commented Oct 17, 2018

Thanks a lot for this fix.
Maybe adding a when clause to only do it if the ansible version is impacted by this bug will be helpful because this "patch" seems to be not functional on later ansible version and not sure that all 2.6.x have the fix backported :

ansible 2.6.4

TASK [Reset persistent connection to host] ******************************************************************************************************************************************************************************************
fatal: [XXXXX]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ [host, port, user] | join('-') | hash('sha1') | truncate (10, False, '', 0) }}): do_truncate() takes at most 4 arguments (5 given)"}

Regards,

Edit: Error related to the Jinja2 version, not functional with Jinja2 2.7.2 but functional with Jinja2 2.10.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment