Skip to content

Commit 6215d16

Browse files
committed
Use initialised backed for fingerprinting
This means backend blocks using early initialisation are correctly fingerprinted
1 parent a7152b2 commit 6215d16

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

image/src/github_pr_comment/backend_fingerprint.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
Combined with the backend type and workspace name, this should uniquely identify a remote state file.
88
99
"""
10+
import json
11+
import os
12+
from pathlib import Path
13+
1014
import canonicaljson
1115

1216
from github_actions.debug import debug
@@ -194,7 +198,40 @@ def fingerprint(backend_type: BackendType, backend_config: BackendConfig, env) -
194198
}
195199

196200
fingerprint_inputs = backends.get(backend_type, lambda c, e: c)(backend_config, env)
201+
fingerprint_inputs = initialised_backend_config(backend_type, fingerprint_inputs)
197202

198203
debug(f'Backend fingerprint includes {fingerprint_inputs.keys()}')
199204

200205
return canonicaljson.encode_canonical_json(fingerprint_inputs)
206+
207+
def initialised_backend_config(backend_type: BackendType, config: dict[str, str]) -> dict[str, str]:
208+
"""
209+
Get backend config from an initialized data directory
210+
"""
211+
212+
statefile_path = Path(os.environ.get('TF_DATA_DIR')) / 'terraform.tfstate'
213+
if not statefile_path.exists():
214+
debug(f'No state file found at {statefile_path}')
215+
return config
216+
217+
with open(statefile_path) as f:
218+
statefile = json.load(f)
219+
220+
backend = statefile.get('backend', {})
221+
if backend.get('type') != backend_type:
222+
debug(f'Backend type {backend.get("type")} from statefile does not match {backend_type}')
223+
return config
224+
225+
if 'config' not in backend:
226+
debug('No backend config found in statefile')
227+
return config
228+
229+
for k in config:
230+
v = backend['config'].get(k)
231+
if v is not None and v != config[k]:
232+
# The backend config in the statefile is different from the one in the .tf file
233+
# We should use the one in the statefile
234+
debug(f'Backend config {k} is {v} (tfstate) instead of {config[k]} (tf file)')
235+
config[k] = v
236+
237+
return config

0 commit comments

Comments
 (0)