From 218a63f58f6985b9e798496ffd30ea0f9dafc67d Mon Sep 17 00:00:00 2001
From: Petros Moisiadis <pmoisiadis@modulus.gr>
Date: Mon, 30 Jul 2012 18:39:45 +0300
Subject: [PATCH] added a 'chdir' argument to the command module

the 'chdir' argument changes the current working directory to the
fullpath supplied as its value, before the execution of the command.
---
 command | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/command b/command
index 533368f444c..754f75110b6 100755
--- a/command
+++ b/command
@@ -31,8 +31,12 @@ def main():
     module = CommandModule(argument_spec=dict())
 
     shell = module.params['shell']
+    chdir = module.params['chdir']
     args  = module.params['args']
 
+    if chdir:
+        os.chdir(chdir)
+
     if not shell:
         args = shlex.split(args)
     startd = datetime.datetime.now()
@@ -77,6 +81,7 @@ class CommandModule(AnsibleModule):
         args = base64.b64decode(MODULE_ARGS)
         items   = shlex.split(args)
         params = {}
+        params['chdir'] = None
         params['shell'] = False
         if args.find("#USE_SHELL") != -1:
              args = args.replace("#USE_SHELL", "")
@@ -99,6 +104,14 @@ class CommandModule(AnsibleModule):
                         rc=0
                     )
                 args = args.replace(x,'')
+            elif x.startswith("chdir="):
+                (k,v) = x.split("=", 1)
+                if not (os.path.exists(v) and os.path.isdir(v)):
+                    self.fail_json(msg="cannot change to directory '%s': path does not exist" % v)
+                elif v[0] != '/':
+                    self.fail_json(msg="the path for 'chdir' argument must be fully qualified")
+                params['chdir'] = v
+                args = args.replace(x, '')
         params['args'] = args
         return (params, args)