dynamic block
时间: 2023-08-31 22:10:14 浏览: 90
BLOCK 应用场景
Dynamic blocks in Terraform allow you to create multiple instances of a resource with different configurations using a single block of code. This is useful when you need to create multiple similar resources, such as multiple EC2 instances with different instance types or different subnet IDs.
To create a dynamic block, you need to define a variable that contains a list of configurations, and then use a for_each loop to iterate over the list and create the resources. Here's an example of how to create multiple EC2 instances with different instance types:
```
variable "instance_types" {
type = list(string)
default = ["t2.micro", "t2.small", "t2.medium"]
}
resource "aws_instance" "ec2_instance" {
for_each = toset(var.instance_types)
ami = "ami-0c55b159cbfafe1f0"
instance_type = each.value
subnet_id = "subnet-0123456789abcdef"
}
```
In this example, the `instance_types` variable contains a list of three different instance types. The `for_each` loop iterates over the list and creates three EC2 instances with the specified instance types.
Dynamic blocks can also be used with other resource types, such as subnets or security groups. They provide a powerful way to create multiple resources with different configurations in a concise and efficient way.
阅读全文