Skip to content

Commit

Permalink
initial version of the ansible for windows wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
bertramn committed Jan 30, 2016
1 parent 6f75ad8 commit 357d158
Show file tree
Hide file tree
Showing 4 changed files with 301 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ _testmain.go
*.exe
*.test
*.prof
/.project
181 changes: 179 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,179 @@
# ansible-win-wrapper
Executable wrapper to wrap ansible commands on windows using cygwin and cygwin-python
# Ansible Wrapper for Windows

This is a simple executable wrapper to allow Vagrant to run ansible commands on windows through to a configured cygwin environment. There are a few [threads](http://stackoverflow.com/questions/29743491/how-to-install-ansible-playbook-on-windows-as-host-with-vagrant) out there that document the use of batch files to bootstrap ansible but I found the windows command shell does not actually work properly when using `--extra-vars` for instance.

We assume you have installed a working cygwin shell on your workstation.

### Installation

##### Install Cygwin Packages

Use the cygwin package installer from https://cygwin.com/ and install the following packages:
* python
* python-setuptools
* gcc-g++
* wget
* openssh
* curl
* git

Now you should have base python environment installed in your cygwin environment.

##### Configure Python Environment

First lets open up a cygwin terminal and install pip.

```sh
$ easy_install-2.7 pip
```

Thereafter we will update `pip` and `setuptools`

```sh
$ pip install -U pip setuptools
```

##### Install Ansible

Still in the cygwin terminal we need to install the ansible dependencies.

```sh
$ pip install -U crypto paramiko PyYAML Jinja2 httplib2 six
```

And finally lets install ansible itself.

```sh
$ pip install -U ansible
```

Quick test to ensure it works.

```sh
$ ansible --version
ansible 2.0.0.2
config file =
configured module search path = Default w/o overrides
```

### Configure Vagrant Environment to work with Ansible

To bridge Vagrant on windows to Ansible on Cygwin we can now use the Ansible Wrapper for Windows binary. The Vagrant Ansible provisionser will use the Vagrant windows environment to load the `ansible-playbook` executable. So we need to ensure Vagrant will find the wrapper executable to hand off to the Cygwin envionment.

Simply copy the `ansible-win-wrapper.exe` into the same folder of the `vagrant.exe` and rename it to `ansible-playbook.exe`.

```cmd
copy ansible-win-wrapper C:\HashiCorp\Vagrant\bin\ansible-playbook.exe
vagrant --version
Vagrant 1.8.1
ansible-playbook --version
ansible-playbook 2.0.0.2
config file =
configured module search path = Default w/o overrides
```

Et voilà, ansible-playbook should now work from vagrant.

### Test Example

Setup a Vagrant project folder with a few basic files. I use cygwin terminal for simplicity but you can also do all of this in windows command or powershell.

```sh
$ mkdir ~/vagrant-test
$ cd ~/vagrant-test
```

All 4 files listed below go into the project folder.

**`Vagrantfile`**

A basic Vagrant machine definition with ansible provisioner configuration.

```rb
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|

config.vm.box = "hashicorp/precise64"

config.vm .provision "ansible" do |ansible|
ansible.verbose = "v"
ansible.limit = "all"
ansible.inventory_path = "./inventory"
ansible.playbook = "playbook.yml"
end

end
```

**`ansible.cnf`**

Ansible default configuration with some Windows specific config.

```properties
[defaults]
host_key_ckecking = False
[ssh_connection]
# ControlMaster on cygwin OpenSSH does not work, so disable it
control_path = none
```

**`inventory`**

Need to create an ansible inventory definition, the default Vagrant generated one does not work, vagrants ansible provisioner generates a inventory path arg that is Windows but must POSIX for ansible to work properly, so we just cheat a little.

```properties
default ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 ansible_ssh_user='vagrant' ansible_ssh_private_key_file='./.vagrant/machines/default/virtualbox/private_key'
```
Note: You may need to adjust the `ansible_ssh_port` to whatever the Vagrant machine bound to. You can get around all this by using a DNS plugin like `vagrant-hostmanager` and then just define actual DNS resolvable vagrant machine names in the inventory.

Also may need to `$ chmod 0644 inventory` depending on how your cygwin fstab is setup, ansible may complain about +x permissions.

**`playbook.yml`**

```yaml
---
- hosts: all
tasks:
- debug: "msg='Hello Ansible from Vagrant'"
```
Lets run it:
```sh
$ vagrant up --no-provision

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'hashicorp/precise64'...
...
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
...
==> default: Machine booted and ready!
```
```sh
$ vagrant provision
==> default: Running provisioner: ansible...
Windows is not officially supported for the Ansible Control Machine.
Please check https://docs.ansible.com/intro_installation.html#control-machine-requirements
default: Running ansible-playbook...

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [default]

TASK [debug] *******************************************************************
ok: [default] => {
"msg": "Hello Ansible from Vagrant"
}

PLAY RECAP *********************************************************************
default : ok=2 changed=0 unreachable=0 failed=0
```
53 changes: 53 additions & 0 deletions ansible-playbook.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
@echo off

REM If you used the stand Cygwin installer this will be C:\cygwin
rem set CYGWIN=%USERPROFILE%\.babun\cygwin
set CYGWIN=c:\cygwin
rem set CYGWIN=C:\dev\apps\MobaXterm\mbx-root
rem set CYGWIN=c:\dev\apps\babun\.babun\cygwin

REM You can switch this to work with bash with %CYGWIN%\bin\bash.exe
rem set SH=%CYGWIN%\bin\zsh.exe
set SH=%CYGWIN%\bin\bash.exe

rem cygwin
set EXEC_ANSIBLE_PLAYBOOK=/usr/bin/ansible-playbook
rem babun
rem set EXEC_ANSIBLE_PLAYBOOK=/bin/ansible-playbook

echo "----------------------------- " > c:\temp\vansible.log
setlocal enabledelayedexpansion
REM
REM set argCount=0
REM for %%x in (%*) do (
REM set /A argCount+=1
REM set "argVec[!argCount!]=%%~x"
REM )
REM
REM echo Number of processed arguments: %argCount% >> c:\temp\vansible.log
REM
REM for /L %%i in (1,1,%argCount%) do (
REM echo %%i- !argVec[%%i]! >> c:\temp\vansible.log
REM echo "Arg is %%i !argVec[%%i]:~0,14!"
REM IF "!argVec[%%i]:~0,14!"=="--extra-vars='" (
REM echo yes---------------
REM echo !argVec[%%i]:~0,14!
REM )
REM )

REM set CMD_LINE_ARGS=
REM set argCount=0
REM :setArgs
REM if ""%1""=="""" goto doneSetArgs
REM set /A argCount+=1
REM echo Add arg !argCount!: %1 >> c:\temp\vansible.log
REM set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
REM shift
REM goto setArgs
REM :doneSetArgs
REM echo "CMD: %CMD_LINE_ARGS%"

REM "%SH%" -c "%EXEC_ANSIBLE_PLAYBOOK% -vvvv %CMD_LINE_ARGS%"
"%SH%" -c "%EXEC_ANSIBLE_PLAYBOOK% %*"

rem c:\dev\apps\python\python-2.7.10\python.exe C:\dev\apps\babun\.babun\cygwin\bin\ansible-playbook
68 changes: 68 additions & 0 deletions ansible-playbook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

/*
* Addresses:
* Can be used in conjunction with below fix to start ansible with extra-vars parameter without falling over.
* https://github.com/mitchellh/vagrant/issues/6726
*
* References:
* http://nathanleclaire.com/blog/2014/12/29/shelled-out-commands-in-golang/
* http://www.darrencoxall.com/golang/executing-commands-in-go/
* https://groups.google.com/forum/#!msg/golang-nuts/cnG-N3KcoUU/4vR5MIuFDjYJ
*
*/

import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)

func main() {

var wrapperExecutableName = filepath.Base(os.Args[0])
var extension = filepath.Ext(wrapperExecutableName)
var executable = wrapperExecutableName[0 : len(wrapperExecutableName)-len(extension)]
// pwd, err := os.Getwd()

args := make([]string, len(os.Args[1:])+1, len(os.Args[1:])+1)
args[0] = "/usr/bin/" + executable
for i, a := range os.Args[1:] {
// fmt.Printf("arg[%d] is: %s\n", i+1, a)
args[i+1] = a
}
cmd := exec.Command("c:\\cygwin\\bin\\bash.exe", "-c", strings.Join(args[:], " "))

cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating "+executable+" wrapper stdout pipeline", err)
os.Exit(1)
}

// echo stdin back to console
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
}()

err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting "+executable+" wrapper", err)
os.Exit(1)
}

err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for "+executable+" wrapper to finish", err)
os.Exit(1)
}

// all good can finish now
os.Exit(0)

}

0 comments on commit 357d158

Please sign in to comment.