0
# Command System
1
2
Comprehensive command framework for creating and executing AWS service operations and custom commands. The command system provides a hierarchical structure that supports AWS services, operations, and custom commands with argument processing and help generation.
3
4
## Capabilities
5
6
### Base Command Interface
7
8
The foundational interface that all CLI commands must implement, providing the basic contract for command execution and help generation.
9
10
```python { .api }
11
class CLICommand:
12
@property
13
def name(self) -> str:
14
"""Command name."""
15
16
@property
17
def lineage(self) -> list:
18
"""Command hierarchy lineage."""
19
20
@property
21
def lineage_names(self) -> list[str]:
22
"""List of command names in hierarchy."""
23
24
@property
25
def arg_table(self) -> dict:
26
"""Argument table for command parameters."""
27
28
def __call__(self, args, parsed_globals):
29
"""
30
Execute the command.
31
32
Parameters:
33
args: parsed command arguments
34
parsed_globals: parsed global arguments
35
36
Returns:
37
Command execution result
38
"""
39
40
def create_help_command(self):
41
"""
42
Create help command for this command.
43
44
Returns:
45
Help command instance
46
"""
47
```
48
49
### Service Command Implementation
50
51
Concrete implementation for AWS service commands that handles service-level operations and subcommand routing.
52
53
```python { .api }
54
class ServiceCommand(CLICommand):
55
def __init__(self, cli_name, session, service_name=None):
56
"""
57
Initialize service command for AWS service.
58
59
Parameters:
60
cli_name: str, CLI name for the service (e.g., 's3', 'ec2')
61
session: botocore.session.Session, AWS session
62
service_name: str, optional service name (defaults to cli_name)
63
"""
64
65
@property
66
def service_model(self):
67
"""Botocore service model providing service metadata and operations."""
68
69
def create_help_command(self):
70
"""Create service-level help command showing available operations."""
71
```
72
73
**Usage Example:**
74
```python
75
import botocore.session
76
from awscli.clidriver import ServiceCommand
77
78
# Create service command for S3
79
session = botocore.session.Session()
80
s3_command = ServiceCommand('s3', session)
81
82
# Access service information
83
print(f"Service name: {s3_command.name}")
84
print(f"Available operations: {s3_command.service_model.operation_names}")
85
```
86
87
### Service Operation Implementation
88
89
Represents individual operations within AWS services, handling operation-specific argument processing and execution.
90
91
```python { .api }
92
class ServiceOperation:
93
def __init__(self, name, parent_name, operation_caller, operation_model, session):
94
"""
95
Initialize service operation.
96
97
Parameters:
98
name: str, operation name (e.g., 'describe-instances')
99
parent_name: str, parent service name (e.g., 'ec2')
100
operation_caller: CLIOperationCaller, handles operation execution
101
operation_model: botocore operation model
102
session: botocore.session.Session, AWS session
103
"""
104
105
@property
106
def name(self) -> str:
107
"""Operation name."""
108
109
@property
110
def lineage(self) -> list:
111
"""Full command hierarchy including service and operation."""
112
113
@property
114
def lineage_names(self) -> list[str]:
115
"""List of command names from root to this operation."""
116
117
@property
118
def arg_table(self) -> dict:
119
"""
120
Argument table mapping parameter names to argument definitions.
121
Contains all operation parameters as CLI arguments.
122
"""
123
124
def create_help_command(self):
125
"""Create operation-level help command with parameter documentation."""
126
```
127
128
**Usage Example:**
129
```python
130
from awscli.clidriver import ServiceOperation, CLIOperationCaller
131
import botocore.session
132
133
# Create session and operation caller
134
session = botocore.session.Session()
135
operation_caller = CLIOperationCaller(session)
136
137
# Get operation model
138
ec2_model = session.get_service_model('ec2')
139
describe_instances_model = ec2_model.operation_model('DescribeInstances')
140
141
# Create operation
142
operation = ServiceOperation(
143
name='describe-instances',
144
parent_name='ec2',
145
operation_caller=operation_caller,
146
operation_model=describe_instances_model,
147
session=session
148
)
149
150
# Access operation information
151
print(f"Operation: {operation.name}")
152
print(f"Lineage: {operation.lineage_names}")
153
print(f"Available parameters: {list(operation.arg_table.keys())}")
154
```
155
156
## Command Hierarchy Structure
157
158
The AWS CLI uses a hierarchical command structure:
159
160
```
161
aws (root)
162
├── s3 (service)
163
│ ├── ls (operation)
164
│ ├── cp (operation)
165
│ └── sync (operation)
166
├── ec2 (service)
167
│ ├── describe-instances (operation)
168
│ ├── run-instances (operation)
169
│ └── terminate-instances (operation)
170
└── iam (service)
171
├── list-users (operation)
172
├── create-user (operation)
173
└── delete-user (operation)
174
```
175
176
### Command Registration
177
178
Commands are dynamically registered based on AWS service models:
179
180
```python
181
# Service commands are created from botocore service models
182
service_names = session.get_available_services()
183
for service_name in service_names:
184
service_command = ServiceCommand(service_name, session)
185
186
# Operations are created from service model operations
187
service_model = session.get_service_model(service_name)
188
for operation_name in service_model.operation_names:
189
operation = ServiceOperation(
190
name=operation_name,
191
parent_name=service_name,
192
operation_caller=operation_caller,
193
operation_model=service_model.operation_model(operation_name),
194
session=session
195
)
196
```
197
198
## Advanced Command Patterns
199
200
### Command Execution Flow
201
202
1. **Command Parsing**: Arguments are parsed into command hierarchy
203
2. **Command Resolution**: Appropriate command instance is located
204
3. **Argument Processing**: Command arguments are validated and processed
205
4. **Command Execution**: Command's `__call__` method is invoked
206
5. **Response Formatting**: Output is formatted according to specified format
207
208
### Custom Command Integration
209
210
While service commands are automatically generated, custom commands can be integrated:
211
212
```python
213
from awscli.commands import CLICommand
214
215
class CustomServiceCommand(CLICommand):
216
def __init__(self, session):
217
self._session = session
218
self._name = 'custom-service'
219
220
@property
221
def name(self):
222
return self._name
223
224
@property
225
def lineage(self):
226
return [self]
227
228
@property
229
def lineage_names(self):
230
return [self.name]
231
232
@property
233
def arg_table(self):
234
return {
235
'param1': CustomArgument('param1', help_text='Custom parameter'),
236
}
237
238
def __call__(self, args, parsed_globals):
239
print(f"Executing custom service with args: {args}")
240
return 0
241
242
def create_help_command(self):
243
return CustomHelpCommand(self)
244
```
245
246
### Error Handling in Commands
247
248
Commands should handle errors gracefully and return appropriate exit codes:
249
250
```python
251
class RobustCommand(CLICommand):
252
def __call__(self, args, parsed_globals):
253
try:
254
# Command logic here
255
return 0 # Success
256
except ValidationError as e:
257
sys.stderr.write(f"Validation error: {e}\n")
258
return 1 # Validation failure
259
except ServiceError as e:
260
sys.stderr.write(f"Service error: {e}\n")
261
return 2 # Service failure
262
except Exception as e:
263
sys.stderr.write(f"Unexpected error: {e}\n")
264
return 255 # Unexpected failure
265
```