Skip to content

Commit b099298

Browse files
committed
Merge pull request hashicorp#2596 from hashicorp/d-tfvars-mappings
docs: expand how to assign mappings from file
2 parents 8be06a0 + b4ca04c commit b099298

1 file changed

Lines changed: 48 additions & 3 deletions

File tree

website/source/intro/getting-started/variables.html.md

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ the `TF_VAR_access_key` variable can be set to set the `access_key` variable.
9898
We recommend using the "terraform.tfvars" file, and ignoring it from
9999
version control.
100100

101+
<a id="mappings"></a>
101102
## Mappings
102103

103104
We've replaced our sensitive strings with variables, but we still
@@ -140,15 +141,59 @@ While we don't use it in our example, it is worth noting that you
140141
can also do a static lookup of a mapping directly with
141142
`${var.amis.us-east-1}`.
142143

143-
We set defaults, but mappings can also be overridden using the
144-
`-var` and `-var-file` values. For example, if the user wanted to
145-
specify an alternate AMI for us-east-1:
144+
<a id="assigning-mappings"></a>
145+
## Assigning Mappings
146+
147+
We set defaults above, but mappings can also be set using the `-var` and
148+
`-var-file` values. For example, if the user wanted to specify an alternate AMI
149+
for us-east-1:
146150

147151
```
148152
$ terraform plan -var 'amis.us-east-1=foo'
149153
...
150154
```
151155

156+
**Note**: even if every key will be assigned as input, the variable must be
157+
established as a mapping by setting its default to `{}`.
158+
159+
Here is an example of setting a mapping's keys from a file. Starting with these
160+
variable definitions:
161+
162+
```
163+
variable "region" {}
164+
variable "amis" {
165+
default = {}
166+
}
167+
```
168+
169+
You can specify keys in a `terraform.tfvars` file:
170+
171+
```
172+
amis.us-east-1 = "ami-abc123"
173+
amis.us-west-2 = "ami-def456"
174+
```
175+
176+
And access them via `lookup()`:
177+
178+
```
179+
output "ami" {
180+
value = "${lookup(var.amis, var.region)}
181+
}
182+
```
183+
184+
Like so:
185+
186+
```
187+
$ terraform apply -var region=us-west-2
188+
189+
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
190+
191+
Outputs:
192+
193+
ami = ami-def456
194+
195+
```
196+
152197
## Next
153198

154199
Terraform provides variables for parameterizing your configurations.

0 commit comments

Comments
 (0)