-
Notifications
You must be signed in to change notification settings - Fork 0
/
lw
executable file
·777 lines (723 loc) · 25.2 KB
/
lw
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
#!/usr/bin/env python
"""
Littlewing: Simple, powerful infrastructure automation.
https://github.com/kfeldmann/littlewing
Copyright (c) 2016, Kris Feldmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import sys
import json
import os
import re
import subprocess
import time
import yaml
if sys.version_info > (3, 0):
from urllib.parse import quote, unquote
else:
from urllib import quote, unquote
AWSCLI = os.environ.get('AWSCLI', 'aws')
FILENAME = '(none)'
LINENO = '(none)'
STEPNO = '(none)'
TS = time.strftime('%Y%m%d%H%M%S', time.localtime())
REGION = None
PROFILE = None
VAR = {}
SECRETS = {}
TARGET_GROUPS = {}
MARKER = 'tilde'
LOOP_STACK = []
NULL_LOOP_DEPTH = 0
LISTING = False
TARGET = None
DEFAULT_FOUND = False
OUTDIR = '.lw-output'
def _err(message):
"""
Write error message to stderr along with FILENAME,
STEPNO, and LINENO, and then exit(1).
"""
sys.stderr.write('ERROR: file: %s, step: %s, line: %s\n' \
% (FILENAME, STEPNO, LINENO))
sys.stderr.write('ERROR: %s\n' % message)
raise SystemExit(1)
def _wrn(message):
"""
Write warning message to stderr along with FILENAME,
STEPNO, and LINENO.
"""
sys.stderr.write('WARN: file: %s, step: %s, line: %s\n' \
% (FILENAME, STEPNO, LINENO))
sys.stderr.write('WARN: %s\n' % message)
return None
def _inf(message):
"Write informational message to stdout."
sys.stdout.write('INFO: %s\n' % message)
return None
def _dbg(message):
"""
If the environment variable DEBUG has been set, write
debugging message to stdout.
"""
if os.environ.get('DEBUG', False):
sys.stdout.write('DEBUG: %s\n' % message)
return None
def usage():
"Write usage statement to stderr and exit(2)."
sys.stderr.write('Usage: lw [-l|--list|<target>]\n')
raise SystemExit(2)
def __var_asm(sec_name):
sec_response = aws_call( \
REGION,
PROFILE,
('secretsmanager', 'get-secret-value'),
('--secret-id', sec_name) \
)
ss = sec_response.get('SecretString', '')
if ss != '':
SECRETS[ss] = 1
return ss
def __varsub(in_str):
"Dereference variables and output references."
global FILENAME, LINENO
_dbg('__varsub(): starting with in_str = %s' % in_str)
words = in_str.split('.')
_dbg('__varsub(): words = %s' % repr(words))
if words[0] == 'var':
if len(words) == 2:
if words[1] in VAR:
return VAR[words[1]]
raise ValueError('Unknown variable: %s' % words[1])
if len(words) == 3:
if words[1] in VAR:
if isinstance(VAR[words[1]], dict) and words[2] in VAR[words[1]]:
return VAR[words[1]][words[2]]
if isinstance(VAR[words[1]], str):
raise ValueError('Treating a string variable as a map: %s.%s'
% (words[1], words[2]))
raise ValueError('Unknown variable: %s.%s'
% (words[1], words[2]))
raise ValueError('Unknown variable: %s.%s'
% (words[1], words[2]))
raise ValueError('Malformed variable line: %s' % in_str)
if words[0] == 'aws':
fname = '.'.join(words[:4])
elif words[0] == 'exec':
fname = '.'.join(words[:3])
elif words[0] == 'asm':
return __var_asm('.'.join(words[1:]))
else:
_err('Unknown provider: %s' % words[0])
try:
f = open('%s/%s' % (OUTDIR, fname), 'r')
FILENAME = '%s/%s' % (OUTDIR, fname)
except IOError:
_err('Unknown resource: %s' % fname)
LINENO = 0
while True:
line = f.readline()
LINENO += 1
if line == '':
break
line = line.strip()
try:
n, v = line.split(':', 1)
except ValueError:
f.close()
_err('Malformed line in output file (%s): %s'
% (fname, line))
if n == in_str:
f.close()
return unquote(v)
f.close()
_err('Unknown resource attribute: %s' % in_str)
def varsub(val):
"""
Recursively (to a limit) find variables in the input string
and call __varsub() to dereference them.
"""
_dbg('varsub(): starting with val = %s' % val)
if isinstance(val, None.__class__):
return val
if isinstance(val, int):
return str(val)
i = 0
while i < 100:
if MARKER == 'dollar':
s = re.search(r'\$\{([^${}]+)\}', val)
else:
s = re.search(r'\~\{([^~{}]+)\}', val)
try:
s.group(1)
except (IndexError, AttributeError):
break
_dbg('varsub(): s.group(0) = %s' % s.group(0))
_dbg('varsub(): s.group(1) = %s' % s.group(1))
needle = s.group(0).replace('$', r'\$')
val = re.sub(needle, __varsub(s.group(1)), val)
i += 1
if MARKER == 'dollar':
# Un-escape $\\{ --> ${, and $\\\{ --> $\{
val = val.replace(r'$\\{', r'${')
val = val.replace(r'$\\\{', r'$\{')
return val
def aws_call(region, profile, cmdtuple, argtuple):
"Spawn aws-cli subprocess to execute commands."
if (not region) or (not profile):
_err('Must set region and profile before calling aws.')
args = [
AWSCLI,
'--region', region,
'--profile', profile
]
args.extend(cmdtuple)
if argtuple:
args.extend(argtuple)
try:
outdata = subprocess.check_output(args)
except (OSError, subprocess.CalledProcessError) as ex:
_err('Failed to run %s %s %s: %s\n' \
% (AWSCLI, cmdtuple[0], cmdtuple[1], ex) \
+ 'ERROR: Args: %s' % repr(args))
if outdata: # Some calls do not return data
if cmdtuple[0] == 's3':
# Output is text, not JSON
return {'Output': outdata}
try:
outdict = json.loads(outdata)
except json.JSONDecodeError as ex:
_err( \
"""Failed to parse json response from %s %s %s.
Exception is: %s
JSON source:
%s
""" % (AWSCLI, cmdtuple[0], cmdtuple[1], ex, outdata))
outdict['Output'] = outdata
else:
outdict = None
return outdict
def exec_call(cmd, argtuple):
"Spawn subprocess to execute <cmd>."
args = [cmd]
if argtuple:
args.extend(argtuple)
try:
outdata = subprocess.check_output(args)
except (OSError, subprocess.CalledProcessError) as ex:
_err('Failed to run %s: %s' % (cmd, ex))
return {'Output': outdata}
def redact(s):
"""
Look for secret values in s and redact them.
"""
for sec in SECRETS.keys():
s = s.replace(sec, 'redacted')
return s
def stringify(path, name, obj):
"""
Recursively convert heirarchical object into a list of strings,
each using a dotted notation to represent the branch to each
attribute and its value.
"""
strings = []
if obj is None:
return strings
if isinstance(obj, dict):
for k in obj:
strings.extend(stringify('%s.%s' % (path, name), k, obj[k]))
elif isinstance(obj, list):
i = 0
for item in obj:
strings.extend(stringify('%s.%s' % (path, name), i, item))
i += 1
this = '%s.%s.Count:%d' % (path, name, len(obj))
strings.append(this.lstrip('.'))
elif isinstance(obj, bytes):
this = '%s.%s:%s' % (path, name, quote(redact(obj.decode('utf-8'))))
strings.append(this.lstrip('.'))
else:
this = '%s.%s:%s' % (path, name, quote(redact(str(obj))))
strings.append(this.lstrip('.'))
return strings
def store_output(name, outdict):
"Stringify and write out the output data from a step."
try:
f = open('%s/%s' % (OUTDIR, name), 'w')
except IOError:
_err('Failed to open output file: %s' % name)
for line in stringify('', name, outdict):
f.write('%s\n' % line)
f.close()
return None
def clear_all_output():
"Move all output aside, effectively clearing it."
global TS
if not os.path.exists('%s-cleared-%s' % (OUTDIR, TS)):
os.mkdir('%s-cleared-%s' % (OUTDIR, TS))
for f in os.listdir(OUTDIR):
os.rename( \
'%s/%s' % (OUTDIR, f),
'%s-cleared-%s/%s' % (OUTDIR, TS, f))
return None
def clear_one_output(path):
"Move one output file aside, effectively clearing it."
global TS
if not os.path.exists('%s/%s' \
% (OUTDIR, path)):
_err("Output not found: %s. Was it already cleared?" % path)
else:
if not os.path.exists('%s-cleared-%s' % (OUTDIR, TS)):
os.mkdir('%s-cleared-%s' % (OUTDIR, TS))
os.rename( \
'%s/%s' % (OUTDIR, path),
'%s-cleared-%s/%s' % (OUTDIR, TS, path))
return None
def varsub_tuple(intuple):
"Substitute variables in each element of a tuple."
if intuple is None:
return None
outtuple = []
for item in intuple:
try:
outtuple.append(varsub(item))
except ValueError as ex:
_err(str(ex))
return outtuple
def set_region(value, tries=1, trylimit=1):
"""
Set the global 'REGION` and VAR['REGION'] variables
using variable substitution.
"""
global REGION
try:
REGION = varsub(value)
VAR['REGION'] = REGION
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
return True
def set_profile(value, tries=1, trylimit=1):
"""
Set the global 'PROFILE` and VAR['PROFILE'] variables
using variable substitution.
"""
global PROFILE
try:
PROFILE = varsub(value)
VAR['PROFILE'] = PROFILE
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
return True
def start_loop(this_stepno, value, tries=1, trylimit=1):
"""
Push the start and count of this loop onto the LOOP_STACK.
Use variable substitution for the length.
The values in LOOP_STACK[] have the following format:
[starting_stepno, loop_count, loop_index]
The loop_index value is incremented during the loop
execution until it is equal to loop_count.
"""
try:
count = varsub(value)
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
else:
try:
count = int(count)
except ValueError as ex:
_err(str(ex))
else:
_dbg('Pushing loop onto the stack: [%d, %d, 0]' \
% (this_stepno, count))
LOOP_STACK.append([this_stepno, count, 0])
set_loop_index_var()
return True
def check_null_loop():
"""
Are we inside a loop that is already at it's limit? For example,
a zero-length loop which can be used as a poor-man's boolean.
"""
if LOOP_STACK:
if LOOP_STACK[-1][2] >= LOOP_STACK[-1][1]:
_dbg('check_null_loop() returning True')
return True
else:
_dbg('check_null_loop() returning False')
return False
return None # only for pylint
def add_null_loop():
"""
Add a "null loop" to the stack (actually just a counter).
"""
global NULL_LOOP_DEPTH
NULL_LOOP_DEPTH += 1
_dbg('Added a null loop')
return None
def end_null_loop():
"""
Remove a "null loop" from the stack (actually just a counter).
"""
global NULL_LOOP_DEPTH
if NULL_LOOP_DEPTH <= 0:
return False
NULL_LOOP_DEPTH -= 1
_dbg('Subtracted a null loop')
return True
def increment_loop_index():
"""
Increment the loop_index value.
Return True if the loop should continue, and False if it has reached
the end (index == count).
"""
LOOP_STACK[-1][2] += 1
_dbg('Loop status: %d, %d, %d' \
% (LOOP_STACK[-1][0], LOOP_STACK[-1][1], LOOP_STACK[-1][2]))
if LOOP_STACK[-1][2] >= LOOP_STACK[-1][1]:
_dbg('Loop done. Popping from LOOP_STACK.')
LOOP_STACK.pop()
set_loop_index_var()
return False
_dbg('Loop continuing.')
set_loop_index_var()
return True
def set_loop_index_var():
"""
Update the LOOP_INDEX* variables, which indicate how many times
each loop has iterated so far.
"""
if LOOP_STACK:
VAR['LOOP_INDEX'] = str(LOOP_STACK[-1][2])
_dbg('Setting LOOP_INDEX to %s' % str(LOOP_STACK[-1][2]))
if len(LOOP_STACK) > 1:
j = 1
for i in range(len(LOOP_STACK)-2, -1, -1):
VAR['LOOP_INDEX_%d' % j] = str(LOOP_STACK[i][2])
_dbg('i=%d, Setting LOOP_INDEX_%d to %s' \
% (i, j, str(LOOP_STACK[i][2])))
j += 1
else:
VAR['LOOP_INDEX'] = "0"
return None
def set_var(name, value, tries=1, trylimit=1):
"Set global 'VAR[name]' using variable substitution."
if isinstance(value, str):
try:
VAR[name] = varsub(value)
_dbg('Set string VAR[%s] = "%s"' % (name, VAR[name]))
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
elif isinstance(value, int):
VAR[name] = str(value)
_dbg('Set int VAR[%s] = "%s"' % (name, VAR[name]))
elif isinstance(value, dict):
VAR[name] = value
_dbg('Set dict VAR[%s] = "%s"' % (name, repr(VAR[name])))
else:
_err('Unknown variable type for var.%s' % name)
return True
def set_default_target(value, tries=1, trylimit=1):
"""
Set global 'TARGET' (once) using variable substitution.
"""
global TARGET
global DEFAULT_FOUND
if not TARGET:
if isinstance(value, str):
try:
TARGET = varsub(value)
if LISTING:
DEFAULT_FOUND = True
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
else:
_wrn('Default target must be a string.')
return True
return None # only for pylint
def set_target_groups(tgdict, tries=1, trylimit=1):
"Set global 'TARGET_GROUPS' using variable substitution."
if not isinstance(tgdict, dict):
_wrn("'target-groups' must be a dict.")
return True
for tgname in tgdict:
if not isinstance(tgdict[tgname], list):
_wrn("'target-groups: %s' must be a list." % tgname)
return True
try:
tgn = varsub(tgname)
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
else:
try:
TARGET_GROUPS[tgn] = varsub_tuple(tgdict[tgname])
except ValueError as ex:
if tries >= trylimit:
_err(str(ex))
else:
return False
return True
### main ###############################################################
if len(sys.argv) > 2 \
or '-?' in sys.argv \
or '-h' in sys.argv \
or '--help' in sys.argv:
usage()
if len(sys.argv) == 2:
if sys.argv[1] in ('-l', '--list'):
LISTING = True
else:
TARGET = sys.argv[1]
# Legacy support
if os.path.exists('.terraflop-output'):
OUTDIR = '.terraflop-output'
if not os.path.exists(OUTDIR):
os.mkdir(OUTDIR)
ALL_FILES = os.listdir('.')
INPUT_FILES = []
for F in ALL_FILES:
if F[-4:] == '.yml':
INPUT_FILES.append(F)
INPUT_FILES.sort()
VAR['USER'] = os.environ.get('USER', 'littlewing')
VAR['LOOP_INDEX'] = "0"
VAR['LOOP_INDEX_1'] = "0"
VAR['LOOP_INDEX_2'] = "0"
VAR['LOOP_INDEX_3'] = "0"
VAR['LOOP_INDEX_4'] = "0"
VAR['LOOP_INDEX_5'] = "0"
VAR['LOOP_INDEX_6'] = "0"
VAR['LOOP_INDEX_7'] = "0"
VAR['LOOP_INDEX_8'] = "0"
VAR['LOOP_INDEX_9'] = "0"
for in_file in INPUT_FILES:
F = open(in_file, 'r')
FILENAME = in_file
LINENO = '(yaml)'
yd = yaml.load(F, Loader=yaml.Loader)
F.close()
# Attempt to auto-discover the variable MARKER ('$' or '~')
F = open(in_file, 'r')
data = F.read()
F.close()
dollar = data.count('${')
tilde = data.count('~{')
if dollar > 0 and tilde == 0:
MARKER = 'dollar'
_dbg('Setting variable MARKER to dollar ${}')
elif dollar > 0 and tilde > 0:
_wrn('Found both ${dollar} and ~{tilde} variable markers!')
# Have to make sure we load all the vars, target-groups,
# default-target, and set region/profile before
# running the steps.
if LISTING:
_inf('File: %s' % FILENAME)
# Try up to 'maxtries' passes to resolve variable dependencies
z = 0
maxtries = 10
vardep_keep_going = False
while True:
z += 1
for K in yd:
LINENO = '(%s...)' % str(K)[:10]
if K == 'region':
if not set_region(yd[K], z, maxtries):
vardep_keep_going = True
else:
_dbg('region is set to %s' % REGION)
elif K == 'profile':
if not set_profile(yd[K], z, maxtries):
vardep_keep_going = True
else:
_dbg('profile is set to %s' % PROFILE)
elif K[:4] == 'var.':
if not set_var(K[4:], yd[K], z, maxtries):
vardep_keep_going = True
else:
_dbg('VAR[%s] is set to %s' % (K[4:], VAR[K[4:]]))
elif K == 'default-target':
if not set_default_target(yd[K], z, maxtries):
vardep_keep_going = True
else:
_dbg('default-target is set to %s' % TARGET)
elif K == 'target-groups':
if not set_target_groups(yd[K], z, maxtries):
vardep_keep_going = True
if (z >= maxtries) or (not vardep_keep_going):
break
# List targets
if LISTING:
if DEFAULT_FOUND:
_inf('Default target: %s' % TARGET)
else:
_inf('Default target: (all steps)')
for TGNAME in TARGET_GROUPS:
_inf('[%s]: %s' \
% (TGNAME, ', '.join(TARGET_GROUPS[TGNAME])))
for K in yd:
if K[:5] == 'steps':
try:
tgt = varsub(K[6:])
except ValueError as ex:
_err(str(ex))
if tgt:
_inf(tgt)
else:
if DEFAULT_FOUND:
_inf('(targetless - not reachable since ' \
+ 'default target has been set)')
else:
_inf('(targetless)')
continue
# Make the targets in a target-group run in order
if TARGET and TARGET in TARGET_GROUPS:
goals = TARGET_GROUPS[TARGET]
elif TARGET:
goals = [TARGET]
else:
goals = [None]
for goal in goals:
for K in yd:
if K[:5] == 'steps':
try:
tgt = varsub(K[6:])
except ValueError as ex:
_err(str(ex))
if goal and tgt != goal:
_dbg('Skipping %s (target: %s, goal: %s)' \
% (tgt, TARGET, goal))
continue
_dbg('Examining step list %s' % K)
STEPNO = 0
while STEPNO < len(yd[K]):
STEPNO += 1
step = yd[K][STEPNO - 1] # STEPNO is 1-based for printing
# We're grabbing the first key in the dictionary.
# This works only because there is always only one key.
step_key = '(none)'
for step_key in step:
break
LINENO = '(%s)' % step_key
try:
rsrc_pathname = varsub(step_key)
except ValueError as ex:
_err(str(ex))
if rsrc_pathname == 'end-loop':
if not LOOP_STACK:
_err('Found "end-loop" outside of any loop.')
if end_null_loop():
continue
if increment_loop_index():
STEPNO = LOOP_STACK[-1][0]
continue
if rsrc_pathname == 'loop':
if check_null_loop():
add_null_loop()
continue
start_loop(STEPNO, step[step_key])
continue
if check_null_loop():
_dbg('Inside a null loop. Skipping to the end.')
continue # If we're inside a null loop, skip to the end-loop
if rsrc_pathname == 'print':
if isinstance(step[step_key], str):
try:
sys.stdout.write('%s\n' % \
varsub(step[step_key]))
except ValueError as ex:
_err(str(ex))
else:
_wrn('%s %s' \
% ('Print statements can only use string',
'arguments (with or without variables).'))
continue
if rsrc_pathname == 'clear-all-output':
if step[step_key]:
_inf('Running %s' % rsrc_pathname)
clear_all_output()
continue
if rsrc_pathname == 'clear-one-output':
if step[step_key]:
_inf('Running %s' % rsrc_pathname)
clear_one_output(varsub(step[step_key]))
continue
if rsrc_pathname == 'region':
set_region(step[step_key])
continue
if rsrc_pathname == 'profile':
set_profile(step[step_key])
continue
if rsrc_pathname[:4] == 'var.':
ky = rsrc_pathname[4:]
rawval = step[step_key]
set_var(ky, rawval)
continue
if os.path.exists('%s/%s' \
% (OUTDIR, rsrc_pathname)):
_dbg('%s has already been run.' % rsrc_pathname)
continue
if rsrc_pathname[0] == '+':
rsrc_pathname = rsrc_pathname[1:]
WORDS = rsrc_pathname.split('.')
if WORDS[0] == 'aws':
CMDTUPLE = (WORDS[1], WORDS[2])
argtupleraw = step[step_key]
_inf('Running %s' % rsrc_pathname)
OUTDICT = aws_call(
REGION, PROFILE, CMDTUPLE,
varsub_tuple(argtupleraw))
store_output(rsrc_pathname, OUTDICT)
elif WORDS[0] == 'exec':
CMD = WORDS[1]
argtupleraw = step[step_key]
_inf('Running %s' % rsrc_pathname)
OUTDICT = exec_call(
CMD, varsub_tuple(argtupleraw))
store_output(rsrc_pathname, OUTDICT)
elif WORDS[0] == 'ssh':
argtupleraw = step[step_key]
_inf('Running %s' % rsrc_pathname)
ARGS = ['ssh']
ARGS.extend(varsub_tuple(argtupleraw))
response = subprocess.call(ARGS)
else:
_err('Unrecognized provider: %s' % WORDS[0])