================ CODE SNIPPETS ================ TITLE: Sample Response: List Available Terraform Provider Installation Packages (JSON) DESCRIPTION: An example JSON response showing the structure returned by the API when successfully listing available installation packages for a Terraform provider version. It includes an 'archives' object with OS/architecture specific download details. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/provider-network-mirror-protocol.mdx#_snippet_7 LANGUAGE: json CODE: ``` { "archives": { "darwin_amd64": { "url": "terraform-provider-random_2.0.0_darwin_amd64.zip", "hashes": [ "h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs=" ] }, "linux_amd64": { "url": "terraform-provider-random_2.0.0_linux_amd64.zip", "hashes": [ "h1:lCJCxf/LIowc2IGS9TPjWDyXY4nOmdGdfcwwDQCOURQ=" ] } } } ``` -------------------------------- TITLE: Sample Request: List Available Terraform Provider Installation Packages (curl) DESCRIPTION: An example `curl` command demonstrating how to query the network mirror API to list available installation packages for a specific version (2.0.0) of the 'random' provider. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/provider-network-mirror-protocol.mdx#_snippet_6 LANGUAGE: shell CODE: ``` curl 'https://terraform.example.com/providers/registry.terraform.io/hashicorp/random/2.0.0.json' ``` -------------------------------- TITLE: Configure Terraform Provider Installation with Mirror and Direct Methods DESCRIPTION: This HCL example demonstrates how to set up a `provider_installation` block in Terraform's CLI configuration. It shows a `filesystem_mirror` for specific providers and a `direct` method for others, using `include` and `exclude` patterns to define applicability. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/config/config-file.mdx#_snippet_3 LANGUAGE: HCL CODE: ``` provider_installation { filesystem_mirror { path = "/usr/share/terraform/providers" include = ["example.com/*/*"] } direct { exclude = ["example.com/*/*"] } } ``` -------------------------------- TITLE: Terraform UI provision_start Message Hook JSON Example DESCRIPTION: Example JSON payload for the `provision_start` message hook, indicating the beginning of a provisioning step with a 'local-exec' provisioner. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_20 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "null_resource.none[0]: Provisioning with 'local-exec'...", "@module": "terraform.ui", "@timestamp": "2021-03-26T16:38:43.997431-04:00", "hook": { "resource": { "addr": "null_resource.none[0]", "module": "", "resource": "null_resource.none[0]", "implied_provider": "null", "resource_type": "null_resource", "resource_name": "none", "resource_key": 0 }, "provisioner": "local-exec" }, "type": "provision_start" } ``` -------------------------------- TITLE: Example Terraform Main Configuration with Module and Resource DESCRIPTION: This `main.tf` configuration demonstrates a typical Terraform setup, including provider requirements, a module call, and a local file resource. The `module.credentials` reads data from an S3 bucket, and `local_file.credentials_json` then uses this data to create a local file, showcasing inter-resource dependencies. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/tests/mocking.mdx#_snippet_6 LANGUAGE: hcl CODE: ``` # main.tf terraform { required_providers { aws = { source = "hashicorp/aws" } } } module "credentials" { source = "./modules/s3_data" data_bucket_name = "my_company_bucket_name" } resource "local_file" "credentials_json" { filename = "credentials.json" content = jsonencode(module.credentials.data) } ``` -------------------------------- TITLE: Terraform UI apply_start Message Hook JSON Example DESCRIPTION: Example JSON payload for the `apply_start` message hook, showing an `info` level message for a resource creation event. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_12 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "random_pet.animal: Creating...", "@module": "terraform.ui", "@timestamp": "2021-05-25T13:32:41.825308-04:00", "hook": { "resource": { "addr": "random_pet.animal", "module": "", "resource": "random_pet.animal", "implied_provider": "random", "resource_type": "random_pet", "resource_name": "animal", "resource_key": null }, "action": "create" }, "type": "apply_start" } ``` -------------------------------- TITLE: HCL formatlist Function Usage Examples DESCRIPTION: These examples demonstrate how to use the `formatlist` function in HCL. The first example formats a list of names with a simple greeting. The second example shows how to combine a non-list argument with a list argument to produce a formatted list of strings. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/formatlist.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > formatlist("Hello, %s!", ["Valentina", "Ander", "Olivia", "Sam"]) [ "Hello, Valentina!", "Hello, Ander!", "Hello, Olivia!", "Hello, Sam!", ] > formatlist("%s, %s!", "Salutations", ["Valentina", "Ander", "Olivia", "Sam"]) [ "Salutations, Valentina!", "Salutations, Ander!", "Salutations, Olivia!", "Salutations, Sam!", ] ``` -------------------------------- TITLE: Example cURL Request to Find Provider Package DESCRIPTION: Demonstrates how to make an HTTP GET request using cURL to retrieve a provider package's metadata and download URL. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/provider-registry-protocol.mdx#_snippet_6 LANGUAGE: bash CODE: ``` curl 'https://registry.terraform.io/v1/providers/hashicorp/random/2.0.0/download/linux/amd64' ``` -------------------------------- TITLE: Credentials Helper 'get' Command Example DESCRIPTION: Illustrates how Terraform invokes a credentials helper with the 'get' verb to retrieve credentials for a specific hostname. The helper is expected to print a JSON credentials object to stdout. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/credentials-helpers.mdx#_snippet_2 LANGUAGE: Shell CODE: ``` terraform-credentials-credstore --host=credstore.example.com get app.terraform.io ``` -------------------------------- TITLE: Example AWS Network Topology with Terraform DESCRIPTION: This comprehensive example demonstrates a simple AWS network topology using Terraform. It showcases the use of the `terraform` block for provider requirements, `variable` definitions, `provider` configuration, and `resource` blocks for creating a VPC and multiple subnets. The example also illustrates variable referencing, resource dependencies, and built-in functions like `cidrsubnet` for dynamic value generation. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/index.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 1.0.4" } } } variable "aws_region" {} variable "base_cidr_block" { description = "A /16 CIDR range definition, such as 10.1.0.0/16, that the VPC will use" default = "10.1.0.0/16" } variable "availability_zones" { description = "A list of availability zones in which to create subnets" type = list(string) } provider "aws" { region = var.aws_region } resource "aws_vpc" "main" { # Referencing the base_cidr_block variable allows the network address # to be changed without modifying the configuration. cidr_block = var.base_cidr_block } resource "aws_subnet" "az" { # Create one subnet for each given availability zone. count = length(var.availability_zones) # For each subnet, use one of the specified availability zones. availability_zone = var.availability_zones[count.index] # By referencing the aws_vpc.main object, Terraform knows that the subnet # must be created only after the VPC is created. vpc_id = aws_vpc.main.id # Built-in functions and operators can be used for simple transformations of # values, such as computing a subnet address. Here we create a /20 prefix for # each subnet, using consecutive addresses for each availability zone, # such as 10.1.16.0/20 . cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 4, count.index+1) } ``` -------------------------------- TITLE: Terraform Provider Installation Methods API DESCRIPTION: This section documents the available methods for configuring Terraform provider installation within the `provider_installation` block. It outlines the `direct`, `filesystem_mirror`, and `network_mirror` methods, detailing their purpose, required arguments, and expected behavior. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/config/config-file.mdx#_snippet_4 LANGUAGE: APIDOC CODE: ``` provider_installation: methods: direct: description: Requests provider information directly from its origin registry and downloads over the network. arguments: None filesystem_mirror: description: Consults a local directory for provider copies. arguments: path: type: string required: true description: The directory path to look for provider copies. layouts_supported: - Packed: "HOSTNAME/NAMESPACE/TYPE/terraform-provider-TYPE_VERSION_TARGET.zip" - Unpacked: "HOSTNAME/NAMESPACE/TYPE/VERSION/TARGET" note: "Terraform attempts to create a symbolic link to the mirror directory for unpacked layouts." network_mirror: description: Consults a particular HTTPS server for provider copies, regardless of registry host. arguments: url: type: string required: true description: The base URL for the network mirror, must use 'https:' scheme and end with a trailing slash. Expected to implement the provider network mirror protocol. ``` -------------------------------- TITLE: Initialize Terraform Project and Configuration DESCRIPTION: This snippet demonstrates the initial steps to set up a Terraform project. It includes creating a Git repository, authoring the initial 'main.tf' configuration file, and initializing Terraform to download necessary provider plugins. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/intro/core-workflow.mdx#_snippet_0 LANGUAGE: sh CODE: ``` # Create repository $ git init my-infra && cd my-infra Initialized empty Git repository in /.../my-infra/.git/ # Write initial config $ vim main.tf # Initialize Terraform $ terraform init Initializing provider plugins... # ... Terraform has been successfully initialized! ``` -------------------------------- TITLE: Show a Terraform Resource Configured with For_Each DESCRIPTION: This example shows how to display a specific instance of a resource, `packet_device.worker`, configured with the `for_each` meta-argument. It targets the instance identified by the key `"example"`. The command syntax varies slightly across different operating system shells due to quoting requirements for special characters. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/state/show.mdx#_snippet_3 LANGUAGE: shell CODE: ``` $ terraform state show 'packet_device.worker["example"]' ``` LANGUAGE: powershell CODE: ``` $ terraform state show 'packet_device.worker[\"example\"]' ``` LANGUAGE: cmd CODE: ``` $ terraform state show packet_device.worker[\"example\"] ``` -------------------------------- TITLE: Terraform CLI: get Command Usage and Options DESCRIPTION: Documents the `terraform get` command, its basic usage, and available options like `-update` and `-no-color` for managing module downloads and updates. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/get.mdx#_snippet_0 LANGUAGE: APIDOC CODE: ``` Command: terraform get Description: Downloads and updates modules mentioned in the root module. Usage: terraform get [options] Options: -update: If specified, modules that are already downloaded will be checked for updates and the updates will be downloaded if present. -no-color: Disable text coloring in the output. ``` -------------------------------- TITLE: Build and Launch Terraform Website Locally DESCRIPTION: This command navigates to the Terraform top-level directory and builds the documentation website locally. It allows contributors to preview all changes, including content from both the `terraform` and `terraform-website` repositories, before creating a pull request. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/README.md#_snippet_2 LANGUAGE: Makefile CODE: ``` make website ``` -------------------------------- TITLE: Display Complete Terraform Module Directory Structure with Nested Modules and Examples DESCRIPTION: This snippet illustrates a comprehensive Terraform module directory structure, including all optional elements. It demonstrates how to organize nested modules within a `modules/` directory and provide usage examples in an `examples/` directory, representing the most complex possible module organization. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/modules/develop/structure.mdx#_snippet_1 LANGUAGE: sh CODE: ``` $ tree complete-module/ . ├── README.md ├── main.tf ├── variables.tf ├── outputs.tf ├── ... ├── modules/ │   ├── nestedA/ │   │   ├── README.md │   │   ├── variables.tf │   │   ├── main.tf │   │   ├── outputs.tf │   ├── nestedB/ │   ├── .../ ├── examples/ │   ├── exampleA/ │   │   ├── main.tf │   ├── exampleB/ │   ├── .../ ``` -------------------------------- TITLE: Terraform HCL: `regexall` Practical Examples DESCRIPTION: Provides concrete examples of `regexall` in action, demonstrating how to extract all alphabetical sequences, count the number of matches, and use the function to check for the presence of a pattern within a string. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/regexall.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > regexall("[a-z]+", "1234abcd5678efgh9") [ "abcd", "efgh", ] > length(regexall("[a-z]+", "1234abcd5678efgh9")) 2 > length(regexall("[a-z]+", "123456789")) > 0 false ``` -------------------------------- TITLE: Example Terraform Test File Message JSON DESCRIPTION: A JSON example of a `test_file` message, showing a completed test file with a 'pass' status. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_31 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "main.tftest.hcl... pass", "@module": "terraform.ui", "@testfile": "validation.tftest.hcl", "@timestamp": "2023-08-09T16:12:30.724368+02:00", "test_file": { "path": "validation.tftest.hcl", "progress": "complete", "status": "pass" }, "type": "test_file" } ``` -------------------------------- TITLE: Example Terraform HCL Configuration for Console Testing DESCRIPTION: A sample `main.tf` configuration defining a map variable `apps` and a `random_pet` resource. This configuration serves as the context for interactive `terraform console` examples, allowing users to test expressions against defined variables and resources. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/console.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` variable "apps" { type = map(any) default = { "foo" = { "region" = "us-east-1", }, "bar" = { "region" = "eu-west-1", }, "baz" = { "region" = "ap-south-1", }, } } resource "random_pet" "example" { for_each = var.apps } ``` -------------------------------- TITLE: Demonstrate Basic `log` Function Usage in HCL DESCRIPTION: Shows practical examples of the `log` function with different numbers and bases, illustrating its output for common logarithmic calculations. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/log.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > log(50, 10) 1.6989700043360185 > log(16, 2) 4 ``` -------------------------------- TITLE: fileset Function Usage Examples DESCRIPTION: Illustrates various applications of the `fileset` function with different glob patterns and path specifications, demonstrating how it enumerates files and directories. Examples include matching specific file extensions, alternative names, and recursive directory traversal. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/fileset.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > fileset(path.module, "files/*.txt") [ "files/hello.txt", "files/world.txt", ] > fileset(path.module, "files/{hello,world}.txt") [ "files/hello.txt", "files/world.txt", ] > fileset("${path.module}/files", "*") [ "hello.txt", "world.txt", ] > fileset("${path.module}/files", "**") [ "hello.txt", "world.txt", "subdirectory/anotherfile.txt", ] ``` -------------------------------- TITLE: Example usage of slice function in HCL DESCRIPTION: This example demonstrates how to use the `slice` function in HCL to extract a sub-list. It shows the input list `["a", "b", "c", "d"]`, the start index `1`, and the end index `3`, resulting in `["b", "c"]`. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/slice.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > slice(["a", "b", "c", "d"], 1, 3) [ "b", "c", ] ``` -------------------------------- TITLE: HCL startswith Function Usage Examples DESCRIPTION: Illustrates the usage of the `startswith` function with various string and prefix combinations, demonstrating its boolean return values based on whether the string begins with the specified prefix. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/startswith.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > startswith("hello world", "hello") true > startswith("hello world", "world") false ``` -------------------------------- TITLE: Example Terraform Resource Object JSON DESCRIPTION: An example JSON representation of a `resource` object, showing a specific instance of a `random_pet` resource with its address, module, type, name, and key. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_27 LANGUAGE: json CODE: ``` { "addr": "module.pets.random_pet.pet[\"friend\"]", "module": "module.pets", "resource": "random_pet.pet[\"friend\"]", "implied_provider": "random", "resource_type": "random_pet", "resource_name": "pet", "resource_key": "friend" } ``` -------------------------------- TITLE: Create new Terraform workspace DESCRIPTION: Demonstrates how to create a new Terraform workspace named 'example' using the `terraform workspace new` command. This creates an empty workspace and switches to it. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/workspace/new.mdx#_snippet_1 LANGUAGE: Shell CODE: ``` $ terraform workspace new example Created and switched to workspace "example"! You're now on a new, empty workspace. Workspaces isolate their state, so if you run "terraform plan" Terraform will not see any existing state for this configuration. ``` -------------------------------- TITLE: Build terraform-bundle Executable from Source DESCRIPTION: Instructions to compile the `terraform-bundle` executable from the Terraform GitHub repository using Go, specifically targeting the v0.15 branch for compatibility with Terraform v0.13 and later. This process requires a working Go toolchain. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/tools/terraform-bundle/README.md#_snippet_0 LANGUAGE: Shell CODE: ``` git clone --single-branch --branch=v0.15 --depth=1 https://github.com/hashicorp/terraform.git cd terraform go build -o ../terraform-bundle ./tools/terraform-bundle ``` -------------------------------- TITLE: Basic Usage Examples for Terraform's signum Function DESCRIPTION: These examples illustrate the `signum` function's behavior when provided with negative, zero, and positive integer inputs, demonstrating its output of -1, 0, or 1 respectively. The examples are shown as console interactions. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/signum.mdx#_snippet_0 LANGUAGE: Console CODE: ``` > signum(-13) -1 > signum(0) 0 > signum(344) 1 ``` -------------------------------- TITLE: Terraform Console: `one` Function Examples with Lists and Sets DESCRIPTION: Provides interactive Terraform console examples demonstrating the `one` function's behavior with various inputs, including empty lists, single-element lists, and sets. It also illustrates the error messages generated when `one` is called with lists or sets containing two or more elements, emphasizing its strict input requirements. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/one.mdx#_snippet_2 LANGUAGE: Terraform Console CODE: ``` > one([]) null > one(["hello"]) "hello" > one(["hello", "goodbye"]) Error: Invalid function argument Invalid value for "list" parameter: must be a list, set, or tuple value with either zero or one elements. > one(toset([])) null > one(toset(["hello"])) "hello" > one(toset(["hello","goodbye"])) Error: Invalid function argument Invalid value for "list" parameter: must be a list, set, or tuple value with either zero or one elements. ``` -------------------------------- TITLE: uuidv5 Function Usage Examples DESCRIPTION: Practical examples demonstrating how to use the `uuidv5` function in Terraform, showcasing its application with predefined namespace keywords (DNS, URL, OID, X.500) and custom UUID namespaces. These examples illustrate how consistent UUIDs are generated for identical inputs, highlighting the function's deterministic nature. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/uuidv5.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` > uuidv5("dns", "www.terraform.io") a5008fae-b28c-5ba5-96cd-82b4c53552d6 > uuidv5("url", "https://www.terraform.io/") 9db6f67c-dd95-5ea0-aa5b-e70e5c5f7cf5 > uuidv5("oid", "1.3.6.1.4") af9d40a5-7a36-5c07-b23a-851cd99fbfa5 > uuidv5("x500", "CN=Example,C=GB") 84e09961-4aa4-57f8-95b7-03edb1073253 ``` LANGUAGE: HCL CODE: ``` > uuidv5("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "www.terraform.io") a5008fae-b28c-5ba5-96cd-82b4c53552d6 ``` LANGUAGE: HCL CODE: ``` > uuidv5("743ac3c0-3bf7-4a5b-9e6c-59360447c757", "LIBS:diskfont.library") ede1a974-df7e-5f17-84b9-76208818b2c8 ``` -------------------------------- TITLE: Terraform UI apply_complete Message Hook JSON Example DESCRIPTION: Example JSON payload for the `apply_complete` message hook, showing a successful resource creation with its ID and completion time. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_16 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "random_pet.animal: Creation complete after 0s [id=smart-lizard]", "@module": "terraform.ui", "@timestamp": "2021-05-25T13:32:41.826179-04:00", "hook": { "resource": { "addr": "random_pet.animal", "module": "", "resource": "random_pet.animal", "implied_provider": "random", "resource_type": "random_pet", "resource_name": "animal", "resource_key": null }, "action": "create", "id_key": "id", "id_value": "smart-lizard", "elapsed_seconds": 0 }, "type": "apply_complete" } ``` -------------------------------- TITLE: Terraform cidrhost Function Usage Examples DESCRIPTION: Provides concrete examples of the `cidrhost` function's usage, demonstrating how it calculates host IP addresses for both IPv4 and IPv6 CIDR prefixes with various host numbers. The examples illustrate both positive and negative `hostnum` values and their resulting IP addresses. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/cidrhost.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` > cidrhost("10.12.112.0/20", 16) 10.12.112.16 > cidrhost("10.12.112.0/20", 268) 10.12.113.12 > cidrhost("fd00:fd12:3456:7890:00a2::/72", 34) fd00:fd12:3456:7890::22 ``` -------------------------------- TITLE: Get Current Plan Timestamp (Console Example) DESCRIPTION: Demonstrates a simple invocation of the `plantimestamp()` function and its expected output in a console environment, showing a UTC timestamp in RFC 3339 format. This output represents the timestamp at the time of the plan operation. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/plantimestamp.mdx#_snippet_0 LANGUAGE: shell CODE: ``` > plantimestamp() 2018-05-13T07:44:12Z ``` -------------------------------- TITLE: Show `range` Function Output Examples in HCL DESCRIPTION: Provides various examples of the `range` function's output with different input parameters, including single argument, two arguments, three arguments, float steps, and negative steps, demonstrating its versatility. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/range.mdx#_snippet_2 LANGUAGE: hcl CODE: ``` > range(3) [ 0, 1, 2, ] > range(1, 4) [ 1, 2, 3, ] > range(1, 8, 2) [ 1, 3, 5, 7, ] > range(1, 4, 0.5) [ 1, 1.5, 2, 2.5, 3, 3.5, ] > range(4, 1) [ 4, 3, 2, ] > range(10, 5, -2) [ 10, 8, 6, ] ``` -------------------------------- TITLE: Get Keys from a Map using Terraform's `keys` Function DESCRIPTION: This example demonstrates the usage of the `keys` function in Terraform to extract all keys from a given map. The function processes the input map and returns its keys as a list, ensuring they are sorted in lexicographical order for consistent results. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/keys.mdx#_snippet_0 LANGUAGE: Console CODE: ``` > keys({a=1, c=2, d=3}) [ "a", "c", "d", ] ``` -------------------------------- TITLE: Terraform HCL File Provisioner Examples DESCRIPTION: Demonstrates various uses of the `file` provisioner in Terraform HCL to copy files, content strings, and directories to an AWS instance, illustrating different `source` and `destination` configurations. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/resources/provisioners/file.mdx#_snippet_0 LANGUAGE: hcl CODE: ``` resource "aws_instance" "web" { # ... # Copies the myapp.conf file to /etc/myapp.conf provisioner "file" { source = "conf/myapp.conf" destination = "/etc/myapp.conf" } # Copies the string in content into /tmp/file.log provisioner "file" { content = "ami used: ${self.ami}" destination = "/tmp/file.log" } # Copies the configs.d folder to /etc/configs.d provisioner "file" { source = "conf/configs.d" destination = "/etc" } # Copies all files and folders in apps/app1 to D:/IIS/webapp1 provisioner "file" { source = "apps/app1/" destination = "D:/IIS/webapp1" } } ``` -------------------------------- TITLE: Get Machine-Readable Terraform Provider Schema DESCRIPTION: Use this command to get machine-readable information about the resources and configuration options offered by each provider. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/plugins/index.mdx#_snippet_2 LANGUAGE: Shell CODE: ``` terraform providers schema ``` -------------------------------- TITLE: Select Terraform Workspace Example DESCRIPTION: Demonstrates listing existing Terraform workspaces and then selecting a specific one named 'default' using the `terraform workspace select` command. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/workspace/select.mdx#_snippet_0 LANGUAGE: Shell CODE: ``` $ terraform workspace list default * development jsmith-test $ terraform workspace select default Switched to workspace "default". ``` -------------------------------- TITLE: Show Installed Terraform Provider Versions DESCRIPTION: Use this command to show the specific provider versions installed for the current working directory. `terraform -version` is an alias that provides similar information. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/plugins/index.mdx#_snippet_1 LANGUAGE: Shell CODE: ``` terraform version ``` -------------------------------- TITLE: Example Input Variables for Network and Subnet Data DESCRIPTION: Provides concrete example values for the `networks` and `subnets` variables. This input data demonstrates the structure expected by the Terraform configuration, with two networks ('a', 'b') and three subnets ('a', 'b', 'c') that will be combined. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/setproduct.mdx#_snippet_8 LANGUAGE: HCL CODE: ``` networks = { a = { base_cidr_block = "10.1.0.0/16" } b = { base_cidr_block = "10.2.0.0/16" } } subnets = { a = { number = 1 } b = { number = 2 } c = { number = 3 } } ``` -------------------------------- TITLE: Illustrate chunklist Function Usage with Examples in HCL DESCRIPTION: These examples demonstrate the behavior of the `chunklist` function in HCL. They show how a list is split into sub-lists based on different `chunk_size` values, illustrating the function's output for various inputs and edge cases like an incomplete final chunk. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/chunklist.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > chunklist(["a", "b", "c", "d", "e"], 2) [ [ "a", "b", ], [ "c", "d", ], [ "e", ], ] > chunklist(["a", "b", "c", "d", "e"], 1) [ [ "a", ], [ "b", ], [ "c", ], [ "d", ], [ "e", ], ] ``` -------------------------------- TITLE: Get Terraform Providers Information DESCRIPTION: Use this command to get information about the providers required by the current working directory's configuration. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/plugins/index.mdx#_snippet_0 LANGUAGE: Shell CODE: ``` terraform providers ``` -------------------------------- TITLE: Terraform CLI: init Command Reference DESCRIPTION: Detailed documentation for the `terraform init` command, including its general usage, options, and specific behaviors related to module copying and backend initialization. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/init.mdx#_snippet_0 LANGUAGE: APIDOC CODE: ``` Command: terraform init Description: Initializes a working directory containing Terraform configuration files and installs plugins for required providers. This is the first command that should be run after writing a new Terraform configuration or cloning an existing one. It is safe to run multiple times. Usage: terraform init [options] General Options: -input=true|false (default: true) Description: Ask for input if necessary. If false, will error if input was required. -lock=true|false (default: true) Description: Disable locking of state files during state-related operations. -lock-timeout= (default: 0s) Description: Override the time Terraform will wait to acquire a state lock. The default causes immediate failure if the lock is already held by another process. -no-color Description: Disable color codes in the command output. -upgrade Description: Opt to upgrade modules and plugins as part of their respective installation steps. Module Copying Options: -from-module=MODULE-SOURCE Description: Copies the given module into the target directory before any other initialization steps are run. Useful for checking out configurations from version control or copying example configurations. Backend Initialization Options: -reconfigure Description: Disregards any existing backend configuration, preventing migration of any existing state. -migrate-state Description: Attempts to copy existing state to the new backend. May result in interactive prompts to confirm migration of workspace states. -force-copy Description: Suppresses interactive prompts for state migration and answers "yes" to migration questions. Automatically enables -migrate-state. -backend=false Description: Skips backend configuration. Recommended only when the working directory was already previously initialized for a particular backend. -backend-config=... Description: Used for partial backend configuration, where settings are dynamic or sensitive and cannot be statically specified in the configuration file. ``` -------------------------------- TITLE: Sample Request: List Available Terraform Provider Versions (curl) DESCRIPTION: An example `curl` command demonstrating how to query the network mirror API to list available versions for the 'random' provider from 'registry.terraform.io' on 'terraform.example.com'. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/provider-network-mirror-protocol.mdx#_snippet_3 LANGUAGE: shell CODE: ``` curl 'https://terraform.example.com/providers/registry.terraform.io/hashicorp/random/index.json' ``` -------------------------------- TITLE: jsondecode Function Usage Examples DESCRIPTION: Illustrates practical examples of using the `jsondecode` function. The first example decodes a JSON object string, and the second demonstrates decoding a simple boolean JSON string, showing the resulting Terraform values. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/jsondecode.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` > jsondecode("{\"hello\": \"world\"}") { "hello" = "world" } > jsondecode("true") true ``` -------------------------------- TITLE: Example of matchkeys Function Usage DESCRIPTION: Demonstrates how `matchkeys` filters `valueslist` based on `keyslist` elements matching `searchset`, returning a new list with corresponding values. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/matchkeys.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` > matchkeys(["i-123", "i-abc", "i-def"], ["us-west", "us-east", "us-east"], ["us-east"]) [ "i-abc", "i-def", ] ``` -------------------------------- TITLE: Terraform Language Basic Syntax Elements DESCRIPTION: This snippet illustrates the fundamental syntax elements of the Terraform language, including a concrete `resource` block example and a generic block structure. It demonstrates how blocks, arguments, and expressions are used to define infrastructure components. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/index.mdx#_snippet_0 LANGUAGE: hcl CODE: ``` resource "aws_vpc" "main" { cidr_block = var.base_cidr_block } "" "" { # Block body = # Argument } ``` -------------------------------- TITLE: Credentials Helper 'store' Command Example DESCRIPTION: Demonstrates how Terraform invokes a credentials helper with the 'store' verb to provide new credentials for a given hostname. Terraform writes the JSON credentials object to the helper's stdin. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/credentials-helpers.mdx#_snippet_3 LANGUAGE: Shell CODE: ``` terraform-credentials-credstore --host=credstore.example.com store app.terraform.io ``` -------------------------------- TITLE: Illustrate Terraform HCL split function usage with examples DESCRIPTION: Provides multiple examples of the `split` function, demonstrating its behavior with different inputs: a comma-separated string, a single-element string, and an empty string, showing the resulting list for each scenario. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/split.mdx#_snippet_1 LANGUAGE: hcl CODE: ``` > split(",", "foo,bar,baz") [ "foo", "bar", "baz", ] > split(",", "foo") [ "foo", ] > split(",", "") [ "", ] ``` -------------------------------- TITLE: Create Terraform workspace from existing state DESCRIPTION: Illustrates how to create a new Terraform workspace named 'example' and initialize its state by copying from an existing local state file (`old.terraform.tfstate`) using the `-state` flag. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/commands/workspace/new.mdx#_snippet_2 LANGUAGE: Shell CODE: ``` $ terraform workspace new -state=old.terraform.tfstate example Created and switched to workspace "example". You're now on a new, empty workspace. Workspaces isolate their state, so if you run "terraform plan" Terraform will not see any existing state for this configuration. ``` -------------------------------- TITLE: Terraform UI: Refresh Start Message DESCRIPTION: Defines the structure of the `refresh_start` message hook object, emitted when a resource refresh operation begins, and provides an example JSON payload. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_24 LANGUAGE: APIDOC CODE: ``` refresh_start message hook object: resource: resource object (identifying the resource) id_key: string (key used to identify this instance of the resource) id_value: string (value used to identify this instance of the resource) ``` LANGUAGE: json CODE: ``` { "@level": "info", "@message": "null_resource.none[0]: Refreshing state... [id=1971614370559474622]", "@module": "terraform.ui", "@timestamp": "2021-03-26T14:18:06.508915-04:00", "hook": { "resource": { "addr": "null_resource.none[0]", "module": "", "resource": "null_resource.none[0]", "implied_provider": "null", "resource_type": "null_resource", "resource_name": "none", "resource_key": 0 }, "id_key": "id", "id_value": "1971614370559474622" }, "type": "refresh_start" } ``` -------------------------------- TITLE: Example Path for In-house Provider Executable on Windows DESCRIPTION: This example shows the full path to an in-house Terraform provider executable within a local filesystem mirror on a Windows system. It includes the placeholder source address, version, platform-specific directory (`windows_amd64`), and the provider binary filename, `terraform-provider-ourcloud.exe`. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/providers/requirements.mdx#_snippet_8 LANGUAGE: plaintext CODE: ``` terraform.example.com/examplecorp/ourcloud/1.0.0/windows_amd64/terraform-provider-ourcloud.exe ``` -------------------------------- TITLE: Example Terraform Test Abstract Message JSON DESCRIPTION: A JSON example of the `test_abstract` message, showing the count of found test files and run blocks, along with their validation status. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_29 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "Found 1 file and 2 run blocks", "@module": "terraform.ui", "@timestamp": "2023-08-09T16:12:30.325582+02:00", "test_abstract": { "validation.tftest.hcl": [ "passed_validation", "failed_validatation" ] }, "type": "test_abstract" } ``` -------------------------------- TITLE: HCL substr Basic Usage Example DESCRIPTION: Demonstrates extracting a substring from a simple string 'hello world' starting at offset 1 with a length of 4 characters, resulting in 'ello'. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/substr.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` > substr("hello world", 1, 4) ello ``` -------------------------------- TITLE: List Available Terraform Versions in APT Repository DESCRIPTION: This command queries the APT package manager to display all available versions of the `terraform` package in the configured repositories. It helps users identify which specific Terraform versions can be installed from the HashiCorp APT repository. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/cli/install/apt.mdx#_snippet_0 LANGUAGE: bash CODE: ``` apt policy terraform ``` -------------------------------- TITLE: Terraform UI apply_progress Message Hook JSON Example DESCRIPTION: Example JSON payload for the `apply_progress` message hook, indicating ongoing resource creation and elapsed time for a specific resource instance. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_14 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "null_resource.none[4]: Still creating... [30s elapsed]", "@module": "terraform.ui", "@timestamp": "2021-03-17T09:34:26.222465-04:00", "hook": { "resource": { "addr": "null_resource.none[4]", "module": "", "resource": "null_resource.none[4]", "implied_provider": "null", "resource_type": "null_resource", "resource_name": "none", "resource_key": 4 }, "action": "create", "elapsed_seconds": 30 }, "type": "apply_progress" } ``` -------------------------------- TITLE: Service Discovery Document Example DESCRIPTION: An example JSON document illustrating the `providers.v1` service identifier and its corresponding base URL for the provider registry protocol, as used in Terraform's service discovery process. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/provider-registry-protocol.mdx#_snippet_1 LANGUAGE: json CODE: ``` { "providers.v1": "/terraform/providers/v1/" } ``` -------------------------------- TITLE: Terraform `lookup` Function Usage Examples DESCRIPTION: Illustrates practical applications of the `lookup` function, demonstrating how it retrieves values from a map and handles cases where the key is not found by returning a specified default. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/lookup.mdx#_snippet_1 LANGUAGE: Console CODE: ``` > lookup({a="ay", b="bee"}, "a", "what?") ay > lookup({a="ay", b="bee"}, "c", "what?") what? ``` -------------------------------- TITLE: Testing Terraform Functions in Console DESCRIPTION: This example demonstrates how to use the `terraform console` command to interactively test built-in functions. It shows the input command and the resulting output from the console. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/index.mdx#_snippet_1 LANGUAGE: shell CODE: ``` > max(5, 12, 9) 12 ``` -------------------------------- TITLE: HCL element() Get Last Element Example DESCRIPTION: Shows how to retrieve the last element of a list in HCL by combining the `element` function with the `length` function to calculate the correct zero-based index. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/language/functions/element.mdx#_snippet_3 LANGUAGE: HCL CODE: ``` > element(["a", "b", "c"], length(["a", "b", "c"])-1) c ``` -------------------------------- TITLE: Example JSON for Terraform `change_summary` Message DESCRIPTION: An example JSON payload demonstrating the `change_summary` message. This snippet shows an 'apply' operation resulting in 1 resource added, 0 changed, and 0 destroyed, providing a concise overview of the operation's outcome. SOURCE: https://github.com/hashicorp/terraform/blob/v1.8.0/website/docs/internals/machine-readable-ui.mdx#_snippet_7 LANGUAGE: json CODE: ``` { "@level": "info", "@message": "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.", "@module": "terraform.ui", "@timestamp": "2021-05-25T13:32:41.869168-04:00", "changes": { "add": 1, "change": 0, "remove": 0, "operation": "apply" }, "type": "change_summary" } ```