Skip to content

Commit afc9ca2

Browse files
authored
doc: add documentation on dynamic and for_each loop (#750)
1 parent 2a83bc4 commit afc9ca2

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

docs/resources/instance_security_group_rules.md

+69
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,75 @@ resource "scaleway_instance_security_group_rules" "sgrs01" {
3131
}
3232
```
3333

34+
### Simplify your rules using dynamic block and `for_each` loop
35+
36+
You can use [`for_each` syntax](https://www.terraform.io/docs/configuration/meta-arguments/for_each.html) to simplify the definition of your rules.
37+
Let's suppose that your inbound default policy is to drop, but you want to build a list of exceptions to accept.
38+
Create a local containing your exceptions (`locals.trusted`) and use the `for_each` syntax in a [dynamic block](https://www.terraform.io/docs/configuration/expressions/dynamic-blocks.html):
39+
40+
```hcl
41+
resource "scaleway_instance_security_group" "main" {
42+
description = "test"
43+
name = "terraform test"
44+
inbound_default_policy = "drop"
45+
outbound_default_policy = "accept"
46+
}
47+
48+
locals {
49+
trusted = [
50+
"1.2.3.4",
51+
"4.5.6.7",
52+
"7.8.9.10"
53+
]
54+
}
55+
56+
resource "scaleway_instance_security_group_rules" "main" {
57+
security_group_id = scaleway_instance_security_group.main.id
58+
59+
dynamic "inbound_rule" {
60+
for_each = local.trusted
61+
content {
62+
action = "accept"
63+
ip = inbound_rule.value
64+
port = 80
65+
}
66+
}
67+
}
68+
```
69+
70+
You can also use object to assign IP and port in the same time.
71+
In your locals, you can use [objects](https://www.terraform.io/docs/configuration/types.html#structural-types) to encapsulate several values that will be used later on in the loop:
72+
73+
```hcl
74+
resource "scaleway_instance_security_group" "main" {
75+
description = "test"
76+
name = "terraform test"
77+
inbound_default_policy = "drop"
78+
outbound_default_policy = "accept"
79+
}
80+
81+
locals {
82+
trusted = [
83+
{ ip = "1.2.3.4", port = "80" },
84+
{ ip = "5.6.7.8", port = "81" },
85+
{ ip = "9.10.11.12", port = "81" },
86+
]
87+
}
88+
89+
resource "scaleway_instance_security_group_rules" "main" {
90+
security_group_id = scaleway_instance_security_group.main.id
91+
92+
dynamic "inbound_rule" {
93+
for_each = local.trusted
94+
content {
95+
action = "accept"
96+
ip = inbound_rule.value.ip
97+
port = inbound_rule.value.port
98+
}
99+
}
100+
}
101+
```
102+
34103
## Arguments Reference
35104

36105
The following arguments are supported:

0 commit comments

Comments
 (0)