-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathquads_self_schedule.yml
More file actions
505 lines (463 loc) · 20.8 KB
/
Copy pathquads_self_schedule.yml
File metadata and controls
505 lines (463 loc) · 20.8 KB
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
- name: QUADS Self-Scheduling Workflow
hosts: localhost
connection: local
gather_facts: false
vars_files:
- quads_config.yml
pre_tasks:
- name: Ensure 'workload_name' is provided (if not listing)
when:
- not list_servers_only | default(false)
- not list_active_only | default(false)
ansible.builtin.assert:
that:
- workload_name is defined
- workload_name | trim | length > 0
fail_msg: >-
Please run the playbook with '-e workload_name=' per the docs.
Make sure you wrap the 'workload_name' value in single quotes.
(See examples)
changed_when: false
- name: Validate 'num_hosts' if provided
when: num_hosts is defined
ansible.builtin.assert:
that:
- num_hosts | int > 0
fail_msg: >-
'num_hosts' must be a positive integer greater than 0.
Got: {{ num_hosts }}
changed_when: false
- name: Validate 'preferred_models' type if provided
when:
- preferred_models is defined
- preferred_models is not string
ansible.builtin.assert:
that:
- preferred_models is iterable
- preferred_models is not mapping
fail_msg: >-
'preferred_models' must be either a list of model names or the string "all".
Got type: {{ preferred_models | type_debug }}
changed_when: false
- name: Validate 'preferred_models' is not empty if provided as a list
when:
- preferred_models is defined
- preferred_models is not string
- preferred_models is iterable
- preferred_models is not mapping
ansible.builtin.assert:
that:
- preferred_models | length > 0
fail_msg: >-
'preferred_models' is defined as an empty list.
Either provide model names in the list or set to "all" for any model.
changed_when: false
- name: Warn about duplicate models in preferred_models
when:
- preferred_models is defined
- preferred_models is not string
- preferred_models is iterable
- preferred_models is not mapping
- preferred_models | length > 0
- preferred_models | map('upper') | unique | length < (preferred_models | length)
ansible.builtin.debug:
msg: >-
WARNING: Duplicate models detected in preferred_models list (case-insensitive).
This will cause redundant API calls since models are converted to uppercase.
Duplicates: {%- set duplicates = [] -%}
{%- set upper_models = preferred_models | map('upper') | list -%}
{%- for item in upper_models | unique -%}
{%- if upper_models.count(item) > 1 -%}
{%- set _ = duplicates.append(item) -%}
{%- endif -%}
{%- endfor -%}
{{ duplicates | join(', ') }}
changed_when: false
- name: Get current time for timestamping output file
ansible.builtin.setup:
filter: ansible_date_time
changed_when: false
tasks:
- name: Set up API and user variables
ansible.builtin.set_fact:
quads_user_email: "{{ quads_username }}@{{ quads_user_domain }}"
base_api_url: "https://{{ quads_api_server }}/api/v3"
use_api_token: "{{ (quads_api_token | default('') | length > 0) | bool }}"
changed_when: false
- name: Validate that at least one authentication method is configured
ansible.builtin.assert:
that:
- (use_api_token | bool) or (quads_password is defined and quads_password | length > 0)
fail_msg: >-
No authentication configured. Set either quads_api_token (preferred)
or quads_password in quads_config.yml.
changed_when: false
- name: Authenticate with SSO API token
when: use_api_token | bool
block:
- name: Set token fact from config
ansible.builtin.set_fact:
quads_token: "{{ quads_api_token }}"
changed_when: false
- name: Validate API token against server
ansible.builtin.uri:
url: "{{ base_api_url }}/version"
method: GET
headers:
Authorization: "Bearer {{ quads_token }}"
validate_certs: false
status_code: 200
register: token_check
- name: Display SSO token authentication
ansible.builtin.debug:
msg: "Authenticated via SSO API token as {{ quads_user_email }}"
changed_when: false
- name: Authenticate with username and password
when: not (use_api_token | bool)
block:
- name: Register user with QUADS server
no_log: true
ansible.builtin.uri:
url: "{{ base_api_url }}/register"
method: POST
body_format: json
body:
email: "{{ quads_user_email }}"
password: "{{ quads_password }}"
validate_certs: false
status_code: [200, 201, 409, 401]
- name: Log in and handle authentication errors
block:
- name: Attempt to log in and retrieve authentication token
no_log: true
ansible.builtin.uri:
url: "{{ base_api_url }}/login/"
method: POST
url_username: "{{ quads_user_email }}"
url_password: "{{ quads_password }}"
validate_certs: false
status_code: 200
register: login_result
rescue:
- name: Provide a clear error message for authentication failure
ansible.builtin.fail:
msg: >-
Login failed for user '{{ quads_username }}'.
Please verify the username and password in your quads_config.yml file are correct (401 Unauthorized).
when: login_result.status is defined and login_result.status == 401
- name: Provide error message for HTTP errors
ansible.builtin.fail:
msg: >-
Login failed with HTTP status {{ login_result.status }}.
Error: {{ login_result.msg | default('Unknown error') }}
when: login_result.status is defined and login_result.status != 401
- name: Provide error message for network/connectivity issues
ansible.builtin.fail:
msg: >-
Login failed - could not reach QUADS server at {{ base_api_url }}/login/
Error: {{ login_result.msg | default('Connection failed') }}
This may be a network connectivity issue, DNS failure, or the server may be down.
Please verify the quads_api_server setting in quads_config.yml is correct.
when: login_result.status is not defined
- name: Set token fact from login response
ansible.builtin.set_fact:
quads_token: "{{ login_result.json.auth_token }}"
changed_when: false
- name: List active assignments if requested
when: list_active_only | default(false)
block:
- name: Get list of active assignments for user
ansible.builtin.uri:
url: "{{ base_api_url }}/assignments?owner={{ quads_username }}&is_self_schedule=true&active=true"
method: GET
headers:
Authorization: "Bearer {{ quads_token }}"
validate_certs: false
status_code: 200
register: active_assignments
- name: Display confirmation of no active assignments
when: active_assignments.json | length == 0
ansible.builtin.debug:
msg: "No active self-scheduled assignments found for user {{ quads_username }}"
- name: Display active assignments with helper commands
when: active_assignments.json | length > 0
ansible.builtin.debug:
var: assignments_summary
vars:
assignments_summary: >-
{%- set result = [] -%}
{%- for asn in active_assignments.json -%}
{%- set check_cmd = "curl -s https://%s/api/v3/assignments/%s | jq '.validated'" | format(quads_api_server, asn.id) -%}
{%- if use_api_token | bool -%}
{%- set term_cmd = 'curl -s -k -X POST -H "Authorization: Bearer %s" https://%s/api/v3/assignments/terminate/%s | jq' | format(
quads_token, quads_api_server, asn.id) -%}
{%- else -%}
{%- set login_cmd = "curl -s -k -X POST -u '%s:%s' https://%s/api/v3/login/ | jq -r '.auth_token'" | format(
quads_user_email, quads_password, quads_api_server) -%}
{%- set term_cmd = 'curl -s -k -X POST -H "Authorization: Bearer $(%s)" https://%s/api/v3/assignments/terminate/%s | jq' | format(
login_cmd, quads_api_server, asn.id) -%}
{%- endif -%}
{%- set _ = asn.update({'check_status_command': check_cmd, 'terminate_command': term_cmd}) -%}
{%- set _ = result.append(asn) -%}
{%- endfor -%}
{{ result }}
- name: End playbook execution
ansible.builtin.meta: end_play
- name: Get list of available hosts that can be self-scheduled
ansible.builtin.uri:
url: "{{ base_api_url }}/available?can_self_schedule=true"
method: GET
headers:
Authorization: "Bearer {{ quads_token }}"
validate_certs: false
status_code: 200
register: available_hosts
- name: Get available hosts per preferred model
when:
- schedule_servers is not defined
- not list_servers_only | default(false)
- not list_active_only | default(false)
- preferred_models is defined
- preferred_models is not string
- preferred_models is iterable
- preferred_models is not mapping
ansible.builtin.uri:
url: "{{ base_api_url }}/available?can_self_schedule=true&model={{ item | upper }}"
method: GET
headers:
Authorization: "Bearer {{ quads_token }}"
validate_certs: false
status_code: 200
loop: "{{ preferred_models if (preferred_models is iterable and preferred_models is not string and preferred_models is not mapping) else [] }}"
loop_control:
label: "{{ item }}"
register: available_by_model
- name: Display available server hostnames and exit
when: list_servers_only | default(false)
block:
- name: Print list of available servers
ansible.builtin.debug:
msg: "{{ available_hosts.json }}"
- name: End playbook execution
ansible.builtin.meta: end_play
- name: Prepare user-specified hosts for scheduling
when: schedule_servers is defined
ansible.builtin.set_fact:
hosts_to_schedule: "{{ schedule_servers.split(',') | map('trim') | map('community.general.dict_kv', 'name') | list }}"
- name: Auto-select hosts when none are specified
when: schedule_servers is not defined
block:
- name: Display the number of available hosts found
ansible.builtin.debug:
msg: "Found {{ available_hosts.json | length }} hosts available for self-scheduling."
when: available_hosts.json is sequence
changed_when: false
- name: Select hosts by model preference order
when:
- preferred_models is defined
- preferred_models is not string
- available_by_model is defined
ansible.builtin.set_fact:
hosts_to_schedule: "{{ selected_json | from_json }}"
vars:
needed: "{{ num_hosts | default(1) | int }}"
selected_json: >-
{%- set result = [] -%}
{%- for model_result in available_by_model.results | default([]) -%}
{%- set hosts = model_result.json | default([]) -%}
{%- if hosts is sequence and not hosts is string -%}
{%- if result | length < needed | int -%}
{%- for host in hosts -%}
{%- set existing_hosts = result | map(attribute='name') | list -%}
{%- if result | length < needed | int and host not in existing_hosts -%}
{%- set _ = result.append({'name': host}) -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{{ result | to_json }}
changed_when: false
- name: Display model selection results
when:
- preferred_models is defined
- preferred_models is not string
- hosts_to_schedule is defined
- available_by_model is defined
vars:
selected_hosts_info: >-
{%- set lines = [] -%}
{%- for model_result in available_by_model.results | default([]) -%}
{%- set hosts = model_result.json | default([]) -%}
{%- if hosts is sequence and not hosts is string -%}
{%- for h in hosts_to_schedule -%}
{%- if h.name in hosts -%}
{%- set _ = lines.append(h.name ~ ' (model: ' ~ model_result.item ~ ')') -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{{ lines | to_json }}
ansible.builtin.debug:
msg: "{{ ['Selected ' ~ hosts_to_schedule | length ~ ' host(s) by model preference:'] + (selected_hosts_info | from_json) }}"
changed_when: false
- name: Select first available hosts (no model preference)
when: preferred_models is not defined or preferred_models is string
ansible.builtin.set_fact:
hosts_to_schedule: "{{ selected_hostnames | map('community.general.dict_kv', 'name') | list }}"
vars:
selected_hostnames: "{{ available_hosts.json[: (num_hosts | default(1) | int)] }}"
changed_when: false
- name: Assert that enough hosts were selected
ansible.builtin.assert:
that:
- hosts_to_schedule is defined
- hosts_to_schedule | length >= (num_hosts | default(1) | int)
fail_msg: >-
Could not find enough available hosts matching preferences.
Selected {{ hosts_to_schedule | length | default(0) }},
but need {{ num_hosts | default(1) }}.
{% if preferred_models is defined and preferred_models is not string %}
Preferred models tried: {{ preferred_models | join(', ') }}.
{% endif %}
Please try again later or adjust preferred_models.
changed_when: false
- name: Attempt to create a new assignment
ansible.builtin.uri:
url: "{{ base_api_url }}/assignments/self"
method: POST
headers:
Authorization: "Bearer {{ quads_token }}"
body_format: json
body:
description: "{{ workload_name }}"
owner: "{{ quads_username }}"
qinq: "{{ qinq | default(0) }}"
wipe: "{{ wipe | default('true') }}"
validate_certs: false
status_code: [201, 403]
register: assignment_creation_result
- name: Get existing assignment details if creation was forbidden
when: assignment_creation_result.status == 403
ansible.builtin.uri:
url: "{{ base_api_url }}/assignments?owner={{ quads_username }}&is_self_schedule=true&active=true"
method: GET
headers:
Authorization: "Bearer {{ quads_token }}"
validate_certs: false
status_code: 200
register: existing_assignment_details
- name: Verify existing assignment was found
when: assignment_creation_result.status == 403
ansible.builtin.assert:
that:
- existing_assignment_details.json is defined
- existing_assignment_details.json | length > 0
fail_msg: >-
Assignment creation was forbidden (403), but no existing active assignment was found.
This may indicate a permissions issue or server misconfiguration.
Please contact your QUADS administrator.
changed_when: false
- name: Update assignment description if it already exists
when: assignment_creation_result.status == 403
ansible.builtin.uri:
url: "{{ base_api_url }}/assignments/{{ existing_assignment_details.json[0].id }}"
method: PUT
headers:
Authorization: "Bearer {{ quads_token }}"
body_format: json
body:
description: "{{ workload_name }}"
validate_certs: false
status_code: 200
- name: Set unified assignment data
ansible.builtin.set_fact:
assignment_data: "{{ assignment_creation_result.json if assignment_creation_result.status == 201 else existing_assignment_details.json[0] }}"
changed_when: false
- name: Set facts from unified assignment data
ansible.builtin.set_fact:
assignment_id: "{{ assignment_data.id }}"
assignment_cloud: "{{ assignment_data.cloud.name | default('unknown') }}"
generated_jira_ticket: "{{ assignment_data.ticket | default('None') }}"
changed_when: false
- name: Display generated Jira ticket number
when: generated_jira_ticket != 'None'
ansible.builtin.debug:
msg: "Using assignment with Jira Ticket: {{ generated_jira_ticket }}"
changed_when: false
- name: Schedule each selected host
ansible.builtin.uri:
url: "{{ base_api_url }}/schedules"
method: POST
headers:
Authorization: "Bearer {{ quads_token }}"
body_format: json
body:
cloud: "{{ assignment_cloud }}"
hostname: "{{ item.name }}"
validate_certs: false
status_code: [200, 201]
loop: "{{ hosts_to_schedule }}"
loop_control:
label: "{{ item.name }}"
register: schedule_results
- name: Set command variables for output
ansible.builtin.set_fact:
check_status_command: "curl -s https://{{ quads_api_server }}/api/v3/assignments/{{ assignment_id }} | jq '.validated'"
terminate_command: >-
{% if use_api_token | bool %}
curl -s -k -X POST -H "Authorization: Bearer {{ quads_token }}"
https://{{ quads_api_server }}/api/v3/assignments/terminate/{{ assignment_id }} | jq
{% else %}
curl -s -k -X POST -H "Authorization: Bearer $(curl -s -k -X POST -u '{{ quads_user_email }}:{{ quads_password }}'
https://{{ quads_api_server }}/api/v3/login/ | jq -r '.auth_token')"
https://{{ quads_api_server }}/api/v3/assignments/terminate/{{ assignment_id }} | jq
{% endif %}
changed_when: false
- name: Display final success message
ansible.builtin.debug:
var: final_summary
vars:
final_summary:
status: "Successfully scheduled {{ hosts_to_schedule | length }} host(s)."
check_status_command: "{{ check_status_command }}"
terminate_command: "{{ terminate_command }}"
host_schedules: >-
{%- set schedules = [] -%}
{%- for result in schedule_results.results -%}
{%- set _ = schedules.append({'host': result.item.name, 'schedule_id': result.json.id}) -%}
{%- endfor -%}
{{ schedules }}
assignment_id: "{{ assignment_id }}"
assignment_description: "{{ workload_name }}"
cloud_name: "{{ assignment_cloud }}"
changed_when: false
- name: Generate YAML file with credentials
no_log: true
ansible.builtin.copy:
dest: "./quads_credentials.yml"
content: |
# QUADS API Credentials
# This file was generated by the quads_self_schedule.yml playbook
quads_username: {{ quads_username }}
{% if use_api_token | bool %}
quads_api_token: {{ quads_api_token }}
{% else %}
quads_password: {{ quads_password }}
quads_token: {{ quads_token }}
{% endif %}
mode: "0600"
- name: Generate YAML file with scheduled hosts
ansible.builtin.copy:
dest: "./scheduled_hosts_{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}-{{ ansible_date_time.minute }}-{{ ansible_date_time.second }}.yml"
content: "{{ {'scheduled_hosts': hosts_to_schedule} | to_nice_yaml }}"
mode: "0644"
- name: Generate file with helper commands
ansible.builtin.copy:
dest: "./quads_commands_{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}-{{ ansible_date_time.minute }}-{{ ansible_date_time.second }}.txt"
content: |
# Command to check if your assignment is validated and ready to use:
{{ check_status_command }}
# Command to terminate your assignment when you are finished:
{{ terminate_command }}
mode: "0644"