or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aws-resources.mdconstants.mdhelper-utilities.mdindex.mdintrinsic-functions.mdopenstack-support.mdparameters-outputs.mdtags-metadata.mdtemplate-management.mdvalidation.md

template-management.mddocs/

0

# Template Management

1

2

Core functionality for creating and managing CloudFormation templates, including adding resources, parameters, outputs, mappings, conditions, and converting templates to JSON/YAML formats.

3

4

## Capabilities

5

6

### Template Creation and Configuration

7

8

Create CloudFormation templates with metadata, descriptions, and version settings.

9

10

```python { .api }

11

class Template:

12

def __init__(self, Description: Optional[str] = None, Metadata: Optional[Dict[str, Any]] = None):

13

"""

14

Create a new CloudFormation template.

15

16

Args:

17

Description (str, optional): Template description

18

Metadata (dict, optional): Template metadata

19

"""

20

21

def set_description(self, description: str) -> None:

22

"""Set template description."""

23

24

def set_metadata(self, metadata: Dict[str, Any]) -> None:

25

"""Set template metadata."""

26

27

def set_version(self, version: Optional[str] = None) -> None:

28

"""

29

Set CloudFormation template format version.

30

31

Args:

32

version (str, optional): Template version, defaults to "2010-09-09"

33

"""

34

35

def set_transform(self, transform: Union[List[object], str]) -> None:

36

"""

37

Set template transforms (e.g., AWS::Serverless-2016-10-31).

38

39

Args:

40

transform: Transform name or list of transforms

41

"""

42

43

def set_globals(self, globals: Globals) -> None:

44

"""

45

Set SAM template globals (requires Serverless transform).

46

47

Args:

48

globals: Globals configuration for SAM templates

49

"""

50

```

51

52

### Resource Management

53

54

Add and manage CloudFormation resources within templates with automatic validation and duplicate detection.

55

56

```python { .api }

57

def add_resource(self, resource) -> resource:

58

"""

59

Add a resource to the template.

60

61

Args:

62

resource: AWSObject instance or list of AWSObject instances

63

64

Returns:

65

The added resource(s)

66

67

Raises:

68

ValueError: If maximum resources (500) exceeded or duplicate key detected

69

"""

70

71

def get_or_add_parameter(self, parameter: Parameter) -> Parameter:

72

"""

73

Get existing parameter or add new one.

74

75

Args:

76

parameter: Parameter instance

77

78

Returns:

79

Parameter: Existing or newly added parameter

80

"""

81

```

82

83

### Parameter Management

84

85

Manage template parameters with validation and limits enforcement.

86

87

```python { .api }

88

def add_parameter(self, parameter) -> parameter:

89

"""

90

Add parameter(s) to template.

91

92

Args:

93

parameter: Parameter instance or list of Parameter instances

94

95

Returns:

96

The added parameter(s)

97

98

Raises:

99

ValueError: If maximum parameters (200) exceeded or duplicate key detected

100

"""

101

102

def set_parameter_label(self, parameter: Union[Parameter, str], label: str) -> None:

103

"""

104

Set parameter label for CloudFormation UI.

105

106

Args:

107

parameter: Parameter instance or parameter name

108

label: Display label for parameter

109

"""

110

111

def add_parameter_to_group(self, parameter: Union[Parameter, str], group_name: str) -> str:

112

"""

113

Add parameter to a parameter group.

114

115

Args:

116

parameter: Parameter instance or parameter name

117

group_name: Name of parameter group (created if doesn't exist)

118

119

Returns:

120

str: Group name

121

"""

122

```

123

124

### Output Management

125

126

Manage template outputs with export capabilities for cross-stack references.

127

128

```python { .api }

129

def add_output(self, output) -> output:

130

"""

131

Add output(s) to template.

132

133

Args:

134

output: Output instance or list of Output instances

135

136

Returns:

137

The added output(s)

138

139

Raises:

140

ValueError: If maximum outputs (200) exceeded or duplicate key detected

141

"""

142

```

143

144

### Mappings and Conditions

145

146

Add mappings for static lookups and conditions for conditional resource creation.

147

148

```python { .api }

149

def add_mapping(self, name: str, mapping: Dict[str, Any]) -> None:

150

"""

151

Add mapping to template.

152

153

Args:

154

name: Mapping name

155

mapping: Mapping dictionary

156

157

Raises:

158

ValueError: If maximum mappings (200) exceeded

159

"""

160

161

def add_condition(self, name: str, condition: AWSHelperFn) -> str:

162

"""

163

Add condition to template.

164

165

Args:

166

name: Condition name

167

condition: AWSHelperFn representing the condition logic

168

169

Returns:

170

str: Condition name

171

"""

172

```

173

174

### Rules Management

175

176

Add template rules for parameter validation and constraints.

177

178

```python { .api }

179

def add_rule(self, name: str, rule: object) -> None:

180

"""

181

Add rule to template for parameter constraints.

182

183

Args:

184

name: Rule name

185

rule: Rule dictionary with 'Assertions' and optional 'RuleCondition'

186

187

Raises:

188

ValueError: If duplicate rule name detected

189

"""

190

```

191

192

### Template Conversion

193

194

Convert templates to various output formats.

195

196

```python { .api }

197

def to_dict(self) -> Dict[str, Any]:

198

"""

199

Convert template to dictionary format.

200

201

Returns:

202

dict: Template as dictionary

203

"""

204

205

def to_json(self, indent: int = 1, sort_keys: bool = True,

206

separators: Tuple[str, str] = (",", ": ")) -> str:

207

"""

208

Convert template to JSON string.

209

210

Args:

211

indent: JSON indentation level

212

sort_keys: Whether to sort keys alphabetically

213

separators: JSON separators tuple

214

215

Returns:

216

str: Template as JSON string

217

"""

218

219

def to_yaml(self, clean_up: bool = False, long_form: bool = False,

220

sort_keys: bool = True) -> str:

221

"""

222

Convert template to YAML string.

223

224

Args:

225

clean_up: Whether to clean up CloudFormation-specific syntax

226

long_form: Whether to use long-form YAML syntax

227

sort_keys: Whether to sort keys alphabetically

228

229

Returns:

230

str: Template as YAML string

231

"""

232

```

233

234

### Template Limits

235

236

Constants defining CloudFormation template limits.

237

238

```python { .api }

239

MAX_RESOURCES: int = 500

240

MAX_PARAMETERS: int = 200

241

MAX_OUTPUTS: int = 200

242

MAX_MAPPINGS: int = 200

243

PARAMETER_TITLE_MAX: int = 255

244

```

245

246

## Usage Examples

247

248

### Basic Template Creation

249

250

```python

251

from troposphere import Template, Parameter, Output, Ref

252

from troposphere.ec2 import Instance

253

254

# Create template with description

255

template = Template(Description="My CloudFormation template")

256

257

# Add parameter

258

instance_type = template.add_parameter(Parameter(

259

"InstanceType",

260

Type="String",

261

Default="t2.micro",

262

AllowedValues=["t2.micro", "t2.small", "t2.medium"]

263

))

264

265

# Add resource

266

instance = template.add_resource(Instance(

267

"MyInstance",

268

ImageId="ami-0abcdef1234567890",

269

InstanceType=Ref(instance_type)

270

))

271

272

# Add output

273

template.add_output(Output(

274

"InstanceId",

275

Value=Ref(instance),

276

Description="EC2 Instance ID"

277

))

278

279

# Generate CloudFormation JSON

280

json_template = template.to_json()

281

yaml_template = template.to_yaml()

282

```

283

284

### Advanced Template with Conditions and Mappings

285

286

```python

287

from troposphere import Template, Parameter, Condition, If, Equals, FindInMap

288

from troposphere.ec2 import Instance

289

290

template = Template()

291

292

# Add parameter

293

environment = template.add_parameter(Parameter(

294

"Environment",

295

Type="String",

296

AllowedValues=["dev", "staging", "prod"]

297

))

298

299

# Add condition

300

template.add_condition("IsProduction", Equals(Ref(environment), "prod"))

301

302

# Add mapping

303

template.add_mapping("RegionMap", {

304

"us-east-1": {"AMI": "ami-0ff8a91507f77f867"},

305

"us-west-2": {"AMI": "ami-0bdf93799014acdc4"}

306

})

307

308

# Add conditional resource

309

instance = template.add_resource(Instance(

310

"MyInstance",

311

ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),

312

InstanceType=If("IsProduction", "m5.large", "t2.micro")

313

))

314

```

315

316

### Template with Parameter Groups

317

318

```python

319

from troposphere import Template, Parameter

320

321

template = Template()

322

323

# Add parameters

324

vpc_id = template.add_parameter(Parameter(

325

"VpcId",

326

Type="AWS::EC2::VPC::Id",

327

Description="VPC ID for resources"

328

))

329

330

subnet_id = template.add_parameter(Parameter(

331

"SubnetId",

332

Type="AWS::EC2::Subnet::Id",

333

Description="Subnet ID for instance"

334

))

335

336

# Group parameters

337

template.add_parameter_to_group(vpc_id, "Network Configuration")

338

template.add_parameter_to_group(subnet_id, "Network Configuration")

339

340

# Set parameter labels

341

template.set_parameter_label(vpc_id, "VPC")

342

template.set_parameter_label(subnet_id, "Subnet")

343

```