|
7 | 7 | Combined with the backend type and workspace name, this should uniquely identify a remote state file. |
8 | 8 |
|
9 | 9 | """ |
| 10 | +import json |
| 11 | +import os |
| 12 | +from pathlib import Path |
| 13 | + |
10 | 14 | import canonicaljson |
11 | 15 |
|
12 | 16 | from github_actions.debug import debug |
@@ -194,7 +198,40 @@ def fingerprint(backend_type: BackendType, backend_config: BackendConfig, env) - |
194 | 198 | } |
195 | 199 |
|
196 | 200 | fingerprint_inputs = backends.get(backend_type, lambda c, e: c)(backend_config, env) |
| 201 | + fingerprint_inputs = initialised_backend_config(backend_type, fingerprint_inputs) |
197 | 202 |
|
198 | 203 | debug(f'Backend fingerprint includes {fingerprint_inputs.keys()}') |
199 | 204 |
|
200 | 205 | 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