0
# EC2 Operations
1
2
EC2-specific functionality including tag management operations. These methods are automatically injected into EC2 service resources and instance resources, providing convenient Python interfaces for managing EC2 tags without needing to work directly with low-level client APIs.
3
4
## Capabilities
5
6
### Tag Management for Service Resource
7
8
Tag management methods available on the EC2 service resource for applying tags to multiple resources simultaneously.
9
10
```python { .api }
11
# Methods available on EC2 service resource (boto3.resource('ec2'))
12
def create_tags(self, resources: List[str], tags: List[Dict[str, str]],
13
dry_run: bool = None, **kwargs) -> List:
14
"""
15
Create tags on one or more EC2 resources.
16
17
This method allows applying a set of tags to multiple EC2 resources
18
in a single operation and returns Tag resource objects for each
19
created tag.
20
21
Parameters:
22
- resources: List of EC2 resource IDs to tag (e.g., ['i-1234567890abcdef0'])
23
- tags: List of tag dictionaries with 'Key' and 'Value' keys
24
- dry_run: Perform a dry run without actually creating tags
25
- **kwargs: Additional parameters passed to the underlying create_tags API
26
27
Returns:
28
List of Tag resource objects for each created tag
29
30
Example tags format:
31
[{'Key': 'Environment', 'Value': 'Production'}, {'Key': 'Owner', 'Value': 'TeamA'}]
32
"""
33
```
34
35
### Tag Management for Instance Resource
36
37
Tag management methods available on individual EC2 instance resources for managing tags on specific instances.
38
39
```python { .api }
40
# Methods available on EC2 Instance resources
41
def delete_tags(self, tags: List[Dict[str, str]] = None, dry_run: bool = None,
42
**kwargs) -> None:
43
"""
44
Delete tags from this EC2 instance.
45
46
This method is automatically injected into EC2 Instance resources
47
and allows deletion of specific tags from the instance.
48
49
Parameters:
50
- tags: List of tag dictionaries to delete. If not specified, all tags are deleted
51
- dry_run: Perform a dry run without actually deleting tags
52
- **kwargs: Additional parameters passed to the underlying delete_tags API
53
54
Tag format for deletion:
55
- To delete specific tags: [{'Key': 'Environment'}, {'Key': 'Owner'}]
56
- To delete tags with specific values: [{'Key': 'Environment', 'Value': 'Test'}]
57
- If tags parameter is None, all tags on the resource are deleted
58
"""
59
```
60
61
### Injected Tag Methods
62
63
These methods are automatically added to EC2 resources during resource creation and are not part of the base resource classes.
64
65
```python { .api }
66
# The injection mechanism adds these methods dynamically
67
from boto3.ec2.createtags import create_tags
68
from boto3.ec2.deletetags import delete_tags
69
70
# Internal functions used for method injection
71
def inject_create_tags(event_name: str, class_attributes: dict, **kwargs) -> None:
72
"""Inject create_tags method onto EC2 service resource."""
73
74
def inject_delete_tags(event_emitter, **kwargs) -> None:
75
"""Inject delete_tags method onto EC2 instance resources."""
76
```
77
78
## Usage Examples
79
80
### Creating Tags on Multiple Resources
81
82
```python
83
import boto3
84
85
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
86
87
# Create tags on multiple EC2 resources
88
tag_resources = ec2_resource.create_tags(
89
resources=[
90
'i-1234567890abcdef0', # Instance ID
91
'vol-1234567890abcdef0', # Volume ID
92
'sg-1234567890abcdef0' # Security Group ID
93
],
94
tags=[
95
{'Key': 'Environment', 'Value': 'Production'},
96
{'Key': 'Project', 'Value': 'WebApp'},
97
{'Key': 'Owner', 'Value': 'TeamA'}
98
]
99
)
100
101
# The method returns Tag resource objects
102
print(f"Created {len(tag_resources)} tag resources")
103
for tag in tag_resources:
104
print(f"Tag: {tag.key} = {tag.value} on resource {tag.resource_id}")
105
```
106
107
### Working with Instance Tags
108
109
```python
110
import boto3
111
112
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
113
114
# Get a specific instance
115
instance = ec2_resource.Instance('i-1234567890abcdef0')
116
117
# Create tags on the instance using the service resource method
118
ec2_resource.create_tags(
119
resources=[instance.id],
120
tags=[
121
{'Key': 'Name', 'Value': 'WebServer-01'},
122
{'Key': 'Role', 'Value': 'WebServer'}
123
]
124
)
125
126
# Delete specific tags from the instance using the instance method
127
instance.delete_tags(
128
tags=[
129
{'Key': 'Role'}, # Delete tag by key only
130
{'Key': 'OldTag', 'Value': 'OldValue'} # Delete specific key-value pair
131
]
132
)
133
```
134
135
### Tag Management with Error Handling
136
137
```python
138
import boto3
139
from botocore.exceptions import ClientError
140
141
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
142
instance = ec2_resource.Instance('i-1234567890abcdef0')
143
144
try:
145
# Create tags with dry run to validate permissions
146
ec2_resource.create_tags(
147
resources=[instance.id],
148
tags=[{'Key': 'Test', 'Value': 'DryRun'}],
149
dry_run=True
150
)
151
print("Dry run successful - permissions are correct")
152
153
# Perform actual tag creation
154
tag_resources = ec2_resource.create_tags(
155
resources=[instance.id],
156
tags=[
157
{'Key': 'Environment', 'Value': 'Staging'},
158
{'Key': 'Application', 'Value': 'API-Server'}
159
]
160
)
161
print(f"Successfully created {len(tag_resources)} tags")
162
163
except ClientError as e:
164
error_code = e.response['Error']['Code']
165
if error_code == 'DryRunOperation':
166
print("Dry run completed successfully")
167
elif error_code == 'UnauthorizedOperation':
168
print("Insufficient permissions to create tags")
169
elif error_code == 'InvalidInstanceID.NotFound':
170
print("Instance not found")
171
else:
172
print(f"Error creating tags: {e}")
173
```
174
175
### Batch Tag Operations
176
177
```python
178
import boto3
179
180
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
181
182
# Tag multiple instances with common tags
183
instance_ids = ['i-1234567890abcdef0', 'i-abcdef1234567890', 'i-567890abcdef1234']
184
185
# Apply common tags to all instances
186
common_tags = [
187
{'Key': 'Project', 'Value': 'DataPipeline'},
188
{'Key': 'Environment', 'Value': 'Production'},
189
{'Key': 'ManagedBy', 'Value': 'AutoScaling'}
190
]
191
192
tag_resources = ec2_resource.create_tags(
193
resources=instance_ids,
194
tags=common_tags
195
)
196
197
print(f"Applied {len(common_tags)} tags to {len(instance_ids)} instances")
198
199
# Remove specific tags from all instances
200
for instance_id in instance_ids:
201
instance = ec2_resource.Instance(instance_id)
202
instance.delete_tags(
203
tags=[{'Key': 'ManagedBy'}] # Remove ManagedBy tag
204
)
205
print(f"Removed ManagedBy tag from {instance_id}")
206
```
207
208
### Working with Existing Tags
209
210
```python
211
import boto3
212
213
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
214
instance = ec2_resource.Instance('i-1234567890abcdef0')
215
216
# View existing tags before modification
217
print("Current tags:")
218
for tag in instance.tags or []:
219
print(f" {tag['Key']}: {tag['Value']}")
220
221
# Add new tags while preserving existing ones
222
new_tags = [
223
{'Key': 'BackupSchedule', 'Value': 'Daily'},
224
{'Key': 'MaintenanceWindow', 'Value': 'Sunday-02:00-04:00'}
225
]
226
227
ec2_resource.create_tags(
228
resources=[instance.id],
229
tags=new_tags
230
)
231
232
# Refresh instance to see updated tags
233
instance.reload()
234
print("\nUpdated tags:")
235
for tag in instance.tags or []:
236
print(f" {tag['Key']}: {tag['Value']}")
237
```
238
239
### Using Tags for Resource Management
240
241
```python
242
import boto3
243
244
ec2_resource = boto3.resource('ec2', region_name='us-east-1')
245
246
# Find instances by tag and update them
247
instances = ec2_resource.instances.filter(
248
Filters=[
249
{'Name': 'tag:Environment', 'Values': ['Development']},
250
{'Name': 'instance-state-name', 'Values': ['running']}
251
]
252
)
253
254
development_instance_ids = [instance.id for instance in instances]
255
256
if development_instance_ids:
257
# Tag all development instances with additional metadata
258
ec2_resource.create_tags(
259
resources=development_instance_ids,
260
tags=[
261
{'Key': 'AutoShutdown', 'Value': 'Enabled'},
262
{'Key': 'ShutdownTime', 'Value': '18:00'},
263
{'Key': 'LastUpdated', 'Value': '2023-12-01'}
264
]
265
)
266
print(f"Updated {len(development_instance_ids)} development instances")
267
```