如何在Terraform中编写动态变量与请求体?求对应配置代码
Alright, let's convert your Ansible variable logic into Terraform! The goal here is to dynamically build the myvariable value by checking if optional parameters exist, concatenating them when multiple are provided, and falling back to a default if none are passed. Here's a clean, idiomatic Terraform implementation:
Step 1: Define Optional Input Variables
First, declare the optional parameters (param1, param2, param3) that users can pass in. These are marked as optional so Terraform won't throw an error if they're omitted.
# Optional input parameters mirroring your Ansible vars variable "param1" { type = string description = "Optional first parameter" optional = true } variable "param2" { type = string description = "Optional second parameter" optional = true } variable "param3" { type = string description = "Optional third parameter" optional = true }
Step 2: Compute the Final Variable Value
Use a locals block to handle the dynamic logic. We'll collect all non-null parameters, concatenate them with commas if there are multiple, and default to "default" if no parameters are provided.
# Calculate the final myvariable value using local logic locals { # Filter out any null parameters (since omitted optional vars are null) valid_params = compact([ var.param1, var.param2, var.param3 ]) # Build the result: join valid params with commas, or use default if empty myvariable = length(local.valid_params) > 0 ? join(",", local.valid_params) : "default" }
Step 3: Verify the Result (Like Ansible's Debug)
Add an output block to see the final value of myvariable, just like the debug task in your Ansible playbook.
# Output the computed myvariable to verify the logic output "myvariable" { value = local.myvariable }
How This Matches Your Ansible Logic
This implementation behaves exactly like your Ansible code:
- If
param1is provided, it's included in the final value - If
param2is provided (whether or notparam1exists), it's appended with a comma - If
param3is provided, it's also appended with a comma - If no parameters are passed,
myvariabledefaults to "default"
Example Test Cases
Try these commands to validate the behavior:
Only pass param2:
terraform apply -var="param2=hello"Output:
myvariable = "hello"Pass param1 and param3:
terraform apply -var="param1=foo" -var="param3=bar"Output:
myvariable = "foo,bar"No parameters passed:
terraform applyOutput:
myvariable = "default"All three parameters passed:
terraform apply -var="param1=a" -var="param2=b" -var="param3=c"Output:
myvariable = "a,b,c"
内容的提问来源于stack exchange,提问作者SHIVANGI MANGAL

