0
# Parameters and Outputs
1
2
CloudFormation template parameters for user inputs and outputs for exposing resource values, with comprehensive validation and cross-stack reference support.
3
4
## Capabilities
5
6
### Parameters
7
8
Template parameters allow users to provide input values when creating or updating CloudFormation stacks.
9
10
```python { .api }
11
class Parameter(AWSDeclaration):
12
# Inherits constructor from BaseAWSObject:
13
# def __init__(self, title: str, template: Optional[Template] = None,
14
# validation: bool = True, **kwargs)
15
16
# Key properties (set via constructor kwargs or attribute assignment):
17
# Type: str - Parameter type (required)
18
# Default: Union[str, int, float] - Default value
19
# NoEcho: bool - Whether to mask parameter value in console
20
# AllowedValues: List[Any] - List of allowed values
21
# AllowedPattern: str - Regular expression pattern for validation
22
# MaxLength: int - Maximum string length (String parameters only)
23
# MinLength: int - Minimum string length (String parameters only)
24
# MaxValue: int - Maximum numeric value (Number parameters only)
25
# MinValue: int - Minimum numeric value (Number parameters only)
26
# Description: str - Parameter description
27
# ConstraintDescription: str - Error message for constraint violations
28
29
def validate(self) -> None:
30
"""Validate parameter configuration and default value."""
31
32
def validate_title(self) -> None:
33
"""Validate parameter title length (max 255 characters)."""
34
```
35
36
### Parameter Types
37
38
CloudFormation supports various parameter types with specific validation rules.
39
40
```python { .api }
41
# Basic Parameter Types (string values for Type property)
42
"String" - String parameter type
43
"Number" - Numeric parameter type
44
"List<Number>" - List of numbers parameter type
45
"CommaDelimitedList" - Comma-delimited list parameter type
46
47
# AWS-Specific Parameter Types (string values for Type property)
48
"AWS::EC2::AvailabilityZone::Name" - EC2 Availability Zone name
49
"AWS::EC2::Image::Id" - EC2 AMI ID
50
"AWS::EC2::Instance::Id" - EC2 Instance ID
51
"AWS::EC2::KeyPair::KeyName" - EC2 Key Pair name
52
"AWS::EC2::SecurityGroup::GroupName" - EC2 Security Group name
53
"AWS::EC2::SecurityGroup::Id" - EC2 Security Group ID
54
"AWS::EC2::Subnet::Id" - EC2 Subnet ID
55
"AWS::EC2::VPC::Id" - EC2 VPC ID
56
"AWS::Route53::HostedZone::Id" - Route53 Hosted Zone ID
57
"AWS::S3::Bucket::Name" - S3 Bucket name
58
59
# List Types (string values for Type property)
60
"List<AWS::EC2::AvailabilityZone::Name>" - List of AZ names
61
"List<AWS::EC2::Image::Id>" - List of AMI IDs
62
"List<AWS::EC2::Instance::Id>" - List of Instance IDs
63
"List<AWS::EC2::SecurityGroup::GroupName>" - List of SG names
64
"List<AWS::EC2::SecurityGroup::Id>" - List of SG IDs
65
"List<AWS::EC2::Subnet::Id>" - List of Subnet IDs
66
"List<AWS::EC2::VPC::Id>" - List of VPC IDs
67
"List<AWS::Route53::HostedZone::Id>" - List of Hosted Zone IDs
68
```
69
70
### Outputs
71
72
Template outputs expose resource values and can be imported by other stacks.
73
74
```python { .api }
75
class Output(AWSDeclaration):
76
# Inherits constructor from BaseAWSObject:
77
# def __init__(self, title: str, template: Optional[Template] = None,
78
# validation: bool = True, **kwargs)
79
80
# Key properties (set via constructor kwargs or attribute assignment):
81
# Value: Union[str, AWSHelperFn] - Output value (required)
82
# Description: str - Output description
83
# Export: Export - Export configuration for cross-stack references
84
```
85
86
### Cross-Stack Exports
87
88
Enable cross-stack references by exporting output values.
89
90
```python { .api }
91
class Export(AWSHelperFn):
92
def __init__(self, name: Union[str, AWSHelperFn]):
93
"""Export configuration for outputs with given name."""
94
95
# Args:
96
# name: Union[str, AWSHelperFn] - Export name (must be unique within region)
97
```
98
99
## Usage Examples
100
101
### Basic Parameters
102
103
```python
104
from troposphere import Template, Parameter, Ref
105
from troposphere.constants import T2_MICRO, T2_SMALL, T2_MEDIUM
106
107
template = Template()
108
109
# String parameter with allowed values
110
instance_type = Parameter(
111
"InstanceType",
112
Type="String",
113
Default="t2.micro",
114
AllowedValues=["t2.micro", "t2.small", "t2.medium"],
115
Description="EC2 instance type for the application server",
116
ConstraintDescription="Must be a valid EC2 instance type"
117
)
118
template.add_parameter(instance_type)
119
120
# Number parameter with range
121
port = Parameter(
122
"Port",
123
Type="Number",
124
Default=8080,
125
MinValue=1024,
126
MaxValue=65535,
127
Description="Application port number"
128
)
129
template.add_parameter(port)
130
131
# String parameter with pattern
132
bucket_name = Parameter(
133
"BucketName",
134
Type="String",
135
AllowedPattern="^[a-z0-9.-]*$",
136
MinLength=3,
137
MaxLength=63,
138
Description="S3 bucket name (lowercase letters, numbers, dots, hyphens only)",
139
ConstraintDescription="Bucket name must be 3-63 characters, lowercase letters, numbers, dots, and hyphens only"
140
)
141
template.add_parameter(bucket_name)
142
143
# NoEcho parameter for sensitive data
144
db_password = template.add_parameter(Parameter(
145
"DatabasePassword",
146
Type="String",
147
NoEcho=True,
148
MinLength=8,
149
MaxLength=128,
150
Description="Database master password",
151
ConstraintDescription="Password must be 8-128 characters"
152
))
153
```
154
155
### AWS-Specific Parameter Types
156
157
```python
158
from troposphere import Template, Parameter
159
160
template = Template()
161
162
# VPC selection
163
vpc_id = template.add_parameter(Parameter(
164
"VpcId",
165
Type="AWS::EC2::VPC::Id",
166
Description="VPC ID where resources will be created"
167
))
168
169
# Subnet selection (multiple)
170
subnet_ids = template.add_parameter(Parameter(
171
"SubnetIds",
172
Type="List<AWS::EC2::Subnet::Id>",
173
Description="List of subnet IDs for load balancer"
174
))
175
176
# Key pair selection
177
key_name = template.add_parameter(Parameter(
178
"KeyName",
179
Type="AWS::EC2::KeyPair::KeyName",
180
Description="EC2 Key Pair for SSH access"
181
))
182
183
# AMI selection
184
ami_id = template.add_parameter(Parameter(
185
"AmiId",
186
Type="AWS::EC2::Image::Id",
187
Description="AMI ID for EC2 instances"
188
))
189
190
# Security group selection
191
security_groups = template.add_parameter(Parameter(
192
"SecurityGroups",
193
Type="List<AWS::EC2::SecurityGroup::Id>",
194
Description="Security groups for EC2 instances"
195
))
196
```
197
198
### Complex Parameter Validation
199
200
```python
201
from troposphere import Template, Parameter
202
from troposphere.validators import positive_integer
203
204
template = Template()
205
206
# Custom validation function
207
def validate_cidr(cidr):
208
import ipaddress
209
try:
210
ipaddress.IPv4Network(cidr, strict=False)
211
return cidr
212
except ValueError:
213
raise ValueError(f"Invalid CIDR block: {cidr}")
214
215
# Parameter with custom validator
216
vpc_cidr = Parameter(
217
"VpcCidr",
218
Type="String",
219
Default="10.0.0.0/16",
220
Description="CIDR block for VPC",
221
props={
222
"VpcCidr": (validate_cidr, True)
223
}
224
)
225
226
# CommaDelimitedList parameter
227
availability_zones = template.add_parameter(Parameter(
228
"AvailabilityZones",
229
Type="CommaDelimitedList",
230
Description="List of availability zones",
231
Default="us-east-1a,us-east-1b"
232
))
233
234
# List<Number> parameter
235
alarm_thresholds = template.add_parameter(Parameter(
236
"AlarmThresholds",
237
Type="List<Number>",
238
Description="CloudWatch alarm thresholds",
239
Default="70,85,95"
240
))
241
```
242
243
### Parameter Groups and Labels
244
245
```python
246
from troposphere import Template, Parameter
247
248
template = Template()
249
250
# Network parameters
251
vpc_id = template.add_parameter(Parameter(
252
"VpcId",
253
Type="AWS::EC2::VPC::Id",
254
Description="VPC for resources"
255
))
256
257
subnet_id = template.add_parameter(Parameter(
258
"SubnetId",
259
Type="AWS::EC2::Subnet::Id",
260
Description="Subnet for instance"
261
))
262
263
# Database parameters
264
db_instance_class = template.add_parameter(Parameter(
265
"DBInstanceClass",
266
Type="String",
267
Default="db.t3.micro",
268
Description="RDS instance class"
269
))
270
271
db_allocated_storage = template.add_parameter(Parameter(
272
"DBAllocatedStorage",
273
Type="Number",
274
Default=20,
275
MinValue=20,
276
MaxValue=1000,
277
Description="Database storage size in GB"
278
))
279
280
# Group parameters
281
template.add_parameter_to_group(vpc_id, "Network Configuration")
282
template.add_parameter_to_group(subnet_id, "Network Configuration")
283
template.add_parameter_to_group(db_instance_class, "Database Configuration")
284
template.add_parameter_to_group(db_allocated_storage, "Database Configuration")
285
286
# Set parameter labels
287
template.set_parameter_label(vpc_id, "VPC")
288
template.set_parameter_label(subnet_id, "Subnet")
289
template.set_parameter_label(db_instance_class, "Instance Class")
290
template.set_parameter_label(db_allocated_storage, "Storage Size (GB)")
291
```
292
293
### Basic Outputs
294
295
```python
296
from troposphere import Template, Output, Ref, GetAtt
297
from troposphere.ec2 import Instance
298
from troposphere.s3 import Bucket
299
300
template = Template()
301
302
# Create resources
303
instance = template.add_resource(Instance(
304
"MyInstance",
305
ImageId="ami-0abcdef1234567890",
306
InstanceType="t2.micro"
307
))
308
309
bucket = template.add_resource(Bucket("MyBucket"))
310
311
# Simple outputs
312
template.add_output(Output(
313
"InstanceId",
314
Value=Ref(instance),
315
Description="EC2 Instance ID"
316
))
317
318
template.add_output(Output(
319
"InstancePublicIP",
320
Value=GetAtt(instance, "PublicIp"),
321
Description="Instance public IP address"
322
))
323
324
template.add_output(Output(
325
"BucketName",
326
Value=Ref(bucket),
327
Description="S3 Bucket name"
328
))
329
330
template.add_output(Output(
331
"BucketDomainName",
332
Value=GetAtt(bucket, "DomainName"),
333
Description="S3 Bucket domain name"
334
))
335
```
336
337
### Cross-Stack Exports
338
339
```python
340
from troposphere import Template, Output, Export, Sub, Ref
341
from troposphere.ec2 import VPC, Subnet
342
343
template = Template()
344
345
# Create VPC
346
vpc = template.add_resource(VPC(
347
"MyVPC",
348
CidrBlock="10.0.0.0/16",
349
EnableDnsSupport=True,
350
EnableDnsHostnames=True
351
))
352
353
# Create subnet
354
subnet = template.add_resource(Subnet(
355
"PublicSubnet",
356
VpcId=Ref(vpc),
357
CidrBlock="10.0.1.0/24",
358
MapPublicIpOnLaunch=True
359
))
360
361
# Export VPC ID for other stacks
362
template.add_output(Output(
363
"VpcId",
364
Value=Ref(vpc),
365
Description="VPC ID",
366
Export=Export(Sub("${AWS::StackName}-VPC-ID"))
367
))
368
369
# Export subnet ID
370
template.add_output(Output(
371
"PublicSubnetId",
372
Value=Ref(subnet),
373
Description="Public subnet ID",
374
Export=Export(Sub("${AWS::StackName}-PublicSubnet-ID"))
375
))
376
377
# Export with fixed name
378
template.add_output(Output(
379
"VpcCidr",
380
Value=GetAtt(vpc, "CidrBlock"),
381
Description="VPC CIDR block",
382
Export=Export("MyNetwork-VPC-CIDR")
383
))
384
```
385
386
### Using Imported Values
387
388
```python
389
from troposphere import Template, ImportValue, Sub
390
from troposphere.ec2 import Instance, SecurityGroup
391
392
template = Template()
393
394
# Import values from other stacks
395
vpc_id = ImportValue(Sub("${NetworkStackName}-VPC-ID"))
396
subnet_id = ImportValue(Sub("${NetworkStackName}-PublicSubnet-ID"))
397
398
# Fixed export name import
399
security_group_id = ImportValue("SharedResources-WebServerSecurityGroup")
400
401
# Use imported values
402
instance = template.add_resource(Instance(
403
"WebServer",
404
ImageId="ami-0abcdef1234567890",
405
InstanceType="t2.micro",
406
SubnetId=subnet_id,
407
SecurityGroupIds=[security_group_id]
408
))
409
410
# Parameter for stack name
411
network_stack_param = template.add_parameter(Parameter(
412
"NetworkStackName",
413
Type="String",
414
Description="Name of the network stack to import from"
415
))
416
```
417
418
### Advanced Output Examples
419
420
```python
421
from troposphere import *
422
from troposphere.elasticloadbalancingv2 import LoadBalancer
423
from troposphere.route53 import RecordSet
424
425
template = Template()
426
427
# Create load balancer
428
alb = template.add_resource(LoadBalancer(
429
"ApplicationLoadBalancer",
430
Scheme="internet-facing",
431
Type="application",
432
IpAddressType="ipv4"
433
))
434
435
# Complex output with string manipulation
436
template.add_output(Output(
437
"LoadBalancerURL",
438
Value=Join("", ["http://", GetAtt(alb, "DNSName")]),
439
Description="Application Load Balancer URL"
440
))
441
442
# Conditional output
443
template.add_condition("CreateDNS", Equals(Ref("CreateDNSRecord"), "true"))
444
445
template.add_output(Output(
446
"CustomDomainURL",
447
Condition="CreateDNS",
448
Value=Join("", ["https://", Ref("DomainName")]),
449
Description="Custom domain URL (only if DNS record created)",
450
Export=Export(Sub("${AWS::StackName}-CustomDomain"))
451
))
452
453
# Output with multiple attribute references
454
template.add_output(Output(
455
"LoadBalancerInfo",
456
Value=Sub("DNS: ${DNS}, ARN: ${ARN}, Scheme: ${Scheme}", {
457
"DNS": GetAtt(alb, "DNSName"),
458
"ARN": Ref(alb),
459
"Scheme": GetAtt(alb, "Scheme")
460
}),
461
Description="Load balancer information summary"
462
))
463
```