0
# AWS Resources
1
2
AWS resource classes representing all CloudFormation resource types across 257 AWS services. Each resource class inherits from AWSObject and includes built-in property validation, references, and attribute access.
3
4
## Capabilities
5
6
### Base Resource Classes
7
8
Core base classes that all AWS resources inherit from, providing common functionality for validation, serialization, and CloudFormation integration.
9
10
```python { .api }
11
class BaseAWSObject:
12
def __init__(self, title: Optional[str], template: Optional[Template] = None,
13
validation: bool = True, **kwargs):
14
"""
15
Base class for all AWS objects.
16
17
Args:
18
title: Logical name for the resource
19
template: Template to add resource to
20
validation: Whether to enable property validation
21
**kwargs: Resource properties
22
"""
23
24
def validate(self) -> None:
25
"""Validate resource properties."""
26
27
def to_dict(self, validation: bool = True) -> Dict[str, Any]:
28
"""
29
Convert resource to dictionary format.
30
31
Args:
32
validation: Whether to validate before conversion
33
34
Returns:
35
dict: Resource as dictionary
36
"""
37
38
def to_json(self, indent: int = 4, sort_keys: bool = True,
39
validation: bool = True) -> str:
40
"""
41
Convert resource to JSON string.
42
43
Args:
44
indent: JSON indentation
45
sort_keys: Whether to sort keys
46
validation: Whether to validate before conversion
47
48
Returns:
49
str: Resource as JSON
50
"""
51
52
def no_validation(self):
53
"""Disable validation for this resource."""
54
55
@classmethod
56
def from_dict(cls, title: str, d: Dict[str, Any]):
57
"""
58
Create resource from dictionary.
59
60
Args:
61
title: Resource logical name
62
d: Resource properties dictionary
63
64
Returns:
65
Resource instance
66
"""
67
```
68
69
```python { .api }
70
class AWSObject(BaseAWSObject):
71
dictname = "Properties"
72
73
def ref(self) -> Ref:
74
"""
75
Create Ref to this resource.
76
77
Returns:
78
Ref: Reference to this resource
79
"""
80
81
def get_att(self, value: str) -> GetAtt:
82
"""
83
Get resource attribute.
84
85
Args:
86
value: Attribute name
87
88
Returns:
89
GetAtt: Attribute reference
90
"""
91
```
92
93
```python { .api }
94
class AWSProperty(BaseAWSObject):
95
dictname = None
96
97
def __init__(self, title: Optional[str] = None, **kwargs):
98
"""
99
Base class for resource properties.
100
101
Args:
102
title: Property name (optional)
103
**kwargs: Property values
104
"""
105
```
106
107
### EC2 Resources
108
109
Amazon Elastic Compute Cloud resources for virtual servers, networking, and storage.
110
111
```python { .api }
112
class Instance(AWSObject):
113
resource_type = "AWS::EC2::Instance"
114
# Inherits constructor from BaseAWSObject:
115
# def __init__(self, title: str, template: Optional[Template] = None,
116
# validation: bool = True, **kwargs)
117
118
# Key properties (set via constructor kwargs or attribute assignment):
119
# ImageId: str - AMI ID to launch (required)
120
# InstanceType: str - Instance type (required)
121
# KeyName: str - Key pair name for SSH access
122
# SecurityGroups: List[str] - Security group names (EC2-Classic)
123
# SecurityGroupIds: List[str] - Security group IDs (VPC)
124
# SubnetId: str - Subnet ID for VPC instances
125
# UserData: str - User data script
126
# IamInstanceProfile: str - IAM instance profile
127
# BlockDeviceMappings: List[dict] - Block device mappings
128
129
class SecurityGroup(AWSObject):
130
resource_type = "AWS::EC2::SecurityGroup"
131
# Inherits constructor from BaseAWSObject
132
133
# Key properties:
134
# GroupDescription: str - Security group description (required)
135
# VpcId: str - VPC ID (required for VPC security groups)
136
# SecurityGroupIngress: List[dict] - Inbound rules
137
# SecurityGroupEgress: List[dict] - Outbound rules
138
# GroupName: str - Security group name
139
140
class VPC(AWSObject):
141
resource_type = "AWS::EC2::VPC"
142
# Inherits constructor from BaseAWSObject
143
144
# Key properties:
145
# CidrBlock: str - VPC CIDR block (required)
146
# EnableDnsHostnames: bool - Enable DNS hostnames
147
# EnableDnsSupport: bool - Enable DNS support
148
# InstanceTenancy: str - Instance tenancy ('default', 'dedicated', 'host')
149
150
class Subnet(AWSObject):
151
resource_type = "AWS::EC2::Subnet"
152
# Inherits constructor from BaseAWSObject
153
154
# Key properties:
155
# VpcId: str - VPC ID (required)
156
# CidrBlock: str - Subnet CIDR block (required)
157
# AvailabilityZone: str - Availability zone
158
# MapPublicIpOnLaunch: bool - Auto-assign public IP
159
```
160
161
### S3 Resources
162
163
Amazon Simple Storage Service resources for object storage, buckets, and access control.
164
165
```python { .api }
166
class Bucket(AWSObject):
167
resource_type = "AWS::S3::Bucket"
168
# Inherits constructor from BaseAWSObject
169
170
# Key properties:
171
# BucketName: str - Bucket name
172
# AccessControl: str - Access control list
173
# BucketEncryption: dict - Bucket encryption configuration
174
# CorsConfiguration: dict - CORS configuration
175
# LifecycleConfiguration: dict - Lifecycle rules
176
# NotificationConfiguration: dict - Event notifications
177
# PublicAccessBlockConfiguration: dict - Public access settings
178
# VersioningConfiguration: dict - Versioning configuration
179
WebsiteConfiguration: dict = None, **kwargs):
180
"""
181
S3 Bucket resource.
182
183
Args:
184
title: Logical resource name
185
BucketName: Bucket name (auto-generated if not specified)
186
AccessControl: Canned ACL for bucket
187
BucketEncryption: Encryption configuration
188
CorsConfiguration: CORS configuration
189
LifecycleConfiguration: Lifecycle rules
190
NotificationConfiguration: Event notifications
191
PublicAccessBlockConfiguration: Public access block settings
192
VersioningConfiguration: Versioning settings
193
WebsiteConfiguration: Static website hosting
194
"""
195
196
class BucketPolicy(AWSObject):
197
resource_type = "AWS::S3::BucketPolicy"
198
# Inherits constructor from BaseAWSObject
199
200
# Key properties:
201
# Bucket: str - Bucket name or reference (required)
202
# PolicyDocument: dict - IAM policy document (required)
203
```
204
205
### Lambda Resources
206
207
AWS Lambda resources for serverless computing and event-driven applications.
208
209
```python { .api }
210
class Function(AWSObject):
211
resource_type = "AWS::Lambda::Function"
212
# Inherits constructor from BaseAWSObject
213
214
# Key properties:
215
# Code: dict - Function code (S3 or inline) (required)
216
# Handler: str - Function handler (required)
217
# Role: str - Execution role ARN (required)
218
# Runtime: str - Runtime environment (required)
219
# FunctionName: str - Function name
220
# Description: str - Function description
221
# Environment: dict - Environment variables
222
# MemorySize: int - Memory allocation (128-10240 MB)
223
# Timeout: int - Timeout in seconds (1-900)
224
# VpcConfig: dict - VPC configuration
225
# DeadLetterConfig: dict - Dead letter queue configuration
226
227
class Permission(AWSObject):
228
resource_type = "AWS::Lambda::Permission"
229
# Inherits constructor from BaseAWSObject
230
231
# Key properties:
232
# Action: str - Lambda action ('lambda:InvokeFunction') (required)
233
# FunctionName: str - Function name or ARN (required)
234
# Principal: str - Principal requesting permission (required)
235
# SourceArn: str - Source ARN for permission
236
# SourceAccount: str - Source account ID
237
"""
238
```
239
240
## Usage Examples
241
242
AWS resources use the BaseAWSObject constructor and set properties via keyword arguments or attribute assignment:
243
244
```python
245
from troposphere import Template, Ref, GetAtt
246
from troposphere.ec2 import Instance, SecurityGroup
247
from troposphere.s3 import Bucket
248
249
# Create template
250
template = Template()
251
252
# Method 1: Set properties via constructor kwargs
253
instance = Instance(
254
"MyInstance",
255
ImageId="ami-12345678",
256
InstanceType="t2.micro",
257
KeyName="my-key"
258
)
259
260
# Method 2: Set properties via attribute assignment
261
security_group = SecurityGroup("MySecurityGroup")
262
security_group.GroupDescription = "My security group"
263
security_group.SecurityGroupIngress = [
264
{
265
"IpProtocol": "tcp",
266
"FromPort": 22,
267
"ToPort": 22,
268
"CidrIp": "0.0.0.0/0"
269
}
270
]
271
272
# Method 3: Mixed approach
273
bucket = Bucket(
274
"MyBucket",
275
BucketName="my-unique-bucket-name"
276
)
277
bucket.VersioningConfiguration = {
278
"Status": "Enabled"
279
}
280
281
# Add resources to template
282
template.add_resource(instance)
283
template.add_resource(security_group)
284
template.add_resource(bucket)
285
286
# Reference resources
287
instance.SecurityGroupIds = [Ref(security_group)]
288
289
# Get resource attributes
290
bucket_domain_name = GetAtt(bucket, "DomainName")
291
```
292
293
### RDS Resources
294
295
Amazon Relational Database Service resources for managed databases.
296
297
```python { .api }
298
class DBInstance(AWSObject):
299
resource_type = "AWS::RDS::DBInstance"
300
# Inherits constructor from BaseAWSObject
301
302
# Key properties:
303
# DBInstanceClass: str - DB instance class (required)
304
# Engine: str - Database engine (required)
305
# AllocatedStorage: int - Storage size in GB
306
# DBName: str - Database name
307
# MasterUsername: str - Master username
308
# MasterUserPassword: str - Master password
309
# VPCSecurityGroups: List[str] - VPC security groups
310
# DBSubnetGroupName: str - DB subnet group
311
# MultiAZ: bool - Multi-AZ deployment
312
# StorageEncrypted: bool - Storage encryption
313
314
class DBCluster(AWSObject):
315
resource_type = "AWS::RDS::DBCluster"
316
# Inherits constructor from BaseAWSObject
317
318
# Key properties:
319
# Engine: str - Database engine (required)
320
# MasterUsername: str - Master username
321
# MasterUserPassword: str - Master password
322
# DatabaseName: str - Database name
323
# VpcSecurityGroupIds: List[str] - VPC security group IDs
324
# DBSubnetGroupName: str - DB subnet group
325
```
326
327
### IAM Resources
328
329
Identity and Access Management resources for authentication and authorization.
330
331
```python { .api }
332
class Role(AWSObject):
333
resource_type = "AWS::IAM::Role"
334
335
def __init__(self, title: str, AssumeRolePolicyDocument: dict,
336
RoleName: str = None, ManagedPolicyArns: list = None,
337
Policies: list = None, Path: str = None, **kwargs):
338
"""
339
IAM Role resource.
340
341
Args:
342
title: Logical resource name
343
AssumeRolePolicyDocument: Trust policy document
344
RoleName: Role name
345
ManagedPolicyArns: Managed policy ARNs
346
Policies: Inline policies
347
Path: Role path
348
"""
349
350
class Policy(AWSObject):
351
resource_type = "AWS::IAM::Policy"
352
353
def __init__(self, title: str, PolicyDocument: dict, PolicyName: str,
354
Groups: list = None, Roles: list = None, Users: list = None, **kwargs):
355
"""
356
IAM Policy resource.
357
358
Args:
359
title: Logical resource name
360
PolicyDocument: Policy document
361
PolicyName: Policy name
362
Groups: Groups to attach policy to
363
Roles: Roles to attach policy to
364
Users: Users to attach policy to
365
"""
366
```
367
368
## Resource Properties
369
370
All AWS resources support common properties that can be set as attributes:
371
372
```python { .api }
373
# Common resource attributes
374
resource.Condition = condition_name
375
resource.CreationPolicy = creation_policy_dict
376
resource.DeletionPolicy = "Delete" | "Retain" | "Snapshot"
377
resource.DependsOn = dependency_list
378
resource.Metadata = metadata_dict
379
resource.UpdatePolicy = update_policy_dict
380
resource.UpdateReplacePolicy = "Delete" | "Retain" | "Snapshot"
381
```
382
383
## Usage Examples
384
385
### Basic Resource Creation
386
387
```python
388
from troposphere import Template, Ref
389
from troposphere.ec2 import Instance, SecurityGroup
390
391
template = Template()
392
393
# Create security group
394
sg = template.add_resource(SecurityGroup(
395
"MySecurityGroup",
396
GroupDescription="Allow SSH access",
397
SecurityGroupIngress=[{
398
"IpProtocol": "tcp",
399
"FromPort": 22,
400
"ToPort": 22,
401
"CidrIp": "0.0.0.0/0"
402
}]
403
))
404
405
# Create EC2 instance
406
instance = template.add_resource(Instance(
407
"MyInstance",
408
ImageId="ami-0abcdef1234567890",
409
InstanceType="t2.micro",
410
SecurityGroupIds=[Ref(sg)],
411
KeyName="my-key-pair"
412
))
413
414
# Set resource attributes
415
instance.DeletionPolicy = "Retain"
416
instance.DependsOn = [sg]
417
```
418
419
### Resource with Custom Properties
420
421
```python
422
from troposphere.s3 import Bucket
423
424
# Create S3 bucket with custom properties
425
bucket = Bucket(
426
"MyBucket",
427
BucketName="my-unique-bucket-name",
428
VersioningConfiguration={
429
"Status": "Enabled"
430
},
431
BucketEncryption={
432
"ServerSideEncryptionConfiguration": [{
433
"ServerSideEncryptionByDefault": {
434
"SSEAlgorithm": "AES256"
435
}
436
}]
437
},
438
PublicAccessBlockConfiguration={
439
"BlockPublicAcls": True,
440
"BlockPublicPolicy": True,
441
"IgnorePublicAcls": True,
442
"RestrictPublicBuckets": True
443
}
444
)
445
```
446
447
### Resource References and Attributes
448
449
```python
450
from troposphere import Ref, GetAtt, Output
451
from troposphere.ec2 import Instance
452
453
# Create instance
454
instance = Instance(
455
"MyInstance",
456
ImageId="ami-0abcdef1234567890",
457
InstanceType="t2.micro"
458
)
459
460
# Reference the instance
461
instance_ref = Ref(instance)
462
# or
463
instance_ref = instance.ref()
464
465
# Get instance attributes
466
public_ip = GetAtt(instance, "PublicIp")
467
# or
468
public_ip = instance.get_att("PublicIp")
469
470
# Use in outputs
471
Output(
472
"InstanceId",
473
Value=Ref(instance),
474
Description="Instance ID"
475
)
476
477
Output(
478
"PublicIP",
479
Value=GetAtt(instance, "PublicIp"),
480
Description="Instance public IP"
481
)
482
```