2017年10月17日 Tue

Windows/msys2 下安装和使用 ansible

尽管 ansible 官方不支持 Windows,但 Windows 上的一些 POSIX 兼容环境是可以的,这里记录下使用 msys2 环境安装 ansible 的过程。msys2 是基于 cygwin 开发的,用法与其相似。

通常来说,直接执行 pip2 install ansible 即可, 但由于一些依赖(准确说是依赖的依赖)包含一些专为 *nix 系统开发的 C 代码,导致在安装 ansible 前需要一点小折腾。顺带吐槽下,即使在 *nix 下,也不是 100% 免于折腾,这是 C 的工程特(Wen)性(Ti)决定的。

下面开始痛苦之旅。

安装 python2 环境 和 C/C++ 编译环境

pacman -S python2 python2-pip --noconfirm
pacman -S base-devel --noconfirm

安装依赖 cffi (头文件路径问题)

pacman -S libffi-devel --noconfirm
path_libffi_include=$(pacman -Ql libffi-devel | grep -o -e '[^ ]*include/$' )
ln -s $path_libffi_include /usr/include/libffi
pip2 install cffi

安装依赖 pycrypto (未定义的 u_int )

问题讨论见:
http://cygwin.1069669.n5.nabble.com/python-2-7-12-pip-install-with-extensions-fails-with-warning-quot-BSD-VISIBLE-quot-redefined-td131045.html

pacman -S openssl-devel --noconfirm
sed -i "s/#define __BSD_VISIBLE 1/#define __BSD_VISIBLE 0/g" /usr/include/python2.7/pyconfig.h
pip2 install pycrypto

安装 ansible 完事!

pip2 install ansible==2.3

坚持下,再绕过一个神坑

现在可以执行 ansible 了,但你大概率会碰到这样的一个错误。

Failed to connect to the host via ssh: mux_client_request_session: read from master failed: Connection reset by peer  
Failed to connect to new control master  

可参考:
https://github.com/ansible/ansible/issues/6363
至于 ansible 开发者说的 Ansible doesn't support running from cygwin.,意译下就是“哥没空支持旁门左道的平台”。 我们不鸟他,继续痛苦之旅。
修改 /etc/ansible/ansible.cfg

[ssh_connection]
ssh_args = -o ControlMaster=no -o ControlPersist=60s

如果你还没有这个文件,可以执行下面的一坨 bash 一步到位(如果不灵,可反馈给我修正下)。

ansible_cfg_src=https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
ansible_cfg_dest=/etc/ansible/ansible.cfg

mkdir -p /etc/ansible/
[ -f $ansible_cfg_dest ] && mv $ansible_cfg_dest $ansible_cfg_dest.bak # backup.
wget $ansible_cfg_src -O $ansible_cfg_dest
sed -i "s/^\[ssh_connection\]/\[ssh_connection\]\nssh_args = -o ControlMaster=no -o ControlPersist=60s\n/g" $ansible_cfg_dest

搞定,可以开始爽了。

ansible all -m ping

完。