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

intrinsic-functions.mddocs/

0

# CloudFormation Intrinsic Functions

1

2

Complete implementation of CloudFormation intrinsic functions for references, string manipulation, conditionals, and data transformation within templates. All intrinsic functions inherit from AWSHelperFn and provide JSON serialization.

3

4

## Capabilities

5

6

### Base Intrinsic Function Class

7

8

Base class for all CloudFormation intrinsic functions with common functionality.

9

10

```python { .api }

11

class AWSHelperFn:

12

def __init__(self):

13

"""Base class for CloudFormation intrinsic functions."""

14

15

def to_dict(self) -> Any:

16

"""

17

Convert function to dictionary format.

18

19

Returns:

20

Dictionary representation of the function

21

"""

22

23

def to_json(self, indent: int = 4, sort_keys: bool = True) -> str:

24

"""

25

Convert function to JSON string.

26

27

Args:

28

indent: JSON indentation

29

sort_keys: Whether to sort keys

30

31

Returns:

32

str: JSON representation

33

"""

34

35

def getdata(self, data: object) -> Any:

36

"""

37

Extract data from objects, handling BaseAWSObject references.

38

39

Args:

40

data: Input data

41

42

Returns:

43

Processed data (resource title for BaseAWSObject instances)

44

"""

45

```

46

47

### Reference Functions

48

49

Functions for referencing resources, parameters, and resource attributes.

50

51

```python { .api }

52

class Ref(AWSHelperFn):

53

def __init__(self, data: object):

54

"""

55

Reference to a resource or parameter.

56

57

Args:

58

data: Resource, parameter, or pseudo parameter to reference

59

60

Example:

61

Ref("MyParameter")

62

Ref(my_resource)

63

"""

64

65

class GetAtt(AWSHelperFn):

66

def __init__(self, logicalName: object, attrName: object):

67

"""

68

Get attribute value from a resource.

69

70

Args:

71

logicalName: Resource logical name or resource object

72

attrName: Attribute name to retrieve

73

74

Example:

75

GetAtt("MyInstance", "PublicIp")

76

GetAtt(my_instance, "PrivateDnsName")

77

"""

78

79

class ImportValue(AWSHelperFn):

80

def __init__(self, data: object):

81

"""

82

Import value from cross-stack export.

83

84

Args:

85

data: Export name to import

86

87

Example:

88

ImportValue("NetworkStack-VPC-ID")

89

ImportValue(Sub("${NetworkStack}-VPC-ID"))

90

"""

91

```

92

93

### String Functions

94

95

Functions for string manipulation and transformation.

96

97

```python { .api }

98

class Join(AWSHelperFn):

99

def __init__(self, delimiter: object, values: object):

100

"""

101

Join list of values with delimiter.

102

103

Args:

104

delimiter: String delimiter

105

values: List of values to join

106

107

Example:

108

Join("", ["https://", GetAtt("MyBucket", "DomainName")])

109

Join(",", ["value1", "value2", "value3"])

110

"""

111

112

class Sub(AWSHelperFn):

113

def __init__(self, input_str: object, dict_values: Optional[Dict[str, Any]] = None, **values):

114

"""

115

Substitute variables in string template.

116

117

Args:

118

input_str: String template with ${variable} placeholders

119

dict_values: Dictionary of variable substitutions

120

**values: Keyword argument substitutions

121

122

Example:

123

Sub("Hello ${name}!", {"name": "World"})

124

Sub("arn:aws:s3:::${bucket}/*", bucket=Ref("MyBucket"))

125

Sub("${AWS::StackName}-resource")

126

"""

127

128

class Split(AWSHelperFn):

129

def __init__(self, delimiter: object, values: object):

130

"""

131

Split string by delimiter into list.

132

133

Args:

134

delimiter: String delimiter

135

values: String to split

136

137

Example:

138

Split(",", "a,b,c") # Returns ["a", "b", "c"]

139

Split(":", ImportValue("MyStack-AZ-List"))

140

"""

141

142

class Base64(AWSHelperFn):

143

def __init__(self, data: Any):

144

"""

145

Encode string as Base64.

146

147

Args:

148

data: String or function to encode

149

150

Example:

151

Base64("Hello World")

152

Base64(Sub("#!/bin/bash\necho ${Message}", Message="Hello"))

153

"""

154

```

155

156

### Selection and Lookup Functions

157

158

Functions for selecting values from lists and looking up values in mappings.

159

160

```python { .api }

161

class Select(AWSHelperFn):

162

def __init__(self, indx: object, objects: object):

163

"""

164

Select item from list by index.

165

166

Args:

167

indx: Index (0-based) to select

168

objects: List to select from

169

170

Example:

171

Select(0, GetAZs()) # First availability zone

172

Select(1, Split(",", "a,b,c")) # Returns "b"

173

"""

174

175

class FindInMap(AWSHelperFn):

176

def __init__(self, mapname: object, toplevelkey: object, secondlevelkey: object,

177

defaultvalue: Optional[object] = None):

178

"""

179

Look up value in mapping.

180

181

Args:

182

mapname: Mapping name

183

toplevelkey: Top-level key

184

secondlevelkey: Second-level key

185

defaultvalue: Default value if key not found

186

187

Example:

188

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

189

FindInMap("InstanceTypeMap", Ref("Environment"), "InstanceType", "t2.micro")

190

"""

191

```

192

193

### Conditional Functions

194

195

Functions for conditional logic and boolean operations.

196

197

```python { .api }

198

class If(AWSHelperFn):

199

def __init__(self, cond: object, true: object, false: object):

200

"""

201

Conditional selection between two values.

202

203

Args:

204

cond: Condition name to evaluate

205

true: Value if condition is true

206

false: Value if condition is false

207

208

Example:

209

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

210

If("CreateBucket", Ref("MyBucket"), Ref("AWS::NoValue"))

211

"""

212

213

class Condition(AWSHelperFn):

214

def __init__(self, data: object):

215

"""

216

Reference to a template condition.

217

218

Args:

219

data: Condition name

220

221

Example:

222

Condition("IsProduction")

223

"""

224

225

class Equals(AWSHelperFn):

226

def __init__(self, value_one: object, value_two: object):

227

"""

228

Compare two values for equality.

229

230

Args:

231

value_one: First value

232

value_two: Second value

233

234

Example:

235

Equals(Ref("Environment"), "production")

236

Equals(Ref("AWS::Region"), "us-east-1")

237

"""

238

239

class And(AWSHelperFn):

240

def __init__(self, cond_one: object, cond_two: object, *conds: object):

241

"""

242

Logical AND operation on conditions.

243

244

Args:

245

cond_one: First condition

246

cond_two: Second condition

247

*conds: Additional conditions

248

249

Example:

250

And(Equals(Ref("Environment"), "prod"), Equals(Ref("CreateBackup"), "true"))

251

"""

252

253

class Or(AWSHelperFn):

254

def __init__(self, cond_one: object, cond_two: object, *conds: object):

255

"""

256

Logical OR operation on conditions.

257

258

Args:

259

cond_one: First condition

260

cond_two: Second condition

261

*conds: Additional conditions

262

263

Example:

264

Or(Equals(Ref("Environment"), "dev"), Equals(Ref("Environment"), "test"))

265

"""

266

267

class Not(AWSHelperFn):

268

def __init__(self, cond: object):

269

"""

270

Logical NOT operation on condition.

271

272

Args:

273

cond: Condition to negate

274

275

Example:

276

Not(Equals(Ref("Environment"), "production"))

277

"""

278

```

279

280

### AWS-Specific Functions

281

282

Functions that interact with AWS services and infrastructure.

283

284

```python { .api }

285

class GetAZs(AWSHelperFn):

286

def __init__(self, region: object = ""):

287

"""

288

Get availability zones for region.

289

290

Args:

291

region: Region name (empty string for current region)

292

293

Example:

294

GetAZs() # Current region AZs

295

GetAZs("us-west-2") # Specific region AZs

296

"""

297

298

class Cidr(AWSHelperFn):

299

def __init__(self, ipblock: object, count: object, sizemask: Optional[object] = None):

300

"""

301

Generate CIDR blocks from IP block.

302

303

Args:

304

ipblock: IP block in CIDR notation

305

count: Number of subnets to create

306

sizemask: Subnet mask size (default: depends on count)

307

308

Example:

309

Cidr("10.0.0.0/16", 6, 8) # 6 subnets with /24 masks

310

Cidr(GetAtt("MyVPC", "CidrBlock"), 2)

311

"""

312

```

313

314

### Pseudo Parameters

315

316

Pre-defined Ref objects for AWS pseudo parameters.

317

318

```python { .api }

319

# Pseudo Parameter Constants

320

AWS_ACCOUNT_ID: str = "AWS::AccountId"

321

AWS_NOTIFICATION_ARNS: str = "AWS::NotificationARNs"

322

AWS_NO_VALUE: str = "AWS::NoValue"

323

AWS_PARTITION: str = "AWS::Partition"

324

AWS_REGION: str = "AWS::Region"

325

AWS_STACK_ID: str = "AWS::StackId"

326

AWS_STACK_NAME: str = "AWS::StackName"

327

AWS_URL_SUFFIX: str = "AWS::URLSuffix"

328

329

# Pre-defined Ref Objects

330

AccountId: Ref = Ref(AWS_ACCOUNT_ID)

331

NotificationARNs: Ref = Ref(AWS_NOTIFICATION_ARNS)

332

NoValue: Ref = Ref(AWS_NO_VALUE)

333

Partition: Ref = Ref(AWS_PARTITION)

334

Region: Ref = Ref(AWS_REGION)

335

StackId: Ref = Ref(AWS_STACK_ID)

336

StackName: Ref = Ref(AWS_STACK_NAME)

337

URLSuffix: Ref = Ref(AWS_URL_SUFFIX)

338

```

339

340

## Usage Examples

341

342

### Basic References

343

344

```python

345

from troposphere import Template, Parameter, Ref, GetAtt

346

from troposphere.ec2 import Instance

347

348

template = Template()

349

350

# Parameter reference

351

instance_type = template.add_parameter(Parameter(

352

"InstanceType",

353

Type="String",

354

Default="t2.micro"

355

))

356

357

# Resource creation with parameter reference

358

instance = template.add_resource(Instance(

359

"MyInstance",

360

ImageId="ami-0abcdef1234567890",

361

InstanceType=Ref(instance_type) # Reference parameter

362

))

363

364

# Get resource attribute

365

public_ip = GetAtt(instance, "PublicIp")

366

```

367

368

### String Manipulation

369

370

```python

371

from troposphere import Join, Sub, Split, Base64

372

from troposphere.ec2 import Instance

373

374

# Join strings

375

url = Join("", [

376

"https://",

377

GetAtt("MyLoadBalancer", "DNSName"),

378

"/api"

379

])

380

381

# String substitution

382

user_data = Sub("""#!/bin/bash

383

echo "Stack: ${AWS::StackName}" >> /var/log/info.log

384

echo "Region: ${AWS::Region}" >> /var/log/info.log

385

echo "Custom: ${Message}" >> /var/log/info.log

386

""", Message="Hello World")

387

388

# Base64 encoding for user data

389

instance = Instance(

390

"MyInstance",

391

UserData=Base64(user_data),

392

# ... other properties

393

)

394

395

# Split string

396

availability_zones = Split(",", "us-east-1a,us-east-1b,us-east-1c")

397

first_az = Select(0, availability_zones)

398

```

399

400

### Conditionals and Logic

401

402

```python

403

from troposphere import Template, Parameter, Condition, If, Equals, And, Or, Not

404

405

template = Template()

406

407

# Parameters

408

environment = template.add_parameter(Parameter(

409

"Environment",

410

Type="String",

411

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

412

))

413

414

backup_enabled = template.add_parameter(Parameter(

415

"BackupEnabled",

416

Type="String",

417

AllowedValues=["true", "false"],

418

Default="false"

419

))

420

421

# Conditions

422

template.add_condition("IsProduction",

423

Equals(Ref(environment), "prod"))

424

425

template.add_condition("IsNotDev",

426

Not(Equals(Ref(environment), "dev")))

427

428

template.add_condition("ProdWithBackup",

429

And(

430

Equals(Ref(environment), "prod"),

431

Equals(Ref(backup_enabled), "true")

432

))

433

434

template.add_condition("DevOrStaging",

435

Or(

436

Equals(Ref(environment), "dev"),

437

Equals(Ref(environment), "staging")

438

))

439

440

# Conditional resource properties

441

instance = Instance(

442

"MyInstance",

443

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

444

Monitoring=If("ProdWithBackup", True, False)

445

)

446

```

447

448

### Mappings and Lookups

449

450

```python

451

from troposphere import Template, FindInMap, Select, GetAZs

452

453

template = Template()

454

455

# Add mapping

456

template.add_mapping("RegionMap", {

457

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

458

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

459

"eu-west-1": {"AMI": "ami-047bb4163c506cd98"}

460

})

461

462

# Use mapping lookup

463

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

464

465

# Select from availability zones

466

first_az = Select(0, GetAZs())

467

second_az = Select(1, GetAZs())

468

469

# Use in resources

470

instance = Instance(

471

"MyInstance",

472

ImageId=ami_id,

473

AvailabilityZone=first_az,

474

InstanceType="t2.micro"

475

)

476

```

477

478

### Advanced Function Combinations

479

480

```python

481

from troposphere import *

482

from troposphere.s3 import Bucket

483

from troposphere.cloudfront import Distribution

484

485

# Complex string building with multiple functions

486

bucket_domain = GetAtt("MyBucket", "RegionalDomainName")

487

488

origin_domain = If("UseCloudFront",

489

GetAtt("MyDistribution", "DomainName"),

490

bucket_domain

491

)

492

493

api_url = Join("", [

494

"https://",

495

origin_domain,

496

"/api/",

497

Ref("AWS::StackName"),

498

"/",

499

Select(0, Split("-", Ref("AWS::AccountId")))

500

])

501

502

# User data with complex substitution

503

user_data_script = Sub("""#!/bin/bash

504

export STACK_NAME="${AWS::StackName}"

505

export REGION="${AWS::Region}"

506

export ACCOUNT_ID="${AWS::AccountId}"

507

export API_URL="${ApiUrl}"

508

export BUCKET_NAME="${BucketName}"

509

510

# Download from S3

511

aws s3 cp s3://${BucketName}/scripts/setup.sh /tmp/setup.sh

512

chmod +x /tmp/setup.sh

513

/tmp/setup.sh

514

""", {

515

"ApiUrl": api_url,

516

"BucketName": Ref("MyBucket")

517

})

518

```