summaryrefslogtreecommitdiffstats
path: root/ansible_collections/theforeman/foreman/plugins/modules/job_template.py
blob: 57ed1577e374b791f13d1acd52d17ecf5bc89994 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018 Manuel Bonk & Matthias Dellweg (ATIX AG)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
---
module: job_template
version_added: 1.0.0
short_description: Manage Job Templates
description:
  - Manage Remote Execution Job Templates
author:
  - "Manuel Bonk (@manuelbonk) ATIX AG"
  - "Matthias Dellweg (@mdellweg) ATIX AG"
options:
  audit_comment:
    description:
      - Content of the audit comment field
    type: str
  description_format:
    description:
      - description of the job template. Template inputs can be referenced.
    type: str
  file_name:
    description:
      - The path of a template file, that shall be imported.
      - Either this or I(template) is required as a source for the Job Template "content".
    type: path
  job_category:
    description:
      - The category the template should be assigend to
    type: str
  locked:
    description:
      - Determines whether the template shall be locked
    default: false
    type: bool
  name:
    description:
      - The name of the Job Template.
      - If omited, will be determined from the C(name) header of the template or the filename (in that order).
      - The special value "*" can be used to perform bulk actions (modify, delete) on all existing templates.
    type: str
  provider_type:
    description:
      - Determines via which provider the template shall be executed
    required: false
    type: str
  snippet:
    description:
      - Determines whether the template shall be a snippet
    type: bool
  template:
    description:
      - The content of the Job Template.
      - Either this or I(file_name) is required as a source for the Job Template "content".
    type: str
  template_inputs:
    description:
      - The template inputs used in the Job Template
    type: list
    elements: dict
    suboptions:
      advanced:
        description:
          - Template Input is advanced
        type: bool
      description:
        description:
          - description of the Template Input
        type: str
      fact_name:
        description:
          - Fact name to use.
          - Required when I(input_type=fact).
        type: str
      input_type:
        description:
          - input type
        required: true
        choices:
          - user
          - fact
          - variable
          - puppet_parameter
        type: str
      name:
        description:
          - name of the Template Input
        required: true
        type: str
      options:
        description:
          - Template values for user inputs. Must be an array of any type.
        type: list
        elements: raw
      puppet_class_name:
        description:
          - Puppet class name.
          - Required when I(input_type=puppet_parameter).
        type: str
      puppet_parameter_name:
        description:
          - Puppet parameter name.
          - Required when I(input_type=puppet_parameter).
        type: str
      required:
        description:
          - Is the input required
        type: bool
      variable_name:
        description:
          - Variable name to use.
          - Required when I(input_type=variable).
        type: str
      value_type:
        description:
          - Type of the value
        choices:
          - plain
          - search
          - date
          - resource
        type: str
      resource_type:
        description:
          - Type of the resource
        type: str
      hidden_value:
        description:
          - The value contains sensitive information and should't be normally visible, useful e.g. for passwords
        type: bool
      default:
        description:
          - Default value for user input
        type: str
        version_added: 3.8.0
extends_documentation_fragment:
  - theforeman.foreman.foreman
  - theforeman.foreman.foreman.entity_state_with_defaults
  - theforeman.foreman.foreman.taxonomy
'''

EXAMPLES = '''

- name: "Create a Job Template inline"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: A New Job Template
    state: present
    template: |
      <%#
          name: A Job Template
      %>
      rm -rf <%= input("toDelete") %>
    template_inputs:
      - name: toDelete
        input_type: user
    locations:
      - Gallifrey
    organizations:
      - TARDIS INC

- name: "Create a Job Template from a file"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: a new job template
    file_name: timeywimey_template.erb
    template_inputs:
      - name: a new template input
        input_type: user
    state: present
    locations:
      - Gallifrey
    organizations:
      - TARDIS INC

- name: "remove a job template's template inputs"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: a new job template
    template_inputs: []
    state: present
    locations:
      - Gallifrey
    organizations:
      - TARDIS INC

- name: "Delete a Job Template"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: timeywimey
    state: absent

- name: "Create a Job Template from a file and modify with parameter(s)"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    file_name: timeywimey_template.erb
    name: Wibbly Wobbly Template
    state: present
    locations:
      - Gallifrey
    organizations:
      - TARDIS INC

# Providing a name in this case wouldn't be very sensible.
# Alternatively make use of with_filetree to parse recursively with filter.
- name: Parsing a directory of Job templates
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    file_name: "{{ item }}"
    state: present
    locations:
      - SKARO
    organizations:
      - DALEK INC
  with_fileglob:
    - "./arsenal_templates/*.erb"

# If the templates are stored locally and the ansible module is executed on a remote host
- name: Ensure latest version of all your Job Templates
  theforeman.foreman.job_template:
    server_url: "https://foreman.example.com"
    username: "admin"
    password: "changeme"
    state: present
    template: '{{ lookup("file", item.src) }}'
    name: '{{ item.path }}'
  with_filetree: '/path/to/job/templates'
  when: item.state == 'file'


# with name set to "*" bulk actions can be performed
- name: "Delete *ALL* Job Templates"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: "*"
    state: absent

- name: "Assign all Job Templates to the same organization(s)"
  theforeman.foreman.job_template:
    username: "admin"
    password: "changeme"
    server_url: "https://foreman.example.com"
    name: "*"
    state: present
    organizations:
      - DALEK INC
      - sky.net
      - Doc Brown's garage

'''

RETURN = '''
entity:
  description: Final state of the affected entities grouped by their type.
  returned: success
  type: dict
  contains:
    job_templates:
      description: List of job templates.
      type: list
      elements: dict
    template_inputs:
      description: List of template inputs associated with the job template.
      type: list
      elements: dict
'''

import os
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import (
    ForemanTaxonomicEntityAnsibleModule,
    parse_template,
    parse_template_from_file,
)


template_defaults = {
    'provider_type': 'SSH',
    'job_category': 'unknown',
}


template_input_foreman_spec = {
    'id': dict(invisible=True),
    'name': dict(required=True),
    'description': dict(),
    'required': dict(type='bool'),
    'advanced': dict(type='bool'),
    'input_type': dict(required=True, choices=[
        'user',
        'fact',
        'variable',
        'puppet_parameter',
    ]),
    'fact_name': dict(),
    'variable_name': dict(),
    'puppet_class_name': dict(),
    'puppet_parameter_name': dict(),
    'options': dict(type='list', elements='raw'),
    'value_type': dict(choices=[
        'plain',
        'search',
        'date',
        'resource',
    ]),
    'resource_type': dict(),
    'hidden_value': dict(type='bool'),
    'default': dict(),
}


class ForemanJobTemplateModule(ForemanTaxonomicEntityAnsibleModule):
    pass


def main():
    module = ForemanJobTemplateModule(
        foreman_spec=dict(
            description_format=dict(),
            job_category=dict(),
            locked=dict(type='bool', default=False),
            name=dict(),
            provider_type=dict(),
            snippet=dict(type='bool'),
            template=dict(),
            template_inputs=dict(
                type='nested_list',
                foreman_spec=template_input_foreman_spec,
                required_if=(
                    ['input_type', 'fact', ('fact_name',)],
                    ['input_type', 'variable', ('variable_name',)],
                    ['input_type', 'puppet_parameter', ('puppet_class_name', 'puppet_parameter_name')],
                ),
            ),
        ),
        argument_spec=dict(
            audit_comment=dict(),
            file_name=dict(type='path'),
            state=dict(default='present', choices=['absent', 'present_with_defaults', 'present']),
        ),
        mutually_exclusive=[
            ['file_name', 'template'],
        ],
        required_one_of=[
            ['name', 'file_name', 'template'],
        ],
    )

    # We do not want a layout text for bulk operations
    if module.foreman_params.get('name') == '*':
        if module.foreman_params.get('file_name') or module.foreman_params.get('template'):
            module.fail_json(
                msg="Neither file_name nor template allowed if 'name: *'!")

    entity = None
    file_name = module.foreman_params.pop('file_name', None)

    if file_name or 'template' in module.foreman_params:
        if file_name:
            parsed_dict = parse_template_from_file(file_name, module)
        else:
            parsed_dict = parse_template(module.foreman_params['template'], module)
        # sanitize name from template data
        # The following condition can actually be hit, when someone is trying to import a
        # template with the name set to '*'.
        # Besides not being sensible, this would go horribly wrong in this module.
        if parsed_dict.get('name') == '*':
            module.fail_json(msg="Cannot use '*' as a job template name!")
        # module params are priorized
        parsed_dict.update(module.foreman_params)
        # make sure certain values are set
        module.foreman_params = template_defaults.copy()
        module.foreman_params.update(parsed_dict)

    # make sure, we have a name
    if 'name' not in module.foreman_params:
        if file_name:
            module.foreman_params['name'] = os.path.splitext(
                os.path.basename(file_name))[0]
        else:
            module.fail_json(
                msg='No name specified and no filename to infer it.')

    affects_multiple = module.foreman_params['name'] == '*'
    # sanitize user input, filter unuseful configuration combinations with 'name: *'
    if affects_multiple:
        if module.state == 'present_with_defaults':
            module.fail_json(msg="'state: present_with_defaults' and 'name: *' cannot be used together")
        if module.desired_absent:
            further_params = set(module.foreman_params.keys()) - {'name', 'entity'}
            if further_params:
                module.fail_json(msg='When deleting all job templates, there is no need to specify further parameters: %s ' % further_params)

    with module.api_connection():
        if 'audit_comment' in module.foreman_params:
            extra_params = {'audit_comment': module.foreman_params['audit_comment']}
        else:
            extra_params = {}

        if affects_multiple:
            module.set_entity('entity', None)  # prevent lookup
            entities = module.list_resource('job_templates')
            if not entities:
                # Nothing to do; shortcut to exit
                module.exit_json()
            if not module.desired_absent:  # not 'thin'
                entities = [module.show_resource('job_templates', entity['id']) for entity in entities]
                module.auto_lookup_entities()
            module.foreman_params.pop('name')
            for entity in entities:
                module.ensure_entity('job_templates', module.foreman_params, entity, params=extra_params)
        else:
            # The name could have been determined to late, so copy it again
            module.foreman_params['entity'] = module.foreman_params['name']
            entity = module.lookup_entity('entity')
            # TemplateInputs need to be added as separate entities later
            template_inputs = module.foreman_params.get('template_inputs')

            job_template = module.run(params=extra_params)

            update_dependent_entities = (module.state == 'present' or (module.state == 'present_with_defaults' and module.changed))
            if update_dependent_entities and template_inputs is not None:
                scope = {'template_id': job_template['id']}

                # Manage TemplateInputs here
                current_template_input_list = module.list_resource('template_inputs', params=scope) if entity else []
                current_template_inputs = {item['name']: item for item in current_template_input_list}
                for template_input_dict in template_inputs:
                    template_input_entity = current_template_inputs.pop(template_input_dict['name'], None)

                    module.ensure_entity(
                        'template_inputs', template_input_dict, template_input_entity,
                        params=scope, foreman_spec=template_input_foreman_spec,
                    )

                # At this point, desired template inputs have been removed from the dict.
                for template_input_entity in current_template_inputs.values():
                    module.ensure_entity(
                        'template_inputs', None, template_input_entity, state="absent",
                        params=scope, foreman_spec=template_input_foreman_spec,
                    )


if __name__ == '__main__':
    main()