Gosh, this is complicated...    I'm not sure when it was added, but modern terraform fmt has a -recursive flag which probably does what you want without all these shenanigans (https://github.com/alphagov/govuk-infrastructure/blob/main/.github/workflows/ci.yml#L31)