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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. choices: [ 'stdout', 'syslog' ]
  71. version_added: "2.1"
  72. requirements: [ puppet ]
  73. author: "Monty Taylor (@emonty)"
  74. '''
  75. EXAMPLES = '''
  76. # Run puppet agent and fail if anything goes wrong
  77. - puppet
  78. # Run puppet and timeout in 5 minutes
  79. - puppet: timeout=5m
  80. # Run puppet using a different environment
  81. - puppet: environment=testing
  82. '''
  83. def _get_facter_dir():
  84. if os.getuid() == 0:
  85. return '/etc/facter/facts.d'
  86. else:
  87. return os.path.expanduser('~/.facter/facts.d')
  88. def _write_structured_data(basedir, basename, data):
  89. if not os.path.exists(basedir):
  90. os.makedirs(basedir)
  91. file_path = os.path.join(basedir, "{0}.json".format(basename))
  92. # This is more complex than you might normally expect because we want to
  93. # open the file with only u+rw set. Also, we use the stat constants
  94. # because ansible still supports python 2.4 and the octal syntax changed
  95. out_file = os.fdopen(
  96. os.open(
  97. file_path, os.O_CREAT | os.O_WRONLY,
  98. stat.S_IRUSR | stat.S_IWUSR), 'w')
  99. out_file.write(json.dumps(data).encode('utf8'))
  100. out_file.close()
  101. def main():
  102. module = AnsibleModule(
  103. argument_spec=dict(
  104. timeout=dict(default="30m"),
  105. puppetmaster=dict(required=False, default=None),
  106. manifest=dict(required=False, default=None),
  107. logdest=dict(
  108. required=False, default='stdout',
  109. choices=['stdout', 'syslog']),
  110. show_diff=dict(
  111. # internal code to work with --diff, do not use
  112. default=False, aliases=['show-diff'], type='bool'),
  113. facts=dict(default=None),
  114. facter_basename=dict(default='ansible'),
  115. environment=dict(required=False, default=None),
  116. ),
  117. supports_check_mode=True,
  118. mutually_exclusive=[
  119. ('puppetmaster', 'manifest'),
  120. ],
  121. )
  122. p = module.params
  123. global PUPPET_CMD
  124. PUPPET_CMD = module.get_bin_path("puppet", False)
  125. if not PUPPET_CMD:
  126. module.fail_json(
  127. msg="Could not find puppet. Please ensure it is installed.")
  128. global TIMEOUT_CMD
  129. TIMEOUT_CMD = module.get_bin_path("timeout", False)
  130. if p['manifest']:
  131. if not os.path.exists(p['manifest']):
  132. module.fail_json(
  133. msg="Manifest file %(manifest)s not found." % dict(
  134. manifest=p['manifest']))
  135. # Check if puppet is disabled here
  136. if not p['manifest']:
  137. rc, stdout, stderr = module.run_command(
  138. PUPPET_CMD + " config print agent_disabled_lockfile")
  139. if os.path.exists(stdout.strip()):
  140. module.fail_json(
  141. msg="Puppet agent is administratively disabled.",
  142. disabled=True)
  143. elif rc != 0:
  144. module.fail_json(
  145. msg="Puppet agent state could not be determined.")
  146. if module.params['facts'] and not module.check_mode:
  147. _write_structured_data(
  148. _get_facter_dir(),
  149. module.params['facter_basename'],
  150. module.params['facts'])
  151. if TIMEOUT_CMD:
  152. base_cmd = "%(timeout_cmd)s -s 9 %(timeout)s %(puppet_cmd)s" % dict(
  153. timeout_cmd=TIMEOUT_CMD,
  154. timeout=pipes.quote(p['timeout']),
  155. puppet_cmd=PUPPET_CMD)
  156. else:
  157. base_cmd = PUPPET_CMD
  158. if not p['manifest']:
  159. cmd = ("%(base_cmd)s agent --onetime"
  160. " --ignorecache --no-daemonize --no-usecacheonfailure"
  161. " --no-splay --detailed-exitcodes --verbose") % dict(
  162. base_cmd=base_cmd,
  163. )
  164. if p['puppetmaster']:
  165. cmd += " --server %s" % pipes.quote(p['puppetmaster'])
  166. if p['show_diff']:
  167. cmd += " --show_diff"
  168. if p['environment']:
  169. cmd += " --environment '%s'" % p['environment']
  170. if module.check_mode:
  171. cmd += " --noop"
  172. else:
  173. cmd += " --no-noop"
  174. else:
  175. cmd = "%s apply --detailed-exitcodes " % base_cmd
  176. if p['logdest'] == 'syslog':
  177. cmd += "--logdest syslog "
  178. if p['show_diff']:
  179. cmd += "--show_diff "
  180. if p['environment']:
  181. cmd += "--environment '%s' " % p['environment']
  182. if module.check_mode:
  183. cmd += "--noop "
  184. else:
  185. cmd += "--no-noop "
  186. cmd += pipes.quote(p['manifest'])
  187. rc, stdout, stderr = module.run_command(cmd)
  188. if rc == 0:
  189. # success
  190. module.exit_json(rc=rc, changed=False, stdout=stdout)
  191. elif rc == 1:
  192. # rc==1 could be because it's disabled
  193. # rc==1 could also mean there was a compilation failure
  194. disabled = "administratively disabled" in stdout
  195. if disabled:
  196. msg = "puppet is disabled"
  197. else:
  198. msg = "puppet did not run"
  199. module.exit_json(
  200. rc=rc, disabled=disabled, msg=msg,
  201. error=True, stdout=stdout, stderr=stderr)
  202. elif rc == 2:
  203. # success with changes
  204. module.exit_json(rc=0, changed=True, stdout=stdout, stderr=stderr)
  205. elif rc == 124:
  206. # timeout
  207. module.exit_json(
  208. rc=rc, msg="%s timed out" % cmd, stdout=stdout, stderr=stderr)
  209. else:
  210. # failure
  211. module.fail_json(
  212. rc=rc, msg="%s failed with return code: %d" % (cmd, rc),
  213. stdout=stdout, stderr=stderr)
  214. # import module snippets
  215. from ansible.module_utils.basic import *
  216. if __name__ == '__main__':
  217. main()