/lib/ansible/plugins/action/script.py

https://github.com/debfx/ansible · Python · 152 lines · 74 code · 28 blank · 50 comment · 23 complexity · 8a019aac7a6985a8e4d178627670eb98 MD5 · raw file

  1. # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
  2. #
  3. # This file is part of Ansible
  4. #
  5. # Ansible is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # Ansible is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import (absolute_import, division, print_function)
  18. __metaclass__ = type
  19. import os
  20. import re
  21. import shlex
  22. from ansible.errors import AnsibleError, AnsibleAction, _AnsibleActionDone, AnsibleActionFail, AnsibleActionSkip
  23. from ansible.executor.powershell import module_manifest as ps_manifest
  24. from ansible.module_utils._text import to_bytes, to_native, to_text
  25. from ansible.plugins.action import ActionBase
  26. class ActionModule(ActionBase):
  27. TRANSFERS_FILES = True
  28. # On Windows platform, absolute paths begin with a (back)slash
  29. # after chopping off a potential drive letter.
  30. windows_absolute_path_detection = re.compile(r'^(?:[a-zA-Z]\:)?(\\|\/)')
  31. def run(self, tmp=None, task_vars=None):
  32. ''' handler for file transfer operations '''
  33. if task_vars is None:
  34. task_vars = dict()
  35. result = super(ActionModule, self).run(tmp, task_vars)
  36. del tmp # tmp no longer has any effect
  37. try:
  38. creates = self._task.args.get('creates')
  39. if creates:
  40. # do not run the command if the line contains creates=filename
  41. # and the filename already exists. This allows idempotence
  42. # of command executions.
  43. if self._remote_file_exists(creates):
  44. raise AnsibleActionSkip("%s exists, matching creates option" % creates)
  45. removes = self._task.args.get('removes')
  46. if removes:
  47. # do not run the command if the line contains removes=filename
  48. # and the filename does not exist. This allows idempotence
  49. # of command executions.
  50. if not self._remote_file_exists(removes):
  51. raise AnsibleActionSkip("%s does not exist, matching removes option" % removes)
  52. # The chdir must be absolute, because a relative path would rely on
  53. # remote node behaviour & user config.
  54. chdir = self._task.args.get('chdir')
  55. if chdir:
  56. # Powershell is the only Windows-path aware shell
  57. if self._connection._shell.SHELL_FAMILY == 'powershell' and \
  58. not self.windows_absolute_path_detection.match(chdir):
  59. raise AnsibleActionFail('chdir %s must be an absolute path for a Windows remote node' % chdir)
  60. # Every other shell is unix-path-aware.
  61. if self._connection._shell.SHELL_FAMILY != 'powershell' and not chdir.startswith('/'):
  62. raise AnsibleActionFail('chdir %s must be an absolute path for a Unix-aware remote node' % chdir)
  63. # Split out the script as the first item in raw_params using
  64. # shlex.split() in order to support paths and files with spaces in the name.
  65. # Any arguments passed to the script will be added back later.
  66. raw_params = to_native(self._task.args.get('_raw_params', ''), errors='surrogate_or_strict')
  67. parts = [to_text(s, errors='surrogate_or_strict') for s in shlex.split(raw_params.strip())]
  68. source = parts[0]
  69. # Support executable paths and files with spaces in the name.
  70. executable = to_native(self._task.args.get('executable', ''), errors='surrogate_or_strict')
  71. try:
  72. source = self._loader.get_real_file(self._find_needle('files', source), decrypt=self._task.args.get('decrypt', True))
  73. except AnsibleError as e:
  74. raise AnsibleActionFail(to_native(e))
  75. # now we execute script, always assume changed.
  76. result['changed'] = True
  77. if not self._play_context.check_mode:
  78. # transfer the file to a remote tmp location
  79. tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir,
  80. os.path.basename(source))
  81. # Convert raw_params to text for the purpose of replacing the script since
  82. # parts and tmp_src are both unicode strings and raw_params will be different
  83. # depending on Python version.
  84. #
  85. # Once everything is encoded consistently, replace the script path on the remote
  86. # system with the remainder of the raw_params. This preserves quoting in parameters
  87. # that would have been removed by shlex.split().
  88. target_command = to_text(raw_params).strip().replace(parts[0], tmp_src)
  89. self._transfer_file(source, tmp_src)
  90. # set file permissions, more permissive when the copy is done as a different user
  91. self._fixup_perms2((self._connection._shell.tmpdir, tmp_src), execute=True)
  92. # add preparation steps to one ssh roundtrip executing the script
  93. env_dict = dict()
  94. env_string = self._compute_environment_string(env_dict)
  95. if executable:
  96. script_cmd = ' '.join([env_string, executable, target_command])
  97. else:
  98. script_cmd = ' '.join([env_string, target_command])
  99. if self._play_context.check_mode:
  100. raise _AnsibleActionDone()
  101. script_cmd = self._connection._shell.wrap_for_exec(script_cmd)
  102. exec_data = None
  103. # PowerShell runs the script in a special wrapper to enable things
  104. # like become and environment args
  105. if self._connection._shell.SHELL_FAMILY == "powershell":
  106. # FUTURE: use a more public method to get the exec payload
  107. pc = self._play_context
  108. exec_data = ps_manifest._create_powershell_wrapper(
  109. to_bytes(script_cmd), {}, env_dict, self._task.async_val,
  110. pc.become, pc.become_method, pc.become_user,
  111. pc.become_pass, pc.become_flags, substyle="script"
  112. )
  113. # build the necessary exec wrapper command
  114. # FUTURE: this still doesn't let script work on Windows with non-pipelined connections or
  115. # full manual exec of KEEP_REMOTE_FILES
  116. script_cmd = self._connection._shell.build_module_command(env_string='', shebang='#!powershell', cmd='')
  117. result.update(self._low_level_execute_command(cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir))
  118. if 'rc' in result and result['rc'] != 0:
  119. raise AnsibleActionFail('non-zero return code')
  120. except AnsibleAction as e:
  121. result.update(e.result)
  122. finally:
  123. self._remove_tmp_path(self._connection._shell.tmpdir)
  124. return result