0
# Argument Processing
1
2
Advanced argument parsing, validation, and transformation system that handles complex AWS parameter structures, shorthand syntax, file-based parameter input, and type conversion. The argument processing system bridges CLI input to AWS service parameters.
3
4
## Capabilities
5
6
### Base Argument Interface
7
8
The foundational interface for all CLI arguments, providing the contract for argument registration, parsing, and parameter generation.
9
10
```python { .api }
11
class BaseCLIArgument:
12
def __init__(self, name):
13
"""
14
Initialize base CLI argument.
15
16
Parameters:
17
name: str, argument name
18
"""
19
20
@property
21
def name(self) -> str:
22
"""Argument name."""
23
24
@property
25
def cli_name(self) -> str:
26
"""CLI argument name (e.g., '--instance-ids')."""
27
28
@property
29
def cli_type_name(self) -> str:
30
"""CLI type name for help documentation."""
31
32
@property
33
def required(self) -> bool:
34
"""Whether argument is required."""
35
36
@property
37
def documentation(self) -> str:
38
"""Argument documentation for help."""
39
40
@property
41
def cli_type(self) -> type:
42
"""Python type for argument value."""
43
44
@property
45
def py_name(self) -> str:
46
"""Python parameter name for AWS API."""
47
48
@property
49
def choices(self) -> list:
50
"""Valid choices for argument value."""
51
52
@property
53
def synopsis(self) -> str:
54
"""Argument synopsis for help."""
55
56
@property
57
def positional_arg(self) -> bool:
58
"""Whether argument is positional."""
59
60
@property
61
def nargs(self):
62
"""Number of arguments consumed."""
63
64
@property
65
def group_name(self) -> str:
66
"""Argument group name for help organization."""
67
68
def add_to_arg_table(self):
69
"""Add argument to command's argument table."""
70
71
def add_to_parser(self):
72
"""Add argument to argument parser."""
73
74
def add_to_params(self):
75
"""Add processed argument to parameter dictionary."""
76
```
77
78
### Custom Argument Implementation
79
80
Configurable CLI argument for custom commands with extensive customization options.
81
82
```python { .api }
83
class CustomArgument(BaseCLIArgument):
84
def __init__(self, name, help_text='', dest=None, default=None,
85
action=None, required=None, choices=None, nargs=None,
86
cli_type_name=None, group_name=None, positional_arg=False,
87
no_paramfile=False, argument_model=None, synopsis='', const=None):
88
"""
89
Initialize custom CLI argument with full configuration options.
90
91
Parameters:
92
name: str, argument name
93
help_text: str, help text for argument
94
dest: str, destination variable name
95
default: any, default value
96
action: str, argparse action ('store', 'store_true', etc.)
97
required: bool, whether argument is required
98
choices: list, valid choices for argument
99
nargs: str|int, number of arguments ('?', '*', '+', or integer)
100
cli_type_name: str, type name for help display
101
group_name: str, argument group for help organization
102
positional_arg: bool, whether argument is positional
103
no_paramfile: bool, exclude from parameter file processing
104
argument_model: argument model for advanced configuration
105
synopsis: str, synopsis for help
106
const: any, constant value for certain actions
107
"""
108
```
109
110
**Usage Example:**
111
```python
112
from awscli.arguments import CustomArgument
113
114
# Create custom arguments for a command
115
args = [
116
CustomArgument(
117
'instance-id',
118
help_text='EC2 instance ID to operate on',
119
required=True,
120
cli_type_name='string'
121
),
122
CustomArgument(
123
'dry-run',
124
help_text='Perform a dry run without making changes',
125
action='store_true',
126
default=False
127
),
128
CustomArgument(
129
'tags',
130
help_text='Instance tags in key=value format',
131
nargs='*',
132
cli_type_name='list'
133
)
134
]
135
```
136
137
### Service Argument Implementation
138
139
CLI argument mapped from AWS service parameters with automatic type conversion and validation.
140
141
```python { .api }
142
class CLIArgument(BaseCLIArgument):
143
TYPE_MAP: dict # Class attribute mapping AWS types to Python types
144
145
def __init__(self, name, argument_model, operation_model, event_emitter,
146
is_required=False, serialized_name=None):
147
"""
148
Initialize CLI argument from AWS service parameter.
149
150
Parameters:
151
name: str, argument name
152
argument_model: botocore argument model
153
operation_model: botocore operation model
154
event_emitter: botocore event emitter
155
is_required: bool, whether argument is required
156
serialized_name: str, AWS API parameter name
157
"""
158
```
159
160
### Specialized Argument Types
161
162
Specific argument implementations for common AWS parameter patterns.
163
164
```python { .api }
165
class ListArgument(CLIArgument):
166
"""
167
CLI argument for list-type parameters.
168
Handles comma-separated values and JSON arrays.
169
"""
170
171
class BooleanArgument(CLIArgument):
172
"""
173
CLI argument for boolean parameters.
174
Handles --flag and --no-flag patterns.
175
"""
176
```
177
178
### Argument Processing Functions
179
180
Core functions for processing and transforming CLI arguments into AWS service parameters.
181
182
```python { .api }
183
def unpack_argument(session, service_name, operation_name, cli_argument, value):
184
"""
185
Unpack CLI argument value to AWS service parameter format.
186
187
Parameters:
188
session: botocore.session.Session, AWS session
189
service_name: str, AWS service name
190
operation_name: str, operation name
191
cli_argument: CLI argument instance
192
value: argument value from command line
193
194
Returns:
195
Processed parameter value
196
"""
197
198
def unpack_cli_arg(cli_argument, value):
199
"""
200
Unpack CLI argument value based on argument type.
201
202
Parameters:
203
cli_argument: CLI argument instance
204
value: raw argument value
205
206
Returns:
207
Processed argument value
208
"""
209
210
def create_argument_model_from_schema(schema):
211
"""
212
Create argument model from JSON schema.
213
214
Parameters:
215
schema: dict, JSON schema definition
216
217
Returns:
218
Argument model instance
219
"""
220
```
221
222
**Usage Example:**
223
```python
224
from awscli.argprocess import unpack_argument
225
import botocore.session
226
227
# Process CLI argument for AWS API
228
session = botocore.session.Session()
229
processed_value = unpack_argument(
230
session=session,
231
service_name='ec2',
232
operation_name='describe-instances',
233
cli_argument=instance_ids_arg,
234
value=['i-1234567890abcdef0', 'i-0987654321fedcba0']
235
)
236
```
237
238
## Argument Processing Exceptions
239
240
Specialized exceptions for argument processing errors.
241
242
```python { .api }
243
class UnknownArgumentError(Exception):
244
"""Raised when an unknown argument is encountered."""
245
246
class ParamError(Exception):
247
"""Base exception for parameter processing errors."""
248
249
class ParamSyntaxError(Exception):
250
"""Raised when parameter syntax is invalid."""
251
252
class ParamUnknownKeyError(Exception):
253
"""Raised when an unknown parameter key is encountered."""
254
```
255
256
## Advanced Argument Processing
257
258
### Shorthand Syntax Processing
259
260
AWS CLI supports shorthand syntax for complex parameters:
261
262
```bash
263
# Shorthand for complex structures
264
aws ec2 run-instances --block-device-mappings DeviceName=/dev/sda1,Ebs='{VolumeSize=20}'
265
266
# Equivalent to JSON
267
aws ec2 run-instances --block-device-mappings '[{"DeviceName":"/dev/sda1","Ebs":{"VolumeSize":20}}]'
268
```
269
270
### Parameter File Support
271
272
Arguments can be loaded from files using the `file://` prefix:
273
274
```python
275
# Command line usage
276
aws ec2 run-instances --cli-input-json file://instance-config.json
277
278
# Programmatic equivalent
279
with open('instance-config.json') as f:
280
config = json.load(f)
281
# Process config through argument system
282
```
283
284
### Type Conversion and Validation
285
286
The argument system handles automatic type conversion:
287
288
```python
289
# String to appropriate AWS type conversion
290
TYPE_CONVERSIONS = {
291
'string': str,
292
'integer': int,
293
'long': int,
294
'boolean': bool,
295
'double': float,
296
'float': float,
297
'blob': bytes,
298
'timestamp': datetime,
299
'structure': dict,
300
'list': list,
301
'map': dict
302
}
303
```
304
305
### Argument Table Construction
306
307
Arguments are organized in argument tables for commands:
308
309
```python
310
def build_argument_table(operation_model):
311
"""Build argument table from operation model."""
312
arg_table = {}
313
314
for param_name, param_model in operation_model.input_shape.members.items():
315
cli_name = param_name.replace('_', '-').lower()
316
arg_table[cli_name] = CLIArgument(
317
name=cli_name,
318
argument_model=param_model,
319
operation_model=operation_model,
320
event_emitter=session.get_component('event_emitter')
321
)
322
323
return arg_table
324
```
325
326
### Custom Argument Integration
327
328
Custom commands can define their own argument processing:
329
330
```python
331
from awscli.arguments import CustomArgument
332
from awscli.customizations.commands import BasicCommand
333
334
class MyCommand(BasicCommand):
335
NAME = 'my-command'
336
ARG_TABLE = [
337
CustomArgument(
338
'input-file',
339
help_text='Input file path',
340
required=True,
341
cli_type_name='string'
342
),
343
CustomArgument(
344
'output-format',
345
help_text='Output format',
346
choices=['json', 'yaml', 'text'],
347
default='json'
348
)
349
]
350
351
def _run_main(self, parsed_args, parsed_globals):
352
input_file = parsed_args.input_file
353
output_format = parsed_args.output_format
354
# Process arguments and execute command
355
```