0
# Output Formatting
1
2
Flexible output formatting system supporting multiple formats (JSON, table, text, YAML) with customizable formatters and styling options. The formatting system transforms AWS service responses into user-friendly output formats.
3
4
## Capabilities
5
6
### Formatter Selection
7
8
Core function for selecting appropriate output formatter based on format and options.
9
10
```python { .api }
11
def get_formatter(output_format, args):
12
"""
13
Get appropriate formatter for specified output format.
14
15
Parameters:
16
output_format: str, output format ('json', 'table', 'text', 'yaml')
17
args: parsed arguments with formatting options
18
19
Returns:
20
Formatter instance for the specified format
21
"""
22
23
def is_response_paginated(response) -> bool:
24
"""
25
Check if response contains paginated results.
26
27
Parameters:
28
response: AWS service response
29
30
Returns:
31
bool: True if response is paginated
32
"""
33
```
34
35
### Base Formatter
36
37
Foundation class for all output formatters with common functionality.
38
39
```python { .api }
40
class Formatter:
41
"""
42
Base formatter class for all output formats.
43
Provides common functionality for formatting AWS service responses.
44
"""
45
46
def __init__(self, args):
47
"""
48
Initialize formatter with command arguments.
49
50
Parameters:
51
args: parsed command arguments containing formatting options
52
"""
53
54
def __call__(self, data):
55
"""
56
Format data for output. Must be implemented by subclasses.
57
58
Parameters:
59
data: structured data from AWS service response
60
"""
61
62
def _remove_request_id(self, data):
63
"""
64
Remove request ID from response for cleaner output.
65
66
Parameters:
67
data: response data that may contain request ID
68
69
Returns:
70
data with request ID removed
71
"""
72
73
def _get_default_stream(self):
74
"""
75
Get default output stream (stdout).
76
77
Returns:
78
file-like object for output
79
"""
80
81
def _flush_stream(self, stream=None):
82
"""
83
Flush output stream.
84
85
Parameters:
86
stream: optional stream to flush, defaults to stdout
87
"""
88
```
89
90
### Table Formatting
91
92
Specialized formatters for tabular output with styling and customization options.
93
94
```python { .api }
95
class TableFormatter(Formatter):
96
"""
97
Formatter for table output format.
98
Converts structured data into formatted tables.
99
"""
100
101
def __init__(self, args):
102
"""
103
Initialize table formatter.
104
105
Parameters:
106
args: parsed command arguments with table-specific options
107
"""
108
109
def __call__(self, data):
110
"""
111
Format data as table output.
112
113
Parameters:
114
data: structured data to format as table
115
"""
116
117
class MultiTable:
118
"""
119
Formatter for multiple related tables.
120
Handles complex data structures with nested tables.
121
"""
122
123
def __init__(self, initial_section=True, subsequent_section=False):
124
"""
125
Initialize multi-table formatter.
126
127
Parameters:
128
initial_section: bool, whether this is the initial table section
129
subsequent_section: bool, whether this is a subsequent section
130
"""
131
132
def add_row_header(self, header):
133
"""
134
Add row header to the table.
135
136
Parameters:
137
header: str, header text for the row
138
"""
139
140
def add_rows(self, rows):
141
"""
142
Add multiple rows to the table.
143
144
Parameters:
145
rows: list of row data
146
"""
147
148
class Styler:
149
"""
150
Interface for table styling.
151
Defines how table elements are styled and colored.
152
"""
153
154
def style_header(self, header):
155
"""
156
Style table header.
157
158
Parameters:
159
header: str, header text to style
160
161
Returns:
162
str: styled header text
163
"""
164
165
def style_row(self, row, row_index):
166
"""
167
Style table row.
168
169
Parameters:
170
row: row data to style
171
row_index: int, index of the row
172
173
Returns:
174
styled row data
175
"""
176
177
class ColorizedStyler(Styler):
178
"""
179
Colorized table styling implementation.
180
Adds colors and visual enhancements to table output.
181
"""
182
183
def __init__(self):
184
"""Initialize colorized styler with ANSI color codes."""
185
186
def style_header(self, header):
187
"""
188
Style table header with colors.
189
190
Parameters:
191
header: str, header text to style
192
193
Returns:
194
str: colorized header text
195
"""
196
197
def style_row(self, row, row_index):
198
"""
199
Style table row with conditional colors.
200
201
Parameters:
202
row: row data to style
203
row_index: int, index of the row
204
205
Returns:
206
styled row data with appropriate colors
207
"""
208
```
209
210
### Format-Specific Formatters
211
212
Specialized formatters for different output formats.
213
214
```python { .api }
215
class JSONFormatter(Formatter):
216
"""
217
Formatter for JSON output format.
218
Converts structured data into JSON format with proper indentation and encoding.
219
"""
220
221
def __init__(self, args):
222
"""
223
Initialize JSON formatter.
224
225
Parameters:
226
args: parsed command arguments with JSON-specific options
227
"""
228
229
def __call__(self, data):
230
"""
231
Format data as JSON output.
232
233
Parameters:
234
data: structured data to format as JSON
235
"""
236
237
def _encode_json(self, data):
238
"""
239
Encode data as JSON with proper formatting.
240
241
Parameters:
242
data: data to encode
243
244
Returns:
245
str: JSON-encoded string
246
"""
247
248
class TextFormatter(Formatter):
249
"""
250
Formatter for text output format.
251
Converts structured data into tab-separated text format for scripting.
252
"""
253
254
def __init__(self, args):
255
"""
256
Initialize text formatter.
257
258
Parameters:
259
args: parsed command arguments with text-specific options
260
"""
261
262
def __call__(self, data):
263
"""
264
Format data as text output.
265
266
Parameters:
267
data: structured data to format as text
268
"""
269
270
def _flatten_data(self, data, prefix=""):
271
"""
272
Flatten nested data structure for text output.
273
274
Parameters:
275
data: nested data structure
276
prefix: str, prefix for flattened keys
277
278
Returns:
279
generator: flattened key-value pairs
280
"""
281
282
class YAMLFormatter(Formatter):
283
"""
284
Formatter for YAML output format.
285
Converts structured data into YAML format with proper indentation.
286
"""
287
288
def __init__(self, args):
289
"""
290
Initialize YAML formatter.
291
292
Parameters:
293
args: parsed command arguments with YAML-specific options
294
"""
295
296
def __call__(self, data):
297
"""
298
Format data as YAML output.
299
300
Parameters:
301
data: structured data to format as YAML
302
"""
303
304
def _encode_yaml(self, data):
305
"""
306
Encode data as YAML with proper formatting.
307
308
Parameters:
309
data: data to encode
310
311
Returns:
312
str: YAML-encoded string
313
"""
314
```
315
316
**Usage Examples:**
317
318
```python
319
from awscli.formatter import get_formatter, JSONFormatter, TextFormatter, YAMLFormatter
320
321
# Sample data for formatting examples
322
data = {
323
'Instances': [
324
{'InstanceId': 'i-1234567890abcdef0', 'State': {'Name': 'running'}},
325
{'InstanceId': 'i-0987654321fedcba0', 'State': {'Name': 'stopped'}}
326
]
327
}
328
329
# Table formatter
330
table_formatter = get_formatter('table', args)
331
table_formatter(data)
332
# Output:
333
# --------------------- ---------
334
# | InstanceId | State |
335
# --------------------- ---------
336
# | i-1234567890abc...| running|
337
# | i-0987654321fed...| stopped|
338
# --------------------- ---------
339
340
# JSON formatter
341
json_formatter = get_formatter('json', args)
342
json_formatter(data)
343
# Output: JSON with proper indentation
344
345
# Text formatter
346
text_formatter = get_formatter('text', args)
347
text_formatter(data)
348
# Output:
349
# INSTANCES i-1234567890abcdef0 running
350
# INSTANCES i-0987654321fedcba0 stopped
351
352
# YAML formatter
353
yaml_formatter = get_formatter('yaml', args)
354
yaml_formatter(data)
355
# Output: YAML formatted structure
356
357
# Direct formatter instantiation
358
json_formatter = JSONFormatter(args)
359
json_formatter(data)
360
361
text_formatter = TextFormatter(args)
362
text_formatter(data)
363
364
yaml_formatter = YAMLFormatter(args)
365
yaml_formatter(data)
366
```
367
368
## Output Format Support
369
370
### JSON Format
371
372
Default format providing complete structured output:
373
374
```python
375
# JSON output (default)
376
{
377
"Instances": [
378
{
379
"InstanceId": "i-1234567890abcdef0",
380
"State": {
381
"Name": "running",
382
"Code": 16
383
},
384
"InstanceType": "t2.micro"
385
}
386
]
387
}
388
```
389
390
### Table Format
391
392
Human-readable tabular format:
393
394
```python
395
# Table output
396
-----------------------------------------
397
| InstanceId |
398
-----------------------------------------
399
| i-1234567890abcdef0 |
400
| i-0987654321fedcba0 |
401
-----------------------------------------
402
```
403
404
### Text Format
405
406
Plain text format for scripting:
407
408
```python
409
# Text output
410
INSTANCES i-1234567890abcdef0 running
411
INSTANCES i-0987654321fedcba0 stopped
412
```
413
414
### YAML Format
415
416
YAML structured output:
417
418
```yaml
419
# YAML output
420
Instances:
421
- InstanceId: i-1234567890abcdef0
422
State:
423
Name: running
424
Code: 16
425
- InstanceId: i-0987654321fedcba0
426
State:
427
Name: stopped
428
Code: 80
429
```
430
431
## Advanced Formatting Features
432
433
### Custom Formatter Development
434
435
```python
436
from awscli.formatter import Formatter
437
438
class CustomFormatter(Formatter):
439
"""Custom formatter for specialized output."""
440
441
def __init__(self, args):
442
super().__init__(args)
443
self.custom_options = self._parse_custom_options(args)
444
445
def __call__(self, data):
446
"""Format data with custom logic."""
447
formatted_data = self._transform_data(data)
448
self._output_formatted_data(formatted_data)
449
450
def _transform_data(self, data):
451
"""Apply custom transformations to data."""
452
# Custom transformation logic
453
return data
454
455
def _output_formatted_data(self, data):
456
"""Output formatted data to stream."""
457
import json
458
print(json.dumps(data, indent=2))
459
```
460
461
### Query and Filtering Integration
462
463
```python
464
# JMESPath query integration
465
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name]' --output table
466
467
# Results in filtered table output:
468
----------------------- ---------
469
| i-1234567890abc... | running |
470
| i-0987654321fed... | stopped |
471
----------------------- ---------
472
```
473
474
### Pagination Handling
475
476
```python
477
def handle_paginated_response(response, formatter):
478
"""Handle paginated responses with appropriate formatting."""
479
480
if is_response_paginated(response):
481
# Stream paginated results
482
for page in response:
483
formatter(page)
484
else:
485
# Format single response
486
formatter(response)
487
```
488
489
### Color and Styling
490
491
```python
492
class CustomColorizedStyler(ColorizedStyler):
493
"""Custom colorized styling for tables."""
494
495
def style_header(self, header):
496
"""Style table header with custom colors."""
497
return f"\033[1;36m{header}\033[0m" # Cyan bold
498
499
def style_row(self, row, row_index):
500
"""Style table row based on content."""
501
if 'running' in str(row):
502
return f"\033[0;32m{row}\033[0m" # Green
503
elif 'stopped' in str(row):
504
return f"\033[0;31m{row}\033[0m" # Red
505
return str(row)
506
```
507
508
## Output Format Configuration
509
510
### Global Format Settings
511
512
```python
513
# Set default output format
514
aws configure set output json
515
aws configure set output table
516
aws configure set output text
517
aws configure set output yaml
518
519
# Per-profile format settings
520
aws configure set output table --profile development
521
aws configure set output json --profile production
522
```
523
524
### Command-Specific Formatting
525
526
```python
527
# Override format for specific command
528
aws ec2 describe-instances --output table
529
aws s3 ls --output text
530
aws iam list-users --output yaml
531
```
532
533
### Programmatic Format Control
534
535
```python
536
from awscli.clidriver import create_clidriver
537
538
# Create driver with specific output format
539
driver = create_clidriver()
540
exit_code = driver.main([
541
'ec2', 'describe-instances',
542
'--output', 'table',
543
'--query', 'Reservations[*].Instances[*].[InstanceId,State.Name]'
544
])
545
```
546
547
## Integration with Custom Commands
548
549
```python
550
from awscli.customizations.commands import BasicCommand
551
from awscli.formatter import get_formatter
552
553
class CustomOutputCommand(BasicCommand):
554
NAME = 'custom-output'
555
DESCRIPTION = 'Command demonstrating custom output formatting'
556
557
def _run_main(self, parsed_args, parsed_globals):
558
# Generate data
559
data = self._collect_data()
560
561
# Get formatter based on global output setting
562
output_format = parsed_globals.get('output', 'json')
563
formatter = get_formatter(output_format, parsed_args)
564
565
# Format and output data
566
formatter(data)
567
return 0
568
569
def _collect_data(self):
570
"""Collect data for output."""
571
return {
572
'CustomData': [
573
{'Name': 'Item1', 'Value': 'Value1'},
574
{'Name': 'Item2', 'Value': 'Value2'}
575
],
576
'Metadata': {
577
'Total': 2,
578
'Generated': '2024-01-01T00:00:00Z'
579
}
580
}
581
```