June 20-22 Announcing HashiConf Europe full schedule: keynotes, sessions, labs & more Register Now
  • Overview
    • Enforce Policy as Code
    • Infrastructure as Code
    • Inject Secrets into Terraform
    • Integrate with Existing Workflows
    • Manage Kubernetes
    • Manage Network Infrastructure
    • Manage Virtual Machine Images
    • Multi-Cloud Deployment
    • Terraform CLI
    • Terraform Cloud
    • Terraform Enterprise
  • Registry
  • Tutorials
    • About the Docs
    • Intro to Terraform
    • Configuration Language
    • Terraform CLI
    • Terraform Cloud
    • Terraform Enterprise
    • Provider Use
    • Plugin Development
    • Registry Publishing
    • Integration Program
    • Terraform Tools
    • CDK for Terraform
    • Glossary
  • Community
GitHubTerraform Cloud
Download

    Terraform Language

  • Overview
  • Attributes as Blocks - Configuration Language
  • Terraform v1.0 Compatibility Promises
    • Overview
    • Override Files
    • Dependency Lock File
    • Overview
    • Configuration Syntax
    • JSON Configuration Syntax
    • Style Conventions
    • Overview
    • Resource Blocks
    • Resource Behavior
      • depends_on
      • count
      • for_each
      • provider
      • lifecycle
      • Declaring Provisioners
      • Provisioner Connections
      • Provisioners Without a Resource
      • file
      • local-exec
      • remote-exec

      • chef
      • habitat
      • puppet
      • salt-masterless
  • Data Sources
    • count
    • depends_on
    • for_each
    • lifecycle
    • providers
    • provider
    • Overview
    • Provider Configuration
    • Provider Requirements
    • Dependency Lock File
    • Overview
    • Input Variables
    • Output Values
    • Local Values
    • Overview
    • Module Blocks
    • Module Sources
      • providers
      • depends_on
      • count
      • for_each
      • Overview
      • Standard Module Structure
      • Providers Within Modules
      • Best Practices: Module Composition
      • Publishing Modules
      • Refactoring Modules
    • Module Testing Experiment
    • Overview
    • Types and Values
    • Strings and Templates
    • References to Values
    • Operators
    • Function Calls
    • Conditional Expressions
    • For Expressions
    • Splat Expressions
    • Dynamic Blocks
    • Custom Condition Checks
    • Type Constraints
    • Version Constraints
    • Overview
      • abs
      • ceil
      • floor
      • log
      • max
      • min
      • parseint
      • pow
      • signum
      • chomp
      • format
      • formatlist
      • indent
      • join
      • lower
      • regex
      • regexall
      • replace
      • split
      • strrev
      • substr
      • title
      • trim
      • trimprefix
      • trimsuffix
      • trimspace
      • upper
      • alltrue
      • anytrue
      • chunklist
      • coalesce
      • coalescelist
      • compact
      • concat
      • contains
      • distinct
      • element
      • flatten
      • index
      • keys
      • length
      • list
      • lookup
      • map
      • matchkeys
      • merge
      • one
      • range
      • reverse
      • setintersection
      • setproduct
      • setsubtract
      • setunion
      • slice
      • sort
      • sum
      • transpose
      • values
      • zipmap
      • base64decode
      • base64encode
      • base64gzip
      • csvdecode
      • jsondecode
      • jsonencode
      • textdecodebase64
      • textencodebase64
      • urlencode
      • yamldecode
      • yamlencode
      • abspath
      • dirname
      • pathexpand
      • basename
      • file
      • fileexists
      • fileset
      • filebase64
      • templatefile
      • formatdate
      • timeadd
      • timestamp
      • base64sha256
      • base64sha512
      • bcrypt
      • filebase64sha256
      • filebase64sha512
      • filemd5
      • filesha1
      • filesha256
      • filesha512
      • md5
      • rsadecrypt
      • sha1
      • sha256
      • sha512
      • uuid
      • uuidv5
      • cidrhost
      • cidrnetmask
      • cidrsubnet
      • cidrsubnets
      • can
      • defaults
      • nonsensitive
      • sensitive
      • tobool
      • tolist
      • tomap
      • tonumber
      • toset
      • tostring
      • try
      • type
    • abs
    • abspath
    • alltrue
    • anytrue
    • base64decode
    • base64encode
    • base64gzip
    • base64sha256
    • base64sha512
    • basename
    • bcrypt
    • can
    • ceil
    • chomp
    • chunklist
    • cidrhost
    • cidrnetmask
    • cidrsubnet
    • cidrsubnets
    • coalesce
    • coalescelist
    • compact
    • concat
    • contains
    • csvdecode
    • defaults
    • dirname
    • distinct
    • element
    • file
    • filebase64
    • filebase64sha256
    • filebase64sha512
    • fileexists
    • filemd5
    • fileset
    • filesha1
    • filesha256
    • filesha512
    • flatten
    • floor
    • format
    • formatdate
    • formatlist
    • indent
    • index
    • join
    • jsondecode
    • jsonencode
    • keys
    • length
    • list
    • log
    • lookup
    • lower
    • map
    • matchkeys
    • max
    • md5
    • merge
    • min
    • nonsensitive
    • one
    • parseint
    • pathexpand
    • pow
    • range
    • regex
    • regexall
    • replace
    • reverse
    • rsadecrypt
    • sensitive
    • setintersection
    • setproduct
    • setsubtract
    • setunion
    • sha1
    • sha256
    • sha512
    • signum
    • slice
    • sort
    • split
    • strrev
    • substr
    • sum
    • templatefile
    • textdecodebase64
    • textencodebase64
    • timeadd
    • timestamp
    • title
    • tobool
    • tolist
    • tomap
    • tonumber
    • toset
    • tostring
    • transpose
    • trim
    • trimprefix
    • trimspace
    • trimsuffix
    • try
    • type
    • upper
    • urlencode
    • uuid
    • uuidv5
    • values
    • yamldecode
    • yamlencode
    • zipmap
    • Overview
    • Terraform Cloud
      • Overview
      • Backend Configuration
        • local
        • remote
        • artifactory
        • azurerm
        • consul
        • cos
        • etcd
        • etcdv3
        • gcs
        • http
        • Kubernetes
        • manta
        • oss
        • pg
        • s3
        • swift
      • local
      • remote
      • artifactory
      • azurerm
      • consul
      • cos
      • etcd
      • etcdv3
      • gcs
      • http
      • Kubernetes
      • manta
      • oss
      • pg
      • s3
      • swift
    • Overview
    • Purpose
    • The terraform_remote_state Data Source
    • Backends: State Storage and Locking
    • Import Existing Resources
    • Locking
    • Workspaces
    • Remote State
    • Sensitive Data
    • Overview
    • Upgrading to Terraform v1.2
    • Upgrading to Terraform v1.1
    • Upgrading to Terraform v1.0
    • v1.0 Compatibility Promises
    • Upgrading to Terraform v0.15
    • Upgrading to Terraform v0.14
    • Upgrading to Terraform v0.13
    • Upgrading to Terraform v0.12
    • Upgrading to Terraform v0.11
    • Upgrading to Terraform v0.10
    • Upgrading to Terraform v0.9
    • Upgrading to Terraform v0.8
    • Upgrading to Terraform v0.7
    • Overview
    • Load Order and Semantics
    • Configuration Syntax
    • Interpolation Syntax
    • Overrides
    • Resources
    • Data Sources
    • Providers
    • Variables
    • Outputs
    • Local Values
    • Modules
    • Terraform
    • Provisioners
    • Providers
    • Terraform Push (deprecated)
    • Environment Variables
  • Other Docs

  • Intro to Terraform
  • Configuration Language
  • Terraform CLI
  • Terraform Cloud
  • Terraform Enterprise
  • Provider Use
  • Plugin Development
  • Registry Publishing
  • Integration Program
  • Terraform Tools
  • CDK for Terraform
  • Glossary
Type '/' to Search

»try Function

try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.

This is a special function that is able to catch errors produced when evaluating its arguments, which is particularly useful when working with complex data structures whose shape is not well-known at implementation time.

For example, if some data is retrieved from an external system in JSON or YAML format and then decoded, the result may have attributes that are not guaranteed to be set. We can use try to produce a normalized data structure which has a predictable type that can therefore be used more conveniently elsewhere in the configuration:

locals {
  raw_value = yamldecode(file("${path.module}/example.yaml"))
  normalized_value = {
    name   = tostring(try(local.raw_value.name, null))
    groups = try(local.raw_value.groups, [])
  }
}
locals {
  raw_value = yamldecode(file("${path.module}/example.yaml"))
  normalized_value = {
    name   = tostring(try(local.raw_value.name, null))
    groups = try(local.raw_value.groups, [])
  }
}

With the above local value expressions, configuration elsewhere in the module can refer to local.normalized_value attributes without the need to repeatedly check for and handle absent attributes that would otherwise produce errors.

We can also use try to deal with situations where a value might be provided in two different forms, allowing us to normalize to the most general form:

variable "example" {
  type = any
}

locals {
  example = try(
    [tostring(var.example)],
    tolist(var.example),
  )
}
variable "example" {
  type = any
}

locals {
  example = try(
    [tostring(var.example)],
    tolist(var.example),
  )
}

The above permits var.example to be either a list or a single string. If it's a single string then it'll be normalized to a single-element list containing that string, again allowing expressions elsewhere in the configuration to just assume that local.example is always a list.

This second example contains two expressions that can both potentially fail. For example, if var.example were set to {} then it could be converted to neither a string nor a list. If try exhausts all of the given expressions without any succeeding, it will return an error describing all of the problems it encountered.

We strongly suggest using try only in special local values whose expressions perform normalization, so that the error handling is confined to a single location in the module and the rest of the module can just use straightforward references to the normalized structure and thus be more readable for future maintainers.

The try function can only catch and handle dynamic errors resulting from access to data that isn't known until runtime. It will not catch errors relating to expressions that can be proven to be invalid for any input, such as a malformed resource reference.

Warning: The try function is intended only for concise testing of the presence of and types of object attributes. Although it can technically accept any sort of expression, we recommend using it only with simple attribute references and type conversion functions as shown in the examples above. Overuse of try to suppress errors will lead to a configuration that is hard to understand and maintain.

»Examples

> local.foo
{
  "bar" = "baz"
}
> try(local.foo.bar, "fallback")
baz
> try(local.foo.boop, "fallback")
fallback
> local.foo
{
  "bar" = "baz"
}
> try(local.foo.bar, "fallback")
baz
> try(local.foo.boop, "fallback")
fallback

The try function will not catch errors relating to constructs that are provably invalid even before dynamic expression evaluation, such as a malformed reference or a reference to a top-level object that has not been declared:

> try(local.nonexist, "fallback")

Error: Reference to undeclared local value

A local value with the name "nonexist" has not been declared.
> try(local.nonexist, "fallback")

Error: Reference to undeclared local value

A local value with the name "nonexist" has not been declared.

»Related Functions

  • can, which tries evaluating an expression and returns a boolean value indicating whether it succeeded.
github logoEdit this page
  • Overview
  • Docs
  • Extend
  • Privacy
  • Security
  • Press Kit
  • Consent Manager