Ansible role for running puppet
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

puppet 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #!/usr/bin/python
  2. # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
  3. #
  4. # This module is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This software is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this software. If not, see <http://www.gnu.org/licenses/>.
  16. import os
  17. import pipes
  18. import stat
  19. try:
  20. import json
  21. except ImportError:
  22. try:
  23. import simplejson as json
  24. except ImportError:
  25. # Let snippet from module_utils/basic.py return a proper error in this case
  26. pass
  27. DOCUMENTATION = '''
  28. ---
  29. module: puppet
  30. short_description: Runs puppet
  31. description:
  32. - Runs I(puppet) agent or apply in a reliable manner
  33. version_added: "2.0"
  34. options:
  35. timeout:
  36. description:
  37. - How long to wait for I(puppet) to finish.
  38. required: false
  39. default: 30m
  40. puppetmaster:
  41. description:
  42. - The hostname of the puppetmaster to contact.
  43. required: false
  44. default: None
  45. manifest:
  46. description:
  47. - Path to the manifest file to run puppet apply on.
  48. required: false
  49. default: None
  50. facts:
  51. description:
  52. - A dict of values to pass in as persistent external facter facts
  53. required: false
  54. default: None
  55. facter_basename:
  56. description:
  57. - Basename of the facter output file
  58. required: false
  59. default: ansible
  60. environment:
  61. description:
  62. - Puppet environment to be used.
  63. required: false
  64. default: None
  65. logdest:
  66. description:
  67. - Where the puppet logs should go, if puppet apply is being used
  68. required: false
  69. default: stdout
  70. version_added: "2.1"
  71. requirements: [ puppet ]
  72. author: "Monty Taylor (@emonty)"
  73. '''
  74. EXAMPLES = '''
  75. # Run puppet agent and fail if anything goes wrong
  76. - puppet
  77. # Run puppet and timeout in 5 minutes
  78. - puppet: timeout=5m
  79. # Run puppet using a different environment
  80. - puppet: environment=testing
  81. '''
  82. def _get_facter_dir():
  83. if os.getuid() == 0:
  84. return '/etc/facter/facts.d'
  85. else:
  86. return os.path.expanduser('~/.facter/facts.d')
  87. def _write_structured_data(basedir, basename, data):
  88. if not os.path.exists(basedir):
  89. os.makedirs(basedir)
  90. file_path = os.path.join(basedir, "{0}.json".format(basename))
  91. # This is more complex than you might normally expect because we want to
  92. # open the file with only u+rw set. Also, we use the stat constants
  93. # because ansible still supports python 2.4 and the octal syntax changed
  94. out_file = os.fdopen(
  95. os.open(
  96. file_path, os.O_CREAT | os.O_WRONLY,
  97. stat.S_IRUSR | stat.S_IWUSR), 'w')
  98. out_file.write(json.dumps(data).encode('utf8'))
  99. out_file.close()
  100. def main():
  101. module = AnsibleModule(
  102. argument_spec=dict(
  103. timeout=dict(default="30m"),
  104. puppetmaster=dict(required=False, default=None),
  105. manifest=dict(required=False, default=None),
  106. logdest=dict(
  107. required=False, default='stdout'),
  108. show_diff=dict(
  109. # internal code to work with --diff, do not use
  110. default=False, aliases=['show-diff'], type='bool'),
  111. facts=dict(default=None),
  112. facter_basename=dict(default='ansible'),
  113. environment=dict(required=False, default=None),
  114. ),
  115. supports_check_mode=True,
  116. mutually_exclusive=[
  117. ('puppetmaster', 'manifest'),
  118. ],
  119. )
  120. p = module.params
  121. global PUPPET_CMD
  122. PUPPET_CMD = module.get_bin_path("puppet", False)
  123. if not PUPPET_CMD:
  124. module.fail_json(
  125. msg="Could not find puppet. Please ensure it is installed.")
  126. global TIMEOUT_CMD
  127. TIMEOUT_CMD = module.get_bin_path("timeout", False)
  128. if p['manifest']:
  129. if not os.path.exists(p['manifest']):
  130. module.fail_json(
  131. msg="Manifest file %(manifest)s not found." % dict(
  132. manifest=p['manifest']))
  133. # Check if puppet is disabled here
  134. if not p['manifest']:
  135. rc, stdout, stderr = module.run_command(
  136. PUPPET_CMD + " config print agent_disabled_lockfile")
  137. if os.path.exists(stdout.strip()):
  138. module.fail_json(
  139. msg="Puppet agent is administratively disabled.",
  140. disabled=True)
  141. elif rc != 0:
  142. module.fail_json(
  143. msg="Puppet agent state could not be determined.")
  144. if module.params['facts'] and not module.check_mode:
  145. _write_structured_data(
  146. _get_facter_dir(),
  147. module.params['facter_basename'],
  148. module.params['facts'])
  149. if TIMEOUT_CMD:
  150. base_cmd = "%(timeout_cmd)s -s 9 %(timeout)s %(puppet_cmd)s" % dict(
  151. timeout_cmd=TIMEOUT_CMD,
  152. timeout=pipes.quote(p['timeout']),
  153. puppet_cmd=PUPPET_CMD)
  154. else:
  155. base_cmd = PUPPET_CMD
  156. if not p['manifest']:
  157. cmd = ("%(base_cmd)s agent --onetime"
  158. " --ignorecache --no-daemonize --no-usecacheonfailure"
  159. " --no-splay --detailed-exitcodes --verbose") % dict(
  160. base_cmd=base_cmd,
  161. )
  162. if p['puppetmaster']:
  163. cmd += " --server %s" % pipes.quote(p['puppetmaster'])
  164. if p['show_diff']:
  165. cmd += " --show_diff"
  166. if p['environment']:
  167. cmd += " --environment '%s'" % p['environment']
  168. if module.check_mode:
  169. cmd += " --noop"
  170. else:
  171. cmd += " --no-noop"
  172. else:
  173. cmd = "%s apply --detailed-exitcodes " % base_cmd
  174. if p['show_diff']:
  175. cmd += "--show_diff "
  176. if p['logdest'] != 'stdout':
  177. cmd += "--logdest %s " % p['logdest']
  178. if p['environment']:
  179. cmd += "--environment '%s' " % p['environment']
  180. if module.check_mode:
  181. cmd += "--noop "
  182. else:
  183. cmd += "--no-noop "
  184. cmd += pipes.quote(p['manifest'])
  185. rc, stdout, stderr = module.run_command(cmd)
  186. if rc == 0:
  187. # success
  188. module.exit_json(rc=rc, changed=False, stdout=stdout)
  189. elif rc == 1:
  190. # rc==1 could be because it's disabled
  191. # rc==1 could also mean there was a compilation failure
  192. disabled = "administratively disabled" in stdout
  193. if disabled:
  194. msg = "puppet is disabled"
  195. else:
  196. msg = "puppet did not run"
  197. module.exit_json(
  198. rc=rc, disabled=disabled, msg=msg,
  199. error=True, stdout=stdout, stderr=stderr)
  200. elif rc == 2:
  201. # success with changes
  202. module.exit_json(rc=0, changed=True, stdout=stdout, stderr=stderr)
  203. elif rc == 124:
  204. # timeout
  205. module.exit_json(
  206. rc=rc, msg="%s timed out" % cmd, stdout=stdout, stderr=stderr)
  207. else:
  208. # failure
  209. module.fail_json(
  210. rc=rc, msg="%s failed with return code: %d" % (cmd, rc),
  211. stdout=stdout, stderr=stderr)
  212. # import module snippets
  213. from ansible.module_utils.basic import *
  214. if __name__ == '__main__':
  215. main()