summaryrefslogtreecommitdiffstats
path: root/ansible_collections/cisco/meraki/plugins/modules/meraki_action_batch.py
blob: 8c7b47a14dfd8f4a9ae04ce24c975d1b3b6259fb (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2021, Kevin Breit (@kbreit) <kevin.breit@kevinbreit.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {
    "metadata_version": "1.1",
    "status": ["deprecated"],
    "supported_by": "community",
}

DOCUMENTATION = r"""
---
module: meraki_action_batch
short_description: Manage Action Batch jobs within the Meraki Dashboard.
description:
- Allows for management of Action Batch jobs for Meraki.
notes:
- This module is in active development and the interface may change.
deprecated:
  removed_in: '3.0.0'
  why: Updated modules released with increased functionality
  alternative: cisco.meraki.organizations_action_batches
options:
  state:
    description:
    - Specifies whether to lookup, create, or delete an Action Batch job.
    choices: ['query', 'present', 'absent']
    default: present
    type: str
  net_name:
    description:
    - Name of network, if applicable.
    type: str
  net_id:
      description:
      - ID of network, if applicable.
      type: str
  action_batch_id:
    description:
    - ID of an existing Action Batch job.
    type: str
  confirmed:
    description:
    - Whether job is to be executed.
    type: bool
    default: False
  synchronous:
    description:
    - Whether job is a synchronous or asynchronous job.
    type: bool
    default: True
  actions:
    description:
    - List of actions the job should execute.
    type: list
    elements: dict
    suboptions:
      operation:
        description:
        - Operation type of action
        type: str
        choices: [
            'create',
            'destroy',
            'update',
            'claim',
            'bind',
            'split',
            'unbind',
            'combine',
            'update_order',
            'cycle',
            'swap',
            'assignSeats',
            'move',
            'moveSeats',
            'renewSeats'
        ]
      resource:
        description:
        - Path to Action Batch resource.
        type: str
      body:
        description:
        - Required body of action.
        type: raw
author:
- Kevin Breit (@kbreit)
extends_documentation_fragment: cisco.meraki.meraki
"""


EXAMPLES = r"""
  - name: Query all Action Batches
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: query
    delegate_to: localhost

  - name: Query one Action Batch job
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: query
      action_batch_id: 12345
    delegate_to: localhost

  - name: Create an Action Batch job
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: present
      actions:
      - resource: '/organizations/org_123/networks'
        operation: 'create'
        body:
          name: 'AnsibleActionBatch1'
          productTypes:
            - 'switch'
    delegate_to: localhost

  - name: Update Action Batch job
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: present
      action_batch_id: 12345
      synchronous: false

  - name: Create an Action Batch job with multiple actions
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: present
      actions:
      - resource: '/organizations/org_123/networks'
        operation: 'create'
        body:
          name: 'AnsibleActionBatch2'
          productTypes:
            - 'switch'
      - resource: '/organizations/org_123/networks'
        operation: 'create'
        body:
          name: 'AnsibleActionBatch3'
          productTypes:
            - 'switch'
    delegate_to: localhost

  - name: Delete an Action Batch job
    meraki_action_batch:
      auth_key: abc123
      org_name: YourOrg
      state: absent
      action_batch_id: 12345
    delegate_to: localhost
"""

RETURN = r"""
data:
    description: Information about action batch jobs.
    type: complex
    returned: always
    contains:
        id:
            description: Unique ID of action batch job.
            returned: success
            type: str
            sample: 123
        organization_id:
            description: Unique ID of organization which owns batch job.
            returned: success
            type: str
            sample: 2930418
        confirmed:
            description: Whether action batch job was confirmed for execution.
            returned: success
            type: bool
        synchronous:
            description: Whether action batch job executes synchronously or asynchronously.
            returned: success
            type: bool
        status:
            description: Information about the action batch job state.
            type: complex
            contains:
                completed:
                    description: Whether job has completed.
                    type: bool
                    returned: success
                failed:
                    description: Whether execution of action batch job failed.
                    type: bool
                    returned: success
                errors:
                    description: List of errors, if any, created during execution.
                    type: list
                    returned: success
                created_resources:
                    description: List of resources created during execution.
                    type: list
                    returned: success
                    sample: [{"id": 100, "uri": "/networks/L_XXXXX/groupPolicies/100"}]
        actions:
            description: List of actions associated to job.
            type: dict
"""

from ansible.module_utils.basic import AnsibleModule, json
from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
    MerakiModule,
    meraki_argument_spec,
)


def _construct_payload(meraki):
    payload = dict()
    payload["confirmed"] = meraki.params["confirmed"]
    payload["synchronous"] = meraki.params["synchronous"]
    if meraki.params["actions"] is not None:  # No payload is specified for an update
        payload["actions"] = list()
        for action in meraki.params["actions"]:
            action_detail = dict()
            if action["resource"] is not None:
                action_detail["resource"] = action["resource"]
            if action["operation"] is not None:
                action_detail["operation"] = action["operation"]
            if action["body"] is not None:
                action_detail["body"] = action["body"]
            payload["actions"].append(action_detail)
    return payload


def main():

    # define the available arguments/parameters that a user can pass to
    # the module

    actions_arg_spec = dict(
        operation=dict(
            type="str",
            choices=[
                "create",
                "destroy",
                "update",
                "claim",
                "bind",
                "split",
                "unbind",
                "combine",
                "update_order",
                "cycle",
                "swap",
                "assignSeats",
                "move",
                "moveSeats",
                "renewSeats",
            ],
        ),
        resource=dict(type="str"),
        body=dict(type="raw"),
    )

    argument_spec = meraki_argument_spec()
    argument_spec.update(
        state=dict(
            type="str", choices=["present", "query", "absent"], default="present"
        ),
        net_name=dict(type="str"),
        net_id=dict(type="str"),
        action_batch_id=dict(type="str", default=None),
        confirmed=dict(type="bool", default=False),
        synchronous=dict(type="bool", default=True),
        actions=dict(
            type="list", default=None, elements="dict", options=actions_arg_spec
        ),
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    meraki = MerakiModule(module, function="action_batch")
    meraki.params["follow_redirects"] = "all"

    query_urls = {"action_batch": "/organizations/{org_id}/actionBatches"}
    query_one_urls = {
        "action_batch": "/organizations/{org_id}/actionBatches/{action_batch_id}"
    }
    create_urls = {"action_batch": "/organizations/{org_id}/actionBatches"}
    update_urls = {
        "action_batch": "/organizations/{org_id}/actionBatches/{action_batch_id}"
    }
    delete_urls = {
        "action_batch": "/organizations/{org_id}/actionBatches/{action_batch_id}"
    }

    meraki.url_catalog["get_all"].update(query_urls)
    meraki.url_catalog["get_one"].update(query_one_urls)
    meraki.url_catalog["create"] = create_urls
    meraki.url_catalog["update"] = update_urls
    meraki.url_catalog["delete"] = delete_urls

    payload = None

    if not meraki.params["org_name"] and not meraki.params["org_id"]:
        meraki.fail_json(msg="org_name or org_id is required")

    org_id = meraki.params["org_id"]
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params["org_name"])

    if meraki.params["state"] == "query":
        if meraki.params["action_batch_id"] is None:  # Get all Action Batches
            path = meraki.construct_path("get_all", org_id=org_id)
            response = meraki.request(path, method="GET")
            if meraki.status == 200:
                meraki.result["data"] = response
                meraki.exit_json(**meraki.result)
        elif meraki.params["action_batch_id"] is not None:  # Query one Action Batch job
            path = meraki.construct_path(
                "get_one",
                org_id=org_id,
                custom={"action_batch_id": meraki.params["action_batch_id"]},
            )
            response = meraki.request(path, method="GET")
            if meraki.status == 200:
                meraki.result["data"] = response
                meraki.exit_json(**meraki.result)
    elif meraki.params["state"] == "present":
        if meraki.params["action_batch_id"] is None:  # Create a new Action Batch job
            payload = _construct_payload(meraki)
            path = meraki.construct_path("create", org_id=org_id)
            response = meraki.request(path, method="POST", payload=json.dumps(payload))
            if meraki.status == 201:
                meraki.result["data"] = response
                meraki.result["changed"] = True
                meraki.exit_json(**meraki.result)
        elif meraki.params["action_batch_id"] is not None:
            path = meraki.construct_path(
                "get_one",
                org_id=org_id,
                custom={"action_batch_id": meraki.params["action_batch_id"]},
            )
            current = meraki.request(path, method="GET")
            payload = _construct_payload(meraki)
            if (
                meraki.params["actions"] is not None
            ):  # Cannot update the body once a job is submitted
                meraki.fail_json(msg="Body cannot be updated on existing job.")
            if (
                meraki.is_update_required(current, payload) is True
            ):  # Job needs to be modified
                path = meraki.construct_path(
                    "update",
                    org_id=org_id,
                    custom={"action_batch_id": meraki.params["action_batch_id"]},
                )
                response = meraki.request(
                    path, method="PUT", payload=json.dumps(payload)
                )
                if meraki.status == 200:
                    meraki.result["data"] = response
                    meraki.result["changed"] = True
                    meraki.exit_json(**meraki.result)
            else:  # Idempotent response
                meraki.result["data"] = current
                meraki.exit_json(**meraki.result)
    elif meraki.params["state"] == "absent":
        path = meraki.construct_path(
            "delete",
            org_id=org_id,
            custom={"action_batch_id": meraki.params["action_batch_id"]},
        )
        response = meraki.request(path, method="DELETE")
        if meraki.status == 204:
            meraki.result["data"] = response
            meraki.result["changed"] = True

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    meraki.exit_json(**meraki.result)


if __name__ == "__main__":
    main()