Skip to content

Commit bc66212

Browse files
committed
Read .tofu files
1 parent 6215d16 commit bc66212

File tree

7 files changed

+40
-6
lines changed

7 files changed

+40
-6
lines changed

image/src/terraform/module.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
import os
6-
from typing import Any, cast, NewType, Optional, TYPE_CHECKING, TypedDict, List
6+
from typing import Any, cast, NewType, Optional, TYPE_CHECKING, TypedDict, List, Iterable
77

88
import terraform.hcl
99

@@ -51,6 +51,26 @@ def merge(a: TerraformModule, b: TerraformModule) -> TerraformModule:
5151

5252
return merged
5353

54+
def files_in_module(path: Path) -> Iterable[Path]:
55+
56+
if os.environ.get('OPENTOFU') == 'true':
57+
files = {}
58+
59+
for filename in path.iterdir():
60+
stem = filename.stem
61+
62+
if filename.suffix == '.tf' and stem not in files:
63+
files[stem] = filename
64+
elif filename.suffix == '.tofu':
65+
files[stem] = filename
66+
67+
yield from files.values()
68+
69+
else:
70+
for filename in path.iterdir():
71+
if filename.suffix == '.tf':
72+
yield filename
73+
5474

5575
def load_module(path: Path) -> TerraformModule:
5676
"""
@@ -62,12 +82,10 @@ def load_module(path: Path) -> TerraformModule:
6282

6383
module = cast(TerraformModule, {})
6484

65-
for file in os.listdir(path):
66-
if not file.endswith('.tf'):
67-
continue
85+
for file in files_in_module(path):
6886

6987
try:
70-
tf_file = cast(TerraformModule, terraform.hcl.load(os.path.join(path, file)))
88+
tf_file = cast(TerraformModule, terraform.hcl.load(file))
7189
module = merge(module, tf_file)
7290
except Exception as e:
7391
# ignore tf files that don't parse

tests/test_module.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
from pathlib import Path
2+
13
from terraform.hcl import loads
2-
from terraform.module import get_sensitive_variables
4+
from terraform.module import get_sensitive_variables, files_in_module
35

46

57
def test_get_sensitive_variables():
@@ -26,3 +28,17 @@ def test_get_sensitive_variables():
2628
''')
2729

2830
assert get_sensitive_variables(module) == ['secret', 'super_secret']
31+
32+
def test_load_terraform_module():
33+
assert set(s.name for s in files_in_module(Path('tests/tofu-module'))) == {
34+
'blah.tf',
35+
'hello.tf',
36+
}
37+
38+
def test_load_tofu_module(monkeypatch):
39+
monkeypatch.setenv('OPENTOFU', 'true')
40+
assert set(s.name for s in files_in_module(Path('tests/tofu-module'))) == {
41+
'blah.tf',
42+
'hello.tofu',
43+
'tofu-only.tofu'
44+
}

tests/tofu-module/blah.tf

Whitespace-only changes.

tests/tofu-module/hello.tf

Whitespace-only changes.

tests/tofu-module/hello.tofu

Whitespace-only changes.

tests/tofu-module/nope

Whitespace-only changes.

tests/tofu-module/tofu-only.tofu

Whitespace-only changes.

0 commit comments

Comments
 (0)