├── .github └── workflows │ └── ltf.yaml ├── .gitignore ├── .tool-versions ├── LICENSE ├── Makefile ├── README.md ├── cmd └── ltf │ └── main.go ├── environ.go ├── environ_test.go ├── example ├── .terraform.lock.hcl ├── config.local.tfbackend ├── dev │ └── dev.auto.tfvars ├── live │ ├── blue │ │ └── live.blue.auto.tfvars │ ├── green │ │ └── live.green.auto.tfvars │ └── live.auto.tfvars ├── ltf.yaml └── main.tf ├── go.mod ├── go.sum └── internal ├── arguments ├── arguments.go └── arguments_test.go ├── backend ├── backend.go ├── backend_test.auto.tfvars ├── backend_test.go ├── backend_test.tf └── backend_test.tfbackend ├── filesystem └── filesystem.go ├── hook ├── hook.go ├── hook_test.go └── hooks.go ├── ltf ├── ltf.go ├── ltf_test.go ├── ltf_test.hcl └── version.go ├── settings └── settings.go └── variable ├── variable.go ├── variables.go ├── variables_test.go ├── variables_test.tf └── variables_test.tfvars /.github/workflows/ltf.yaml: -------------------------------------------------------------------------------- 1 | name: LTF 2 | 3 | on: 4 | pull_request: 5 | push: 6 | tags: 7 | - 'v*' 8 | 9 | env: 10 | GO_VERSION: 1.17.7 11 | 12 | jobs: 13 | lint: 14 | name: Lint 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2 19 | - name: Lint 20 | uses: golangci/golangci-lint-action@v2.5.2 21 | test: 22 | name: Test 23 | runs-on: ubuntu-latest 24 | needs: lint 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v2 28 | - name: Setup Go 29 | uses: actions/setup-go@v2 30 | with: 31 | go-version: ${{ env.GO_VERSION }} 32 | - name: Test 33 | run: go test -v -cover ./... 34 | release: 35 | if: github.event_name == 'push' 36 | name: Release 37 | runs-on: ubuntu-latest 38 | needs: test 39 | steps: 40 | - name: Checkout 41 | uses: actions/checkout@v2 42 | with: 43 | fetch-depth: 0 44 | - name: Setup Go 45 | uses: actions/setup-go@v2 46 | with: 47 | go-version: ${{ env.GO_VERSION }} 48 | - name: Build 49 | run: | 50 | GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags='-s -w -X main.version=${{ github.ref_name }}' -v -o ltf-darwin-amd64 ./cmd/ltf 51 | GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags='-s -w -X main.version=${{ github.ref_name }}' -v -o ltf-darwin-arm64 ./cmd/ltf 52 | GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w -X main.version=${{ github.ref_name }}' -v -o ltf-linux-amd64 ./cmd/ltf 53 | - name: Release 54 | uses: softprops/action-gh-release@v1 55 | with: 56 | draft: true 57 | files: | 58 | ltf-darwin-amd64 59 | ltf-darwin-arm64 60 | ltf-linux-amd64 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .terraform 2 | /ltf 3 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | terraform 1.1.5 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | sources = go.sum $(shell find . -name '*.go') 2 | 3 | .PHONY: build 4 | build: test ltf 5 | 6 | .PHONY: clean 7 | clean: 8 | rm -rf ltf 9 | 10 | .PHONY: test 11 | test: $(sources) 12 | go test ./... 13 | # success 14 | 15 | .PHONY: test 16 | testv: $(sources) 17 | go test -v ./... 18 | # success 19 | 20 | ltf: $(sources) 21 | go build ./cmd/ltf 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LTF 2 | 3 | > Status: alpha 4 | 5 | LTF is a minimal, transparent Terraform wrapper. It makes Terraform projects easier to work with. 6 | 7 | In standard Terraform projects, the `*.tf` files are typically duplicated in each environment, with minor differences for the backend configuration. Every environment directory contains nearly identical `*.tf` files and `*.tfvars` files. It requires some effort to maintain all of these environments and keep them consistent. Changes take longer because they involve more files. 8 | 9 | ``` 10 | terraform 11 | ├── dev 12 | │ ├── dev.auto.tfvars 13 | │ ├── main.tf 14 | │ ├── outputs.tf 15 | │ └── variables.tf 16 | ├── qa 17 | │ ├── qa.auto.tfvars 18 | │ ├── main.tf 19 | │ ├── outputs.tf 20 | │ └── variables.tf 21 | └── live 22 | ├── blue 23 | │ ├── live.blue.auto.tfvars 24 | │ ├── main.tf 25 | │ ├── outputs.tf 26 | │ └── variables.tf 27 | └── green 28 | ├── live.green.auto.tfvars 29 | ├── main.tf 30 | ├── outputs.tf 31 | └── variables.tf 32 | ``` 33 | 34 | Using LTF, the `*.tf` files are shared between all environments. A single `*.tfbackend` file is used to configure the backend for all environments, making use of variables. Environment directories only contain what is unique about the environment: the `*.tfvars` file. Maintenance is easier and environments are consistent by default. Changes take less time because they involve fewer files. 35 | 36 | ``` 37 | ltf 38 | ├── auto.tfbackend 39 | ├── main.tf 40 | ├── outputs.tf 41 | ├── variables.tf 42 | ├── dev 43 | │ └── dev.auto.tfvars 44 | ├── qa 45 | │ └── qa.auto.tfvars 46 | └── live 47 | ├── blue 48 | │ └── live.blue.auto.tfvars 49 | └── green 50 | └── live.green.auto.tfvars 51 | ``` 52 | 53 | Using LTF is very easy. It avoids tedious command line arguments. Change to an environment directory and use `ltf` just like you would normally use `terraform` in a simple, single-directory Terraform project. 54 | 55 | ``` 56 | $ cd dev 57 | $ ltf init 58 | $ ltf plan 59 | $ ltf apply 60 | $ cd ../live/green 61 | $ ltf init 62 | $ ltf plan 63 | $ ltf apply -target=random_id.this 64 | ``` 65 | 66 | ## Why use LTF? 67 | 68 | LTF only does a few things: 69 | 70 | * It finds and uses a parent directory as the configuration directory. 71 | * It finds and uses tfvars and tfbackend files from the current and parent directories. 72 | * It supports variables in tfbackend files. 73 | * It supports hooks to run custom scripts before and after Terraform. 74 | 75 | LTF is good because: 76 | 77 | * It avoids tedious command line arguments, so it's quick and easy to use. 78 | * It is a transparent wrapper, so all standard Terraform commands and arguments can be used. 79 | * It is released as a single binary, so installation is easy. 80 | * It keeps your Terraform configuration DRY using only a simple directory structure. 81 | * It only does a few things, so there's not much to learn. 82 | * It runs Terraform in the configuration directory, so there are no temporary files or build/cache directories to complicate things. 83 | 84 | LTF is purposefully simple and feature-light, so it doesn't do everything: 85 | 86 | * [It does not create backend resources for you.](https://github.com/raymondbutcher/ltf/discussions/21) 87 | * [It does not generate Terraform configuration using another language.](https://github.com/raymondbutcher/ltf/discussions/22) 88 | * [It does not support remote configurations.](https://github.com/raymondbutcher/ltf/discussions/24) 89 | * [It does not support run-all or similar commands.](https://github.com/raymondbutcher/ltf/discussions/26) 90 | 91 | ## Installation 92 | 93 | ### Install manually 94 | 95 | Download the appropriate binary for your system from the [releases](https://github.com/raymondbutcher/ltf/releases) page, move it to your `PATH`, and make it executable. 96 | 97 | ### Install using [bin](https://github.com/marcosnils/bin) 98 | 99 | [bin](https://github.com/marcosnils/bin) manages binary files downloaded from different sources. Run the following to install the latest version of LTF: 100 | 101 | ``` 102 | bin install github.com/raymondbutcher/ltf 103 | ``` 104 | 105 | ## Usage 106 | 107 | Run `ltf` instead of `terraform`. All standard Terraform commands and arguments can be used. 108 | 109 | Example: 110 | 111 | ``` 112 | $ ltf init 113 | $ ltf plan 114 | $ ltf apply -target=random_id.this 115 | ``` 116 | 117 | ## How LTF works 118 | 119 | LTF searches the directory tree for a Terraform configuration directory, tfvars files, and tfbackend files, and passes their details to Terraform. 120 | 121 | When LTF finds no `*.tf` or `*.tf.json` files in the current directory, it does the following: 122 | 123 | * Finds the closest parent directory containing `*.tf` or `*.tf.json` files, then adds `-chdir=$dir` to the Terraform command line arguments, to make Terraform use it as the configuration directory. 124 | * Sets the `TF_DATA_DIR` environment variable to make Terraform use the `.terraform` directory inside the current directory instead of the configuration directory. 125 | 126 | When running `ltf init`, it does the following: 127 | 128 | * Finds `*.tfbackend` files in the current directory and parent directories, stopping at the configuration directory, then updates the `TF_CLI_ARGS_init` environment variable to contain `-backend-config=$attribute` for each attribute. 129 | * The use of Terraform variables in `*.tfbackend` files is supported. 130 | 131 | It always does the following: 132 | 133 | * Finds `*.tfvars` and `*.tfvars.json` files in the current directory and parent directories, stopping at the configuration directory, then sets the `TF_VAR_name` environment variable for each variable. 134 | * Terraform's [precedence rules](https://www.terraform.io/language/values/variables#variable-definition-precedence) are followed when finding variables, with the additional rule that variables in subdirectories take precendence over variables in parent directories. 135 | * If any tfvars files exist in the configuration directory, variables from those files take precedence over any environment variables. LTF raises an error if it tries to set an environment variable that would be ignored by Terraform. This can be avoided by using variable defaults instead of tfvars files, or by moving the tfvars files into a subdirectory. 136 | * Runs hook scripts before and after Terraform. 137 | 138 | ## Hooks 139 | 140 | LTF also supports hook scripts defined in `ltf.yaml`. It looks for this file in the current directory or any parent directory. Hook scripts are just Bash scripts; they can contain multiple lines, and they can even export environment variables. Environment variables will persist to subsequent hooks and to the Terraform command. 141 | 142 | Hooks can be configured to run `before` specific Terraform commands, and/or `after` they have completed successfully, and/or after they have `failed`. 143 | 144 | ### Schema 145 | 146 | ```yaml 147 | hooks: 148 | $name: # the name of the hook 149 | before: # (optional) run the script before these commands 150 | - terraform # the hook will always run 151 | - terraform $subcommand # the hook will only run before this subcommand 152 | after: [] # (optional) run the script after these commands finish successfully 153 | failed: [] # (optional) run the script after these commands have failed 154 | script: $script # bash script to run 155 | ``` 156 | 157 | ### Example: running commands 158 | 159 | ```yaml 160 | hooks: 161 | greetings: 162 | before: 163 | - terraform 164 | script: | 165 | echo "Hello, this is a hook!" 166 | echo "The date is $(date -I)" 167 | ``` 168 | 169 | ### Example: Setting environment variables 170 | 171 | ```yaml 172 | hooks: 173 | TF_VAR_hook: 174 | before: 175 | - terraform apply 176 | - terraform plan 177 | script: export TF_VAR_hook=hello 178 | ``` 179 | -------------------------------------------------------------------------------- /cmd/ltf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/raymondbutcher/ltf" 8 | "github.com/raymondbutcher/ltf/internal/arguments" 9 | internal "github.com/raymondbutcher/ltf/internal/ltf" // TODO: refactor this package away 10 | ) 11 | 12 | func main() { 13 | cwd, err := os.Getwd() 14 | if err != nil { 15 | fmt.Fprintf(os.Stderr, "%s: error getting current working directory: %s\n", os.Args[0], err) 16 | os.Exit(1) 17 | } 18 | 19 | env := ltf.NewEnviron(os.Environ()...) 20 | args, err := arguments.New(os.Args, env) 21 | if err != nil { 22 | fmt.Fprintf(os.Stderr, "%s: error parsing cli arguments: %s\n", os.Args[0], err) 23 | os.Exit(1) 24 | } 25 | 26 | _, exitStatus, err := internal.Run(cwd, args, env) 27 | if err != nil { 28 | fmt.Fprintf(os.Stderr, "%s: %s\n", args.Bin, err) 29 | } 30 | 31 | os.Exit(exitStatus) 32 | } 33 | -------------------------------------------------------------------------------- /environ.go: -------------------------------------------------------------------------------- 1 | package ltf 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // Environ contains environment variables in the same format returned by os.Environ() 8 | // and used by exec.Command{} but with methods to get and set values more easily. 9 | type Environ []string 10 | 11 | // NewEnviron returns a new Environ object 12 | // with the provided environment variables in the format "key=value". 13 | func NewEnviron(env ...string) Environ { 14 | return append(Environ{}, env...) 15 | } 16 | 17 | // GetValue returns the named environment variable value or an empty string if it doesn't exist. 18 | func (env Environ) GetValue(name string) string { 19 | prefix := name + "=" 20 | value := "" 21 | for _, item := range env { 22 | if strings.HasPrefix(item, prefix) { 23 | value = item[len(prefix):] 24 | } 25 | } 26 | return value 27 | } 28 | 29 | // SetValue adds an environment variable to the environment variables. 30 | // If the variable already exists, it is replaced. 31 | // A new, updated Environ object is returned; it does not modify the existing object. 32 | func (env Environ) SetValue(name string, value string) Environ { 33 | newEnv := Environ{} 34 | prefix := name + "=" 35 | for _, v := range env { 36 | if !strings.HasPrefix(v, prefix) { 37 | newEnv = append(newEnv, v) 38 | } 39 | } 40 | newEnv = append(newEnv, name+"="+value) 41 | return newEnv 42 | } 43 | -------------------------------------------------------------------------------- /environ_test.go: -------------------------------------------------------------------------------- 1 | package ltf 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/matryer/is" 7 | ) 8 | 9 | func TestEnviron(t *testing.T) { 10 | is := is.New(t) 11 | 12 | env := NewEnviron( 13 | "ONE=1", 14 | "TWO=2", 15 | "THREE=3", 16 | ) 17 | 18 | is.Equal(env.GetValue("ONE"), "1") 19 | is.Equal(env.GetValue("TWO"), "2") 20 | is.Equal(env.GetValue("THREE"), "3") 21 | 22 | env = env.SetValue("TWO", "changed") 23 | 24 | is.Equal(env.GetValue("ONE"), "1") 25 | is.Equal(env.GetValue("TWO"), "changed") 26 | is.Equal(env.GetValue("THREE"), "3") 27 | 28 | is.Equal(len(env), 3) 29 | } 30 | -------------------------------------------------------------------------------- /example/.terraform.lock.hcl: -------------------------------------------------------------------------------- 1 | # This file is maintained automatically by "terraform init". 2 | # Manual edits may be lost in future updates. 3 | 4 | provider "registry.terraform.io/hashicorp/random" { 5 | version = "3.1.0" 6 | hashes = [ 7 | "h1:BZMEPucF+pbu9gsPk0G0BHx7YP04+tKdq2MrRDF1EDM=", 8 | "zh:2bbb3339f0643b5daa07480ef4397bd23a79963cc364cdfbb4e86354cb7725bc", 9 | "zh:3cd456047805bf639fbf2c761b1848880ea703a054f76db51852008b11008626", 10 | "zh:4f251b0eda5bb5e3dc26ea4400dba200018213654b69b4a5f96abee815b4f5ff", 11 | "zh:7011332745ea061e517fe1319bd6c75054a314155cb2c1199a5b01fe1889a7e2", 12 | "zh:738ed82858317ccc246691c8b85995bc125ac3b4143043219bd0437adc56c992", 13 | "zh:7dbe52fac7bb21227acd7529b487511c91f4107db9cc4414f50d04ffc3cab427", 14 | "zh:a3a9251fb15f93e4cfc1789800fc2d7414bbc18944ad4c5c98f466e6477c42bc", 15 | "zh:a543ec1a3a8c20635cf374110bd2f87c07374cf2c50617eee2c669b3ceeeaa9f", 16 | "zh:d9ab41d556a48bd7059f0810cf020500635bfc696c9fc3adab5ea8915c1d886b", 17 | "zh:d9e13427a7d011dbd654e591b0337e6074eef8c3b9bb11b2e39eaaf257044fd7", 18 | "zh:f7605bd1437752114baf601bdf6931debe6dc6bfe3006eb7e9bb9080931dca8a", 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /example/config.local.tfbackend: -------------------------------------------------------------------------------- 1 | path = "/tmp/terraform/${var.env}${var.color == "" ? "" : ".${var.color}"}.tfstate" 2 | -------------------------------------------------------------------------------- /example/dev/dev.auto.tfvars: -------------------------------------------------------------------------------- 1 | env = "dev" 2 | byte_length = 8 3 | -------------------------------------------------------------------------------- /example/live/blue/live.blue.auto.tfvars: -------------------------------------------------------------------------------- 1 | color = "blue" 2 | byte_length = 16 3 | -------------------------------------------------------------------------------- /example/live/green/live.green.auto.tfvars: -------------------------------------------------------------------------------- 1 | color = "green" 2 | byte_length = 32 3 | -------------------------------------------------------------------------------- /example/live/live.auto.tfvars: -------------------------------------------------------------------------------- 1 | env = "live" 2 | -------------------------------------------------------------------------------- /example/ltf.yaml: -------------------------------------------------------------------------------- 1 | hooks: 2 | set TF_VAR_secret: 3 | before: 4 | - terraform apply 5 | - terraform plan 6 | script: export TF_VAR_secret=hello 7 | information about hooks: 8 | before: 9 | - terraform hooks 10 | script: | 11 | set -euo pipefail 12 | echo 13 | echo "This hook runs when 'terraform hooks' has been run. Terraform itself" 14 | echo "has no 'hooks' subcommand, so this script ends with an error to prevent" 15 | echo "Terraform from running and failing with an error message." 16 | echo 17 | echo "What can hook scripts do?" 18 | echo 19 | echo "- Run multiple commands on different lines." 20 | message='- Set and use variables.' 21 | echo "${message}" 22 | more_info () { 23 | echo "- Define and call functions." 24 | } 25 | more_info 26 | export TF_INPUT=0 27 | echo "- Export environment variables to make them available in other hooks" 28 | echo " and Terraform when it runs. For example: export TF_INPUT=${TF_INPUT}" 29 | echo "- Run any command available on the system." 30 | echo " For example, here is today's date: $(date -I)" 31 | echo 32 | echo "How are hook scripts executed?" 33 | echo 34 | echo "LTF runs hook scripts inside a wrapper script using Bash." 35 | echo "After the hook script has finished, the wrapper script exports" 36 | echo "the environment and passes it to any subsequent hooks and to" 37 | echo "the Terraform command. This lets hooks set Terraform options" 38 | echo "and variables, just by exporting environment variables." 39 | echo 40 | echo "Now it will error on purpose to prevent Terraform from running." 41 | echo "A future version of LTF will have a more graceful solution for this." 42 | echo 43 | exit 1 44 | -------------------------------------------------------------------------------- /example/main.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | backend "local" {} 3 | } 4 | 5 | variable "byte_length" { 6 | type = number 7 | } 8 | 9 | variable "color" { 10 | type = string 11 | default = "" 12 | } 13 | 14 | variable "env" { 15 | type = string 16 | } 17 | 18 | variable "secret" { 19 | type = string 20 | sensitive = true 21 | } 22 | 23 | resource "random_id" "this" { 24 | byte_length = var.byte_length 25 | prefix = "${var.env}-" 26 | } 27 | 28 | output "secret" { 29 | value = var.secret 30 | sensitive = true 31 | } 32 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/raymondbutcher/ltf 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 7 | github.com/hashicorp/hcl/v2 v2.11.1 8 | github.com/hashicorp/terraform-config-inspect v0.0.0-20211115214459-90acf1ca460f 9 | github.com/matryer/is v1.4.0 10 | github.com/tmccombs/hcl2json v0.3.3 11 | github.com/zclconf/go-cty v1.8.1 12 | gopkg.in/yaml.v2 v2.4.0 13 | ) 14 | 15 | require ( 16 | github.com/agext/levenshtein v1.2.3 // indirect 17 | github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect 18 | github.com/google/go-cmp v0.5.5 // indirect 19 | github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f // indirect 20 | github.com/mitchellh/go-wordwrap v1.0.1 // indirect 21 | golang.org/x/text v0.3.5 // indirect 22 | ) 23 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= 2 | github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= 3 | github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= 4 | github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= 5 | github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= 6 | github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= 7 | github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= 8 | github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= 9 | github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= 10 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 11 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 13 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 14 | github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= 15 | github.com/go-test/deep v1.0.7 h1:/VSMRlnY/JSyqxQUzQLKVMAskpY/NZKFA5j2P+0pP2M= 16 | github.com/go-test/deep v1.0.7/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V36o8= 17 | github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 18 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 19 | github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 20 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 21 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 22 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 23 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 24 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 25 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= 26 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= 27 | github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= 28 | github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= 29 | github.com/hashicorp/hcl/v2 v2.0.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV3txagJ90= 30 | github.com/hashicorp/hcl/v2 v2.9.1/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= 31 | github.com/hashicorp/hcl/v2 v2.11.1 h1:yTyWcXcm9XB0TEkyU/JCRU6rYy4K+mgLtzn2wlrJbcc= 32 | github.com/hashicorp/hcl/v2 v2.11.1/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= 33 | github.com/hashicorp/terraform-config-inspect v0.0.0-20211115214459-90acf1ca460f h1:R8UIC07Ha9jZYkdcJ51l4ownCB8xYwfJtrgZSMvqjWI= 34 | github.com/hashicorp/terraform-config-inspect v0.0.0-20211115214459-90acf1ca460f/go.mod h1:Z0Nnk4+3Cy89smEbrq+sl1bxc9198gIP4I7wcQF6Kqs= 35 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 36 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 37 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 38 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 39 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 40 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 41 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 42 | github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= 43 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= 44 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 45 | github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= 46 | github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= 47 | github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= 48 | github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= 49 | github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= 50 | github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= 51 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 52 | github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= 53 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 54 | github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 55 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 56 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 57 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 58 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 59 | github.com/tmccombs/hcl2json v0.3.3 h1:+DLNYqpWE0CsOQiEZu+OZm5ZBImake3wtITYxQ8uLFQ= 60 | github.com/tmccombs/hcl2json v0.3.3/go.mod h1:Y2chtz2x9bAeRTvSibVRVgbLJhLJXKlUeIvjeVdnm4w= 61 | github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= 62 | github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= 63 | github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= 64 | github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= 65 | github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= 66 | github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= 67 | github.com/zclconf/go-cty v1.8.1 h1:SI0LqNeNxAgv2WWqWJMlG2/Ad/6aYJ7IVYYMigmfkuI= 68 | github.com/zclconf/go-cty v1.8.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= 69 | github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= 70 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 71 | golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 72 | golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 73 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 74 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= 75 | golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 76 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 77 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 78 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 79 | golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 80 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 81 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 82 | golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= 83 | golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 84 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 85 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 86 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 87 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 88 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 89 | google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 90 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 91 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 92 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 93 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 94 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 95 | -------------------------------------------------------------------------------- /internal/arguments/arguments.go: -------------------------------------------------------------------------------- 1 | package arguments 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/google/shlex" 9 | "github.com/raymondbutcher/ltf" 10 | ) 11 | 12 | // Arguments contains information about the arguments passed into the LTF 13 | // program via command line arguments and the TF_CLI_ARGS 14 | // and TF_CLI_ARGS_name environment variables. 15 | type Arguments struct { 16 | // Bin is the command that was run. 17 | Bin string 18 | 19 | // Args holds command line arguments, including the value of Bin as Args[0]. 20 | Args []string 21 | 22 | // Virtual holds the combined arguments from Args and also extra arguments 23 | // provided by the `TF_CLI_ARGS` and `TF_CLI_ARGS_name` environment variables. 24 | Virtual []string 25 | 26 | // EnvToJson is true if the -env-to-json flag was specified. 27 | // This is a special LTF flag used by the hooks system. 28 | EnvToJson bool 29 | 30 | // Chdir is the value of the -chdir global option if specified. 31 | Chdir string 32 | 33 | // Help is true if the -help global option is specified. 34 | Help bool 35 | 36 | // Version is true if the -version global option is specified 37 | // or the subcommand is "version". 38 | Version bool 39 | 40 | // Subcommand is the first non-flag argument if there is one. 41 | Subcommand string 42 | } 43 | 44 | // New populates and returns an arguments struct. 45 | func New(args []string, env ltf.Environ) (*Arguments, error) { 46 | if len(args) == 0 { 47 | return nil, errors.New("not enough arguments") 48 | } 49 | 50 | a := Arguments{} 51 | a.Args = args 52 | a.Bin = args[0] 53 | a.EnvToJson = len(args) > 1 && args[1] == "-env-to-json" 54 | 55 | virtual, err := combine(args, env) 56 | if err != nil { 57 | return &a, err 58 | } 59 | a.Virtual = virtual 60 | 61 | for _, arg := range virtual[1:] { 62 | if a.Subcommand == "" && len(arg) > 0 && arg[0:1] != "-" { 63 | a.Subcommand = arg 64 | } else if arg == "-help" { 65 | a.Help = true 66 | } else if arg == "-version" { 67 | a.Version = true 68 | } else if strings.HasPrefix(arg, "-chdir=") { 69 | a.Chdir = arg[7:] 70 | } 71 | } 72 | 73 | // Version can be called as a flag (handled above) or as a subcommand. 74 | if a.Subcommand == "version" { 75 | a.Version = true 76 | } 77 | 78 | return &a, err 79 | } 80 | 81 | // clean converts `-var value` and `-var-file value` arguments 82 | // into `-var=value` and `-var-file=value` respectively. 83 | func clean(args []string) []string { 84 | result := []string{} 85 | for i := 0; i < len(args); i++ { 86 | arg := args[i] 87 | if (arg == "-var" || arg == "-var-file") && i < len(args)-1 { 88 | result = append(result, arg+"="+args[i+1]) 89 | i = i + 1 90 | } else { 91 | result = append(result, arg) 92 | } 93 | } 94 | return result 95 | } 96 | 97 | // combine returns the combined arguments from the CLI arguments 98 | // and the TF_CLI_ARGS and TF_CLI_ARGS_name environment variables. 99 | func combine(args []string, env ltf.Environ) ([]string, error) { 100 | args = clean(args) 101 | 102 | result := []string{args[0]} 103 | subcommand := "" 104 | afterEnvArgs := []string{} 105 | 106 | for _, arg := range args[1:] { 107 | if subcommand == "" { 108 | result = append(result, arg) 109 | if arg[0:1] != "-" { 110 | subcommand = arg 111 | } 112 | } else { 113 | afterEnvArgs = append(afterEnvArgs, arg) 114 | } 115 | } 116 | 117 | if envArgs, err := shlex.Split(env.GetValue("TF_CLI_ARGS")); err != nil { 118 | return nil, fmt.Errorf("parsing %s: %w", "TF_CLI_ARGS", err) 119 | } else { 120 | envArgs = clean(envArgs) 121 | for _, arg := range envArgs { 122 | if subcommand == "" && arg[0:1] != "-" { 123 | subcommand = arg 124 | } 125 | result = append(result, arg) 126 | } 127 | } 128 | 129 | if subcommand != "" { 130 | envName := "TF_CLI_ARGS_" + subcommand 131 | if envArgs, err := shlex.Split(env.GetValue(envName)); err != nil { 132 | return nil, fmt.Errorf("parsing %s: %w", envName, err) 133 | } else { 134 | envArgs = clean(envArgs) 135 | result = append(result, envArgs...) 136 | } 137 | } 138 | 139 | result = append(result, afterEnvArgs...) 140 | 141 | return result, nil 142 | } 143 | -------------------------------------------------------------------------------- /internal/arguments/arguments_test.go: -------------------------------------------------------------------------------- 1 | package arguments 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/matryer/is" 7 | "github.com/raymondbutcher/ltf" 8 | ) 9 | 10 | func testArgs(t *testing.T, args []string, env ltf.Environ, expected Arguments) { 11 | is := is.New(t) 12 | 13 | // Already arranged 14 | 15 | // Act 16 | 17 | got, err := New(args, env) 18 | is.NoErr(err) 19 | 20 | // Assert 21 | 22 | is.Equal(got.Bin, expected.Bin) 23 | is.Equal(got.Args, expected.Args) 24 | is.Equal(got.Virtual, expected.Virtual) 25 | is.Equal(got.Chdir, expected.Chdir) 26 | is.Equal(got.Subcommand, expected.Subcommand) 27 | is.Equal(got.Help, expected.Help) 28 | is.Equal(got.Version, expected.Version) 29 | } 30 | 31 | func TestArgumentsChdir(t *testing.T) { 32 | testArgs(t, []string{"ltf", "-chdir=..", "plan"}, ltf.NewEnviron(), Arguments{ 33 | Bin: "ltf", 34 | Args: []string{"ltf", "-chdir=..", "plan"}, 35 | Virtual: []string{"ltf", "-chdir=..", "plan"}, 36 | Chdir: "..", 37 | Subcommand: "plan", 38 | }) 39 | } 40 | 41 | func TestArgumentsHelp(t *testing.T) { 42 | t.Run("flag", func(t *testing.T) { 43 | testArgs(t, []string{"ltf", "-help"}, ltf.NewEnviron(), Arguments{ 44 | Bin: "ltf", 45 | Args: []string{"ltf", "-help"}, 46 | Virtual: []string{"ltf", "-help"}, 47 | Help: true, // the flag should work 48 | }) 49 | }) 50 | 51 | t.Run("subcommand", func(t *testing.T) { 52 | testArgs(t, []string{"ltf", "help"}, ltf.NewEnviron(), Arguments{ 53 | Bin: "ltf", 54 | Args: []string{"ltf", "help"}, 55 | Virtual: []string{"ltf", "help"}, 56 | Subcommand: "help", 57 | Help: false, // the subcommand is not correct usage 58 | }) 59 | }) 60 | } 61 | 62 | func TestArgumentsEmpty(t *testing.T) { 63 | testArgs(t, []string{"ltf"}, ltf.NewEnviron(), Arguments{ 64 | Bin: "ltf", 65 | Args: []string{"ltf"}, 66 | Virtual: []string{"ltf"}, 67 | }) 68 | } 69 | 70 | func TestArgumentsVars(t *testing.T) { 71 | t.Run("combined var arg", func(t *testing.T) { 72 | testArgs(t, []string{"ltf", "plan", "-var=one=1"}, ltf.NewEnviron(), Arguments{ 73 | Bin: "ltf", 74 | Args: []string{"ltf", "plan", "-var=one=1"}, 75 | Virtual: []string{"ltf", "plan", "-var=one=1"}, 76 | Subcommand: "plan", 77 | }) 78 | }) 79 | 80 | t.Run("separate var args", func(t *testing.T) { 81 | testArgs(t, []string{"ltf", "plan", "-var", "one=1"}, ltf.NewEnviron(), Arguments{ 82 | Bin: "ltf", 83 | Args: []string{"ltf", "plan", "-var", "one=1"}, 84 | Virtual: []string{"ltf", "plan", "-var=one=1"}, 85 | Subcommand: "plan", 86 | }) 87 | }) 88 | 89 | t.Run("combined var-file arg", func(t *testing.T) { 90 | testArgs(t, []string{"ltf", "plan", "-var-file=test.tfvars"}, ltf.NewEnviron(), Arguments{ 91 | Bin: "ltf", 92 | Args: []string{"ltf", "plan", "-var-file=test.tfvars"}, 93 | Virtual: []string{"ltf", "plan", "-var-file=test.tfvars"}, 94 | Subcommand: "plan", 95 | }) 96 | }) 97 | 98 | t.Run("separate var-file args", func(t *testing.T) { 99 | testArgs(t, []string{"ltf", "plan", "-var-file", "test.tfvars"}, ltf.NewEnviron(), Arguments{ 100 | Bin: "ltf", 101 | Args: []string{"ltf", "plan", "-var-file", "test.tfvars"}, 102 | Virtual: []string{"ltf", "plan", "-var-file=test.tfvars"}, 103 | Subcommand: "plan", 104 | }) 105 | }) 106 | 107 | // From the Terraform docs: 108 | // These arguments are inserted directly after the subcommand (such as plan) 109 | // and before any flags specified directly on the command-line. This behavior 110 | // ensures that flags on the command-line take precedence over environment variables. 111 | 112 | t.Run("env args", func(t *testing.T) { 113 | testArgs(t, []string{"ltf", "plan", "-var", "one=1"}, ltf.NewEnviron("TF_CLI_ARGS=-var=two=2 -var three=3"), Arguments{ 114 | Bin: "ltf", 115 | Args: []string{"ltf", "plan", "-var", "one=1"}, 116 | Virtual: []string{"ltf", "plan", "-var=two=2", "-var=three=3", "-var=one=1"}, 117 | Subcommand: "plan", 118 | }) 119 | }) 120 | 121 | t.Run("subcommand env args", func(t *testing.T) { 122 | testArgs(t, []string{"ltf", "plan", "-var", "one=1"}, ltf.NewEnviron("TF_CLI_ARGS_plan=-var=two=2"), Arguments{ 123 | Bin: "ltf", 124 | Args: []string{"ltf", "plan", "-var", "one=1"}, 125 | Virtual: []string{"ltf", "plan", "-var=two=2", "-var=one=1"}, 126 | Subcommand: "plan", 127 | }) 128 | }) 129 | 130 | t.Run("wrong subcommand env args", func(t *testing.T) { 131 | // When doing a "plan" subcommand, TF_CLI_ARGS_apply should be ignored (apply != plan). 132 | testArgs(t, []string{"ltf", "plan", "-var", "one=1"}, ltf.NewEnviron("TF_CLI_ARGS_apply=-var=two=2"), Arguments{ 133 | Bin: "ltf", 134 | Args: []string{"ltf", "plan", "-var", "one=1"}, 135 | Virtual: []string{"ltf", "plan", "-var=one=1"}, 136 | Subcommand: "plan", 137 | }) 138 | }) 139 | } 140 | 141 | func TestArgumentsVersion(t *testing.T) { 142 | // Test with the flag, the correct way. 143 | testArgs(t, []string{"ltf", "-version"}, ltf.NewEnviron(), Arguments{ 144 | Bin: "ltf", 145 | Args: []string{"ltf", "-version"}, 146 | Virtual: []string{"ltf", "-version"}, 147 | Version: true, 148 | }) 149 | 150 | // Test with a subcommand, also the correct way. 151 | testArgs(t, []string{"ltf", "version"}, ltf.NewEnviron(), Arguments{ 152 | Bin: "ltf", 153 | Args: []string{"ltf", "version"}, 154 | Virtual: []string{"ltf", "version"}, 155 | Subcommand: "version", 156 | Version: true, 157 | }) 158 | } 159 | -------------------------------------------------------------------------------- /internal/backend/backend.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "sort" 7 | 8 | "github.com/hashicorp/hcl/v2" 9 | "github.com/hashicorp/hcl/v2/gohcl" 10 | "github.com/hashicorp/hcl/v2/hclparse" 11 | "github.com/raymondbutcher/ltf/internal/filesystem" 12 | "github.com/raymondbutcher/ltf/internal/variable" 13 | "github.com/zclconf/go-cty/cty" 14 | "github.com/zclconf/go-cty/cty/gocty" 15 | "github.com/zclconf/go-cty/cty/json" 16 | ) 17 | 18 | // LoadConfiguration reads *.tfbackend files from the specified directories, 19 | // renders them with Terraform variables, and returns a backend configuration. 20 | func LoadConfiguration(dirs []string, chdir string, vars variable.Variables) (map[string]string, error) { 21 | filenames, err := findBackendFiles(dirs, chdir) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | backend := map[string]string{} 27 | 28 | for _, filename := range filenames { 29 | if config, err := parseBackendFile(filename, vars); err != nil { 30 | return nil, err 31 | } else { 32 | for name, value := range config { 33 | backend[name] = value 34 | } 35 | } 36 | } 37 | 38 | return backend, nil 39 | } 40 | 41 | // findBackendFiles returns *.tfbackend files to use for the Terraform backend configuration. 42 | func findBackendFiles(dirs []string, chdir string) (filenames []string, err error) { 43 | // Start at the highest directory (configuration directory) 44 | // and go deeper towards the current directory. 45 | // Files in the current directory take precedence 46 | // over files in parent directories. 47 | for i := len(dirs) - 1; i >= 0; i-- { 48 | dir := dirs[i] 49 | 50 | // Get a sorted list of files in this directory. 51 | files, err := filesystem.ReadNames(dir) 52 | if err != nil { 53 | return nil, err 54 | } 55 | sort.Strings(files) 56 | 57 | // Add any matching backend files. 58 | for _, name := range filesystem.MatchNames(files, "*.tfbackend") { 59 | filenames = append(filenames, path.Join(dir, name)) 60 | } 61 | } 62 | 63 | return filenames, nil 64 | } 65 | 66 | // parseBackendFile parses a *.tfbackend file as HCL into a map of strings. 67 | // Variables can be used in the same way as *.tf files using the `var` object. 68 | func parseBackendFile(filename string, vars variable.Variables) (map[string]string, error) { 69 | // Parse the file. 70 | p := hclparse.NewParser() 71 | file, diags := p.ParseHCLFile(filename) 72 | if diags.HasErrors() { 73 | return nil, fmt.Errorf("parsing %s: %s", filename, diags.Error()) 74 | } 75 | 76 | // Decode the file into a map of cty values. 77 | values := map[string]cty.Value{} 78 | ctx, err := varEvalContext(vars) 79 | if err != nil { 80 | return nil, fmt.Errorf("creating backend context for %s: %w", filename, err) 81 | } 82 | diags = gohcl.DecodeBody(file.Body, ctx, &values) 83 | if diags.HasErrors() { 84 | return nil, fmt.Errorf("decoding hcl %s: %s", filename, diags.Error()) 85 | } 86 | 87 | // Convert the cty values into strings. 88 | strings := map[string]string{} 89 | for key, val := range values { 90 | if val.Type() == cty.String { 91 | var s string 92 | err := gocty.FromCtyValue(val, &s) 93 | if err != nil { 94 | return nil, fmt.Errorf("converting string value in %s: %w", filename, err) 95 | } 96 | strings[key] = s 97 | } else { 98 | b, err := json.Marshal(val, val.Type()) 99 | if err != nil { 100 | return nil, fmt.Errorf("converting non-string value in %s: %w", filename, err) 101 | } 102 | strings[key] = string(b) 103 | } 104 | } 105 | 106 | return strings, nil 107 | } 108 | 109 | // varEvalContext returns an EvalContext with a `var` object containing variables. 110 | func varEvalContext(vars variable.Variables) (*hcl.EvalContext, error) { 111 | values := map[string]cty.Value{} 112 | for _, v := range vars { 113 | ct, err := gocty.ImpliedType(v.AnyValue) 114 | if err != nil { 115 | return nil, fmt.Errorf("getting cty type for var.%s (%v): %w", v.Name, v.AnyValue, err) 116 | } 117 | cv, err := gocty.ToCtyValue(v.AnyValue, ct) 118 | if err != nil { 119 | return nil, fmt.Errorf("converting to cty type: %w", err) 120 | } 121 | values[v.Name] = cv 122 | } 123 | ctx := hcl.EvalContext{} 124 | ctx.Variables = map[string]cty.Value{ 125 | "var": cty.ObjectVal(values), 126 | } 127 | return &ctx, nil 128 | } 129 | -------------------------------------------------------------------------------- /internal/backend/backend_test.auto.tfvars: -------------------------------------------------------------------------------- 1 | stack = "vpc" 2 | region = "eu-west-1" 3 | extra = { "eu-west-1" = "success" } 4 | -------------------------------------------------------------------------------- /internal/backend/backend_test.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path" 7 | "testing" 8 | 9 | "github.com/matryer/is" 10 | "github.com/raymondbutcher/ltf" 11 | "github.com/raymondbutcher/ltf/internal/arguments" 12 | "github.com/raymondbutcher/ltf/internal/variable" 13 | ) 14 | 15 | func TestParseBackendFile(t *testing.T) { 16 | is := is.New(t) 17 | 18 | // Arrange 19 | 20 | tempDir, err := os.MkdirTemp("", "ltf-test-") 21 | is.NoErr(err) // error making temporary directory 22 | defer os.RemoveAll(tempDir) 23 | 24 | contents, err := ioutil.ReadFile("backend_test.tfbackend") 25 | is.NoErr(err) // error reading file 26 | filename := path.Join(tempDir, "s3.tfbackend") 27 | err = ioutil.WriteFile(filename, contents, 06666) 28 | is.NoErr(err) // error writing file 29 | 30 | args, err := arguments.New([]string{"ltf"}, ltf.NewEnviron()) 31 | is.NoErr(err) // error creating arguments 32 | vars, err := variable.Load(args, []string{"."}, ".") 33 | is.NoErr(err) // error loading variables 34 | 35 | // Act 36 | 37 | values, err := parseBackendFile(filename, vars) 38 | is.NoErr(err) 39 | 40 | // Assert 41 | 42 | is.Equal(values["bucket"], "some-bucket") 43 | is.Equal(values["key"], "vpc/terraform.tfstate") 44 | is.Equal(values["region"], "eu-west-1") 45 | is.Equal(values["extra"], "success") 46 | is.Equal(values["encrypted"], "true") 47 | } 48 | -------------------------------------------------------------------------------- /internal/backend/backend_test.tf: -------------------------------------------------------------------------------- 1 | // Need to define non-string variables for the value to be parsed as a non-string. 2 | variable "extra" { 3 | type = map(string) 4 | } 5 | -------------------------------------------------------------------------------- /internal/backend/backend_test.tfbackend: -------------------------------------------------------------------------------- 1 | bucket = "some-bucket" 2 | key = "${var.stack}/terraform.tfstate" 3 | region = var.region 4 | extra = var.extra[var.region] 5 | encrypted = true 6 | -------------------------------------------------------------------------------- /internal/filesystem/filesystem.go: -------------------------------------------------------------------------------- 1 | package filesystem 2 | 3 | import ( 4 | "os" 5 | "path" 6 | "path/filepath" 7 | 8 | "github.com/raymondbutcher/ltf/internal/arguments" 9 | ) 10 | 11 | func FindDirs(cwd string, args *arguments.Arguments) (dirs []string, chdir string, err error) { 12 | // Returns directories to use, including the directory to change to. 13 | // Subtle: chdir is sometimes cwd and won't be used 14 | // Subtle: dirs always includes chdir (which may be cwd) 15 | 16 | if args.Chdir != "" { 17 | // The -chdir argument was provided. 18 | chdir, err = filepath.Abs(chdir) 19 | if err != nil { 20 | return nil, "", err 21 | } 22 | // Find directories to use for variables/backend files. 23 | dirs, err = findDirsWithChdir(cwd, chdir) 24 | if err != nil { 25 | return nil, "", err 26 | } 27 | } else { 28 | // Find the configuration directory to use, 29 | // and directories to use for variables/backend files. 30 | dirs, err = findDirsWithoutChdir(cwd) 31 | if err != nil { 32 | return nil, "", err 33 | } 34 | chdir = dirs[len(dirs)-1] 35 | } 36 | return dirs, chdir, nil 37 | } 38 | 39 | func findDirsWithChdir(cwd string, chdir string) ([]string, error) { 40 | // Returns directories between the current directory and the specified 41 | // chdir directory. If the chdir directory is not a parent directory 42 | // of the current directory, then only the current directory and 43 | // the chdir directory are returned. 44 | 45 | var err error 46 | 47 | dir := cwd 48 | dirs := []string{} 49 | 50 | for { 51 | dirs = append(dirs, dir) 52 | 53 | // Stop if this is chdir directory. 54 | if dir == chdir { 55 | return dirs, nil 56 | } 57 | 58 | // Otherwise, move to the parent directory. 59 | dir, err = filepath.Abs(path.Dir(dir)) 60 | if err != nil { 61 | return nil, err 62 | } 63 | 64 | // Stop if this directory was already checked. 65 | // This occurs after reaching the filesystem root. 66 | if dir == dirs[len(dirs)-1] { 67 | // Because the chdir directory was not found in the parents, 68 | // return only the current directory and the chdir directory. 69 | if cwd == chdir { 70 | return []string{cwd}, nil 71 | } else { 72 | return []string{cwd, chdir}, nil 73 | } 74 | } 75 | } 76 | } 77 | 78 | func findDirsWithoutChdir(cwd string) ([]string, error) { 79 | // Returns all directories between the current directory 80 | // and a parent directory containing Terraform configuration files, 81 | // which will be used as the configuration directory. If no configuration 82 | // directory is found, then only the current directory is returned. 83 | 84 | var err error 85 | var files []string 86 | 87 | dir := cwd 88 | dirs := []string{} 89 | 90 | for { 91 | dirs = append(dirs, dir) 92 | 93 | // Stop if this directory contains configuration files. 94 | if files, err = ReadNames(dir); err != nil { 95 | return nil, err 96 | } else if len(MatchNames(files, "*.tf")) > 0 || len(MatchNames(files, "*.tf.json")) > 0 { 97 | return dirs, nil 98 | } 99 | 100 | // Otherwise, move to the parent directory. 101 | dir, err = filepath.Abs(path.Dir(dir)) 102 | if err != nil { 103 | return nil, err 104 | } 105 | 106 | // Stop if this directory was already checked. 107 | // This occurs after reaching the filesystem root. 108 | if dir == dirs[len(dirs)-1] { 109 | // Because no configuration directory was found, 110 | // return only the current directory. 111 | return []string{cwd}, nil 112 | } 113 | } 114 | } 115 | 116 | func MatchNames(files []string, pattern string) []string { 117 | matches := []string{} 118 | for _, name := range files { 119 | if matched, _ := path.Match(pattern, name); matched { 120 | matches = append(matches, name) 121 | } 122 | } 123 | return matches 124 | } 125 | 126 | func ReadNames(dir string) ([]string, error) { 127 | file, err := os.Open(dir) 128 | if err != nil { 129 | return nil, err 130 | } 131 | names, err := file.Readdirnames(0) 132 | if err != nil { 133 | return nil, err 134 | } 135 | return names, err 136 | } 137 | -------------------------------------------------------------------------------- /internal/hook/hook.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "os/exec" 10 | 11 | "github.com/raymondbutcher/ltf" 12 | "github.com/raymondbutcher/ltf/internal/arguments" 13 | ) 14 | 15 | var scriptPreamble = fmt.Sprintf(`#!/bin/bash 16 | exec 3>&1 # redirect 3 to stdout 17 | exec 1>&2 # redirect stdout to sterr 18 | __ltf_env_to_json () { 19 | local code=$? 20 | if [ $code -eq 0 ]; then 21 | "%s" -env-to-json >&3 22 | fi 23 | trap - EXIT 24 | exit $code 25 | } 26 | trap __ltf_env_to_json EXIT 27 | `, os.Args[0]) 28 | 29 | type Hook struct { 30 | Name string 31 | Before []string `yaml:"before"` 32 | After []string `yaml:"after"` 33 | Failed []string `yaml:"failed"` 34 | Script string `yaml:"script"` 35 | } 36 | 37 | // Match reports whether the hook matches the given event and command combination. 38 | func (h *Hook) Match(when string, args *arguments.Arguments) bool { 39 | hookCmds := []string{} 40 | if when == "before" { 41 | hookCmds = h.Before 42 | } else if when == "after" { 43 | hookCmds = h.After 44 | } else if when == "failed" { 45 | hookCmds = h.Failed 46 | } 47 | for _, hookCmd := range hookCmds { 48 | if hookCmd == "terraform" { 49 | return true 50 | } else if args.Subcommand != "" && hookCmd == "terraform "+args.Subcommand { 51 | return true 52 | } 53 | } 54 | return false 55 | } 56 | 57 | // Run executes the hook script and returns the potentially modified environment variables. 58 | func (h *Hook) Run(env ltf.Environ) (modifiedEnv ltf.Environ, err error) { 59 | fmt.Fprintf(os.Stderr, "# %s\n", h.Name) 60 | 61 | hookCmd := exec.Command("bash", "-c", scriptPreamble+h.Script) 62 | hookCmd.Env = env 63 | hookCmd.Stdin = os.Stdin 64 | hookCmd.Stderr = os.Stderr 65 | 66 | stdout, err := hookCmd.StdoutPipe() 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | if err := hookCmd.Start(); err != nil { 72 | return nil, err 73 | } 74 | 75 | bytes, err := ioutil.ReadAll(stdout) 76 | if err != nil { 77 | return nil, err 78 | } 79 | 80 | if err := hookCmd.Wait(); err != nil { 81 | return nil, err 82 | } 83 | 84 | if len(bytes) == 0 { 85 | return nil, errors.New("wrapper script failed to output environment variables") 86 | } 87 | 88 | err = json.Unmarshal(bytes, &modifiedEnv) 89 | if err != nil { 90 | return nil, err 91 | } 92 | 93 | return modifiedEnv, nil 94 | } 95 | -------------------------------------------------------------------------------- /internal/hook/hook_test.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/matryer/is" 7 | "github.com/raymondbutcher/ltf" 8 | "github.com/raymondbutcher/ltf/internal/arguments" 9 | ) 10 | 11 | func TestHookMatch(t *testing.T) { 12 | is := is.New(t) 13 | 14 | t.Run("only before terraform", func(t *testing.T) { 15 | // Arrange 16 | 17 | h := Hook{ 18 | Before: []string{"terraform"}, 19 | After: []string{}, 20 | Failed: []string{}, 21 | } 22 | 23 | t.Run("with subcommand", func(t *testing.T) { 24 | // Act 25 | 26 | args, err := arguments.New([]string{"terraform", "plan"}, ltf.NewEnviron()) 27 | is.NoErr(err) 28 | 29 | // Assert 30 | 31 | is.Equal(h.Match("before", args), true) 32 | is.Equal(h.Match("after", args), false) 33 | is.Equal(h.Match("failed", args), false) 34 | }) 35 | 36 | t.Run("without subcommand", func(t *testing.T) { 37 | // Act 38 | 39 | args, err := arguments.New([]string{"terraform"}, ltf.NewEnviron()) 40 | is.NoErr(err) 41 | 42 | // Assert 43 | 44 | is.Equal(h.Match("before", args), true) 45 | is.Equal(h.Match("after", args), false) 46 | is.Equal(h.Match("failed", args), false) 47 | }) 48 | 49 | }) 50 | 51 | t.Run("only after terraform apply", func(t *testing.T) { 52 | // Arrange 53 | 54 | h := Hook{ 55 | Before: []string{"terraform init"}, 56 | After: []string{"terraform init", "terraform apply"}, 57 | Failed: []string{"terraform init"}, 58 | } 59 | 60 | t.Run("with subcommand", func(t *testing.T) { 61 | // Act 62 | 63 | args, err := arguments.New([]string{"terraform", "apply"}, ltf.NewEnviron()) 64 | is.NoErr(err) 65 | 66 | // Assert 67 | 68 | is.Equal(h.Match("before", args), false) 69 | is.Equal(h.Match("after", args), true) 70 | is.Equal(h.Match("failed", args), false) 71 | }) 72 | 73 | t.Run("without subcommand", func(t *testing.T) { 74 | // Act 75 | 76 | args, err := arguments.New([]string{"terraform"}, ltf.NewEnviron()) 77 | is.NoErr(err) 78 | 79 | // Assert 80 | 81 | is.Equal(h.Match("before", args), false) 82 | is.Equal(h.Match("after", args), false) 83 | is.Equal(h.Match("failed", args), false) 84 | }) 85 | 86 | t.Run("with wrong subcommand", func(t *testing.T) { 87 | // Act 88 | 89 | args, err := arguments.New([]string{"terraform", "plan"}, ltf.NewEnviron()) 90 | is.NoErr(err) 91 | 92 | // Assert 93 | 94 | is.Equal(h.Match("before", args), false) 95 | is.Equal(h.Match("after", args), false) 96 | is.Equal(h.Match("failed", args), false) 97 | }) 98 | }) 99 | } 100 | -------------------------------------------------------------------------------- /internal/hook/hooks.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | import ( 4 | "fmt" 5 | "os/exec" 6 | "strings" 7 | 8 | "github.com/raymondbutcher/ltf/internal/arguments" 9 | "github.com/raymondbutcher/ltf/internal/variable" 10 | ) 11 | 12 | type Hooks map[string]*Hook 13 | 14 | func (m Hooks) Run(when string, cmd *exec.Cmd, args *arguments.Arguments, vars variable.Variables) error { 15 | for _, h := range m { 16 | if h.Match(when, args) { 17 | modifiedEnv, err := h.Run(cmd.Env) 18 | if err != nil { 19 | return err 20 | } 21 | 22 | for _, env := range modifiedEnv { 23 | s := strings.SplitN(env, "=", 2) 24 | if len(s) == 2 { 25 | name := s[0] 26 | if len(name) > 7 && name[:7] == "TF_VAR_" { 27 | name = name[7:] 28 | value := s[1] 29 | v, err := vars.SetValue(name, value, false) 30 | if err != nil { 31 | return fmt.Errorf("hook %s: %w", h.Name, err) 32 | } 33 | v.Print() 34 | } 35 | } 36 | } 37 | cmd.Env = modifiedEnv 38 | } 39 | } 40 | return nil 41 | } 42 | -------------------------------------------------------------------------------- /internal/ltf/ltf.go: -------------------------------------------------------------------------------- 1 | package ltf 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "os/exec" 8 | "path" 9 | "path/filepath" 10 | "strings" 11 | 12 | "github.com/raymondbutcher/ltf" 13 | "github.com/raymondbutcher/ltf/internal/arguments" 14 | "github.com/raymondbutcher/ltf/internal/backend" 15 | "github.com/raymondbutcher/ltf/internal/filesystem" 16 | "github.com/raymondbutcher/ltf/internal/hook" 17 | "github.com/raymondbutcher/ltf/internal/settings" 18 | "github.com/raymondbutcher/ltf/internal/variable" 19 | ) 20 | 21 | const helpMessage = `LTF is a transparent wrapper for Terraform; it passes all command line 22 | arguments and environment variables through to Terraform. LTF also checks 23 | the current directory and parent directories for various Terraform files 24 | and alters the command line arguments and environment variables to make 25 | Terraform use them. 26 | 27 | LTF also executes hooks defined in the first 'ltf.yaml' file it finds 28 | in the current directory or parent directories. This can be used to run 29 | commands or modify the environment before and after Terraform runs.` 30 | 31 | func Run(cwd string, args *arguments.Arguments, env ltf.Environ) (cmd *exec.Cmd, exitStatus int, err error) { 32 | // Special mode to output environment variables after running a hook script. 33 | // It outputs in JSON format to avoid issues with multi-line variables. 34 | if args.EnvToJson { 35 | envJsonBytes, err := json.Marshal(env) 36 | if err != nil { 37 | return nil, 1, fmt.Errorf("%s: error in env-to-json: %w", args.Bin, err) 38 | } 39 | fmt.Print(string(envJsonBytes)) 40 | return nil, 0, nil 41 | } 42 | 43 | // Find and load the optional settings file to get hooks. 44 | var hooks hook.Hooks 45 | if s, err := settings.Load(cwd); err != nil { 46 | return nil, 1, fmt.Errorf("error loading ltf settings: %w", err) 47 | } else { 48 | hooks = s.Hooks 49 | } 50 | 51 | // Skip some chdir and variables functionality for these commands. 52 | skipMode := args.Help || args.Version || args.Subcommand == "" || args.Subcommand == "fmt" 53 | 54 | // Determine the directories to use. 55 | dirs := []string{} 56 | chdir := "" 57 | if !skipMode { 58 | cwd, err = filepath.Abs(cwd) 59 | if err != nil { 60 | return nil, 1, fmt.Errorf("error reading path: %w", err) 61 | } 62 | dirs, chdir, err = filesystem.FindDirs(cwd, args) 63 | if err != nil { 64 | return nil, 1, fmt.Errorf("error finding directories: %w", err) 65 | } 66 | } 67 | 68 | // Set the data directory to the current directory. 69 | if !skipMode && env.GetValue("TF_DATA_DIR") == "" && chdir != cwd { 70 | cwdFromChdir, err := filepath.Rel(chdir, cwd) 71 | if err != nil { 72 | return nil, 1, fmt.Errorf("error reading path: %w", err) 73 | } 74 | dataDir := path.Join(cwdFromChdir, ".terraform") 75 | env = env.SetValue("TF_DATA_DIR", dataDir) 76 | fmt.Fprintf(os.Stderr, "+ TF_DATA_DIR=%s\n", dataDir) 77 | } 78 | 79 | // Load variables from all possible sources. 80 | vars := variable.Variables{} 81 | if !skipMode { 82 | vars, err = variable.Load(args, dirs, chdir) 83 | if err != nil { 84 | return nil, 1, fmt.Errorf("error loading variables: %w", err) 85 | } 86 | for _, v := range vars { 87 | env = env.SetValue("TF_VAR_"+v.Name, v.StringValue) 88 | if v.StringValue != "" { 89 | v.Print() 90 | } 91 | } 92 | } 93 | 94 | // Build the Terraform command to run. 95 | cmd = exec.Command("terraform") 96 | cmd.Env = env 97 | cmd.Stdin = os.Stdin 98 | cmd.Stdout = os.Stdout 99 | cmd.Stderr = os.Stderr 100 | 101 | // Make Terraform change to the configuration directory 102 | // using the -chdir argument. 103 | if !skipMode && args.Chdir == "" && chdir != cwd { 104 | chdirFromCwd, err := filepath.Rel(cwd, chdir) 105 | if err != nil { 106 | return nil, 0, err 107 | } 108 | cmd.Args = append(cmd.Args, "-chdir="+chdirFromCwd) 109 | } 110 | 111 | // Pass all remaining command line arguments to Terraform. 112 | cmd.Args = append(cmd.Args, args.Args[1:]...) 113 | 114 | // Use backend configuration files. 115 | if !skipMode && args.Subcommand == "init" { 116 | backend, err := backend.LoadConfiguration(dirs, chdir, vars) 117 | if err != nil { 118 | return nil, 1, err 119 | } 120 | if len(backend) > 0 { 121 | // Build the -backend-config arguments. 122 | initArgs := []string{} 123 | for name, value := range backend { 124 | initArgs = append(initArgs, "-backend-config="+name+"="+value) 125 | } 126 | 127 | // Append the oldArgs TF_CLI_ARGS_init at the end so they take precedence 128 | // over the values generated by LTF. 129 | oldArgs := env.GetValue("TF_CLI_ARGS_init") 130 | if oldArgs != "" { 131 | initArgs = append(initArgs, oldArgs) 132 | } 133 | 134 | // Set the new environment variable value. 135 | newEnvValue := strings.Join(initArgs, " ") 136 | env = env.SetValue("TF_CLI_ARGS_init", newEnvValue) 137 | cmd.Env = env 138 | fmt.Fprintf(os.Stderr, "+ TF_CLI_ARGS_init=%s\n", newEnvValue) 139 | } 140 | } 141 | 142 | // Run any "before" hooks. 143 | if err := hooks.Run("before", cmd, args, vars); err != nil { 144 | return nil, 1, fmt.Errorf("error from hook: %w", err) 145 | } 146 | 147 | // Special cases to print messages before Terraform runs. 148 | if args.Help { 149 | fmt.Println(helpMessage) 150 | fmt.Println("") 151 | } else if args.Version { 152 | fmt.Printf("LTF %s\n\n", getVersion()) 153 | } 154 | 155 | // Run the Terraform command. 156 | exitCode := 0 157 | cmdString := strings.Join(cmd.Args, " ") 158 | if v := env.GetValue("LTF_TEST_MODE"); v != "" { 159 | fmt.Fprintf(os.Stderr, "# LTF_TEST_MODE=%s skipped %s\n", v, cmdString) 160 | } else { 161 | fmt.Fprintf(os.Stderr, "# %s\n", cmdString) 162 | if err := cmd.Run(); err != nil { 163 | if exitErr, isExitError := err.(*exec.ExitError); isExitError { 164 | exitCode = exitErr.ExitCode() 165 | } else { 166 | return nil, 1, fmt.Errorf("error running command: %w", err) 167 | } 168 | } 169 | } 170 | 171 | // Run any "after" or "failed" hooks. 172 | when := "after" 173 | if exitCode != 0 { 174 | when = "failed" 175 | } 176 | if err = hooks.Run(when, cmd, args, vars); err != nil { 177 | return nil, 1, fmt.Errorf("error from hook: %w", err) 178 | } 179 | 180 | return cmd, exitCode, nil 181 | } 182 | -------------------------------------------------------------------------------- /internal/ltf/ltf_test.go: -------------------------------------------------------------------------------- 1 | package ltf 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | "path" 9 | "strings" 10 | "testing" 11 | 12 | "github.com/hashicorp/hcl/v2/hclsimple" 13 | "github.com/matryer/is" 14 | "github.com/raymondbutcher/ltf" 15 | "github.com/raymondbutcher/ltf/internal/arguments" 16 | ) 17 | 18 | type TestConfig struct { 19 | Arranges []ArrangeConfig `hcl:"arrange,block"` 20 | } 21 | 22 | type ArrangeConfig struct { 23 | Name string `hcl:"name,label"` 24 | Files map[string]string `hcl:"files,optional"` 25 | Acts []ActConfig `hcl:"act,block"` 26 | Asserts []AssertConfig `hcl:"assert,block"` 27 | } 28 | 29 | type ActConfig struct { 30 | Name string `hcl:"name,label"` 31 | Env map[string]string `hcl:"env,optional"` 32 | Cwd string `hcl:"cwd,optional"` 33 | Cmd string `hcl:"cmd"` 34 | Asserts []AssertConfig `hcl:"assert,block"` 35 | } 36 | 37 | type AssertConfig struct { 38 | Name string `hcl:"name,label"` 39 | Cmd string `hcl:"cmd,optional"` 40 | Env map[string]string `hcl:"env,optional"` 41 | ExitCode int `hcl:"exit,optional"` 42 | } 43 | 44 | func TestSuite(t *testing.T) { 45 | var tests TestConfig 46 | if err := hclsimple.DecodeFile("ltf_test.hcl", nil, &tests); err != nil { 47 | log.Fatalf("Failed to load test suite: %s", err) 48 | } 49 | for _, arrange := range tests.Arranges { 50 | for _, act := range arrange.Acts { 51 | for _, assert := range append(act.Asserts, arrange.Asserts...) { 52 | name := fmt.Sprintf("arrange.%s/act.%s/assert.%s", arrange.Name, act.Name, assert.Name) 53 | t.Run(name, func(t *testing.T) { 54 | runTestCase(t, arrange, act, assert) 55 | }) 56 | } 57 | } 58 | } 59 | } 60 | 61 | func runTestCase(t *testing.T, arrange ArrangeConfig, act ActConfig, assert AssertConfig) { 62 | is := is.New(t) 63 | 64 | // Arrange 65 | 66 | tempDir, err := os.MkdirTemp("", "ltf-test-") 67 | is.NoErr(err) 68 | defer os.RemoveAll(tempDir) 69 | 70 | for fileName, fileContents := range arrange.Files { 71 | filePath := path.Join(tempDir, fileName) 72 | fileDir := path.Dir(filePath) 73 | err := os.MkdirAll(fileDir, os.ModePerm) 74 | is.NoErr(err) // error creating dir 75 | err = ioutil.WriteFile(filePath, []byte(fileContents), 06666) 76 | is.NoErr(err) // error creating file 77 | } 78 | 79 | // Act 80 | 81 | cwd := path.Join(tempDir, act.Cwd) 82 | env := ltf.NewEnviron("LTF_TEST_MODE=1") 83 | for key, val := range act.Env { 84 | env = env.SetValue(key, val) 85 | } 86 | args, err := arguments.New(strings.Split(act.Cmd, " "), env) 87 | is.NoErr(err) // error parsing arguments 88 | cmd, exitCode, err := Run(cwd, args, env) 89 | is.NoErr(err) 90 | 91 | // Assert 92 | 93 | is.Equal(exitCode, assert.ExitCode) // ltf exited with unexpected code 94 | 95 | if assert.Cmd != "" { 96 | is.Equal(strings.Join(cmd.Args, " "), assert.Cmd) // ltf did not generate the expected command 97 | } 98 | 99 | if len(assert.Env) > 0 { 100 | env := ltf.NewEnviron(cmd.Env...) 101 | for name, expected := range assert.Env { 102 | t.Run(name, func(t *testing.T) { 103 | is := is.New(t) 104 | actual := env.GetValue(name) 105 | is.Equal(actual, expected) // ltf did not set the expected environment variable 106 | }) 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /internal/ltf/ltf_test.hcl: -------------------------------------------------------------------------------- 1 | arrange "standard" { 2 | files = { 3 | "dev/dev.auto.tfvars" = "x = 1" 4 | "dev/dev.tfbackend" = "path = \"dev/dev.tfbackend\"" 5 | "main.tf" = "" 6 | } 7 | 8 | act "init" { 9 | cwd = "dev" 10 | cmd = "ltf init" 11 | 12 | assert "init" { 13 | cmd = "terraform -chdir=.. init" 14 | env = { 15 | TF_CLI_ARGS_init = "-backend-config=path=dev/dev.tfbackend" 16 | } 17 | } 18 | } 19 | 20 | act "plan" { 21 | cwd = "dev" 22 | cmd = "ltf plan -target=random_id.this" 23 | 24 | assert "cmd" { 25 | cmd = "terraform -chdir=.. plan -target=random_id.this" 26 | env = { 27 | TF_CLI_ARGS_init = "" 28 | } 29 | } 30 | } 31 | 32 | assert "both" { 33 | env = { 34 | TF_DATA_DIR = "dev/.terraform" 35 | TF_VAR_x = "1" 36 | } 37 | } 38 | } 39 | 40 | arrange "fmt" { 41 | files = { 42 | "main.tf" = "" 43 | "subdir/terraform.tfvars" = "x = 1" 44 | } 45 | 46 | act "fmt" { 47 | cwd = "subdir" 48 | cmd = "ltf fmt terraform.tfvars" 49 | } 50 | 51 | assert "fmt bypasses ltf" { 52 | cmd = "terraform fmt terraform.tfvars" 53 | env = { 54 | TF_DATA_DIR = "" 55 | TF_VAR_x = "" 56 | } 57 | } 58 | } 59 | 60 | arrange "variables" { 61 | files = { 62 | "live/blue/a.auto.tfvars" = <<-EOF 63 | x = "a" 64 | EOF 65 | "live/blue/d.auto.tfvars" = <<-EOF 66 | x = "d" # takes precedence in deepest directory 67 | EOF 68 | "live/b.auto.tfvars" = <<-EOF 69 | x = "b" 70 | y = "b" 71 | EOF 72 | "live/e.auto.tfvars" = <<-EOF 73 | x = "e" 74 | y = "e" # takes precedence in deepest directory 75 | EOF 76 | "live/terraform.tfvars" = <<-EOF 77 | x = "terraform" 78 | y = "terraform" 79 | EOF 80 | "c.auto.tfvars" = <<-EOF 81 | z = "c" 82 | EOF 83 | "f.auto.tfvars" = <<-EOF 84 | z = "f" # takes precedence in config directory and trying to override in subdirectories would lead to and error 85 | EOF 86 | "main.tf" = <<-EOF 87 | variable "def" { 88 | default = "main" 89 | } 90 | EOF 91 | } 92 | 93 | act "plan" { 94 | cwd = "live/blue" 95 | cmd = "ltf plan" 96 | } 97 | 98 | assert "args" { 99 | cmd = "terraform -chdir=../.. plan" 100 | env = { 101 | TF_DATA_DIR = "live/blue/.terraform" 102 | TF_CLI_ARGS_init = "" 103 | TF_CLI_ARGS_plan = "" 104 | TF_CLI_ARGS_apply = "" 105 | TF_VAR_x = "d" 106 | TF_VAR_y = "e" 107 | TF_VAR_z = "f" 108 | TF_VAR_def = "main" 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /internal/ltf/version.go: -------------------------------------------------------------------------------- 1 | package ltf 2 | 3 | // version is updated with -ldflags in the pipeline. 4 | var version = "development" 5 | 6 | func getVersion() string { 7 | return version 8 | } 9 | -------------------------------------------------------------------------------- /internal/settings/settings.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | import ( 4 | "io/ioutil" 5 | "path" 6 | "path/filepath" 7 | 8 | "github.com/raymondbutcher/ltf/internal/filesystem" 9 | "github.com/raymondbutcher/ltf/internal/hook" 10 | "gopkg.in/yaml.v2" 11 | ) 12 | 13 | type settings struct { 14 | Hooks hook.Hooks `yaml:"hooks"` 15 | } 16 | 17 | func Load(cwd string) (*settings, error) { 18 | file, err := findFile(cwd) 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | settings := settings{} 24 | 25 | if file == "" { 26 | return &settings, nil 27 | } 28 | 29 | rel, err := filepath.Rel(cwd, file) 30 | if err != nil { 31 | return nil, err 32 | } 33 | 34 | content, err := ioutil.ReadFile(rel) 35 | if err != nil { 36 | return nil, err 37 | } 38 | 39 | if err := yaml.UnmarshalStrict([]byte(content), &settings); err != nil { 40 | return nil, err 41 | } 42 | 43 | for name, hook := range settings.Hooks { 44 | hook.Name = name 45 | } 46 | 47 | return &settings, nil 48 | } 49 | 50 | // findFile returns the path to ltf.yaml in the current or parent directories, 51 | // or an empty string if not found. 52 | func findFile(dir string) (string, error) { 53 | lastDir := "" 54 | for { 55 | // Check this directory. 56 | names, err := filesystem.ReadNames(dir) 57 | if err != nil { 58 | return "", err 59 | } 60 | for _, name := range names { 61 | if name == "ltf.yaml" { 62 | return path.Join(dir, name), nil 63 | } 64 | } 65 | 66 | // Move to the parent directory. 67 | dir = path.Dir(dir) 68 | 69 | // Stop if this directory was already checked. 70 | // This occurs after reaching the filesystem root. 71 | if dir == lastDir { 72 | break 73 | } 74 | lastDir = dir 75 | } 76 | 77 | // Not found. 78 | return "", nil 79 | } 80 | -------------------------------------------------------------------------------- /internal/variable/variable.go: -------------------------------------------------------------------------------- 1 | package variable 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/zclconf/go-cty/cty" 8 | "github.com/zclconf/go-cty/cty/json" 9 | ) 10 | 11 | type Variable struct { 12 | Name string 13 | Type string 14 | AnyValue cty.Value 15 | StringValue string 16 | Sensitive bool 17 | Frozen bool 18 | } 19 | 20 | func New(name string, vtype string, value string) (*Variable, error) { 21 | v := &Variable{} 22 | v.Name = name 23 | v.Type = vtype 24 | err := v.SetValue(value) 25 | return v, err 26 | } 27 | 28 | func (v *Variable) Print() { 29 | if v.Sensitive { 30 | fmt.Fprintf(os.Stderr, "+ TF_VAR_%s=%s\n", v.Name, "(sensitive value)") 31 | } else { 32 | fmt.Fprintf(os.Stderr, "+ TF_VAR_%s=%s\n", v.Name, v.StringValue) 33 | } 34 | } 35 | 36 | func (v *Variable) SetValue(value string) error { 37 | if v.Type == "" || v.Type == "string" { 38 | v.AnyValue = cty.StringVal(value) 39 | } else if value == "" { 40 | v.AnyValue = cty.NilVal 41 | } else { 42 | j := json.SimpleJSONValue{} 43 | if err := j.UnmarshalJSON([]byte(value)); err != nil { 44 | return fmt.Errorf("parsing variable value: %w", err) 45 | } 46 | v.AnyValue = j.Value 47 | } 48 | v.StringValue = value 49 | return nil 50 | } 51 | -------------------------------------------------------------------------------- /internal/variable/variables.go: -------------------------------------------------------------------------------- 1 | package variable 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "path" 8 | "sort" 9 | "strings" 10 | 11 | "github.com/hashicorp/terraform-config-inspect/tfconfig" 12 | "github.com/raymondbutcher/ltf/internal/arguments" 13 | "github.com/raymondbutcher/ltf/internal/filesystem" 14 | "github.com/tmccombs/hcl2json/convert" 15 | ) 16 | 17 | type Variables map[string]*Variable 18 | 19 | // SetValue adds or updates a variable. If freeze is true, it sets the variable to Frozen, 20 | // and is able to update existing frozen variables. If freeze is false, and there is an 21 | // existing frozen variable with a different value, it will error. 22 | func (vars Variables) SetValue(name string, value string, freeze bool) (v *Variable, err error) { 23 | var found bool 24 | 25 | v, found = vars[name] 26 | if !found { 27 | if v, err = New(name, "", value); err != nil { 28 | return nil, err 29 | } 30 | vars[name] = v 31 | } 32 | 33 | if !freeze && v.Frozen && v.StringValue != value { 34 | return nil, fmt.Errorf("cannot change frozen variable %s", name) 35 | } 36 | 37 | if err := v.SetValue(value); err != nil { 38 | return nil, err 39 | } 40 | 41 | if freeze { 42 | v.Frozen = true 43 | } 44 | 45 | return v, nil 46 | } 47 | 48 | // SetValues sets multiple variable values. It uses the same freeze logic as SetValue. 49 | func (vars Variables) SetValues(values map[string]string, freeze bool) error { 50 | for name, value := range values { 51 | if _, err := vars.SetValue(name, value, freeze); err != nil { 52 | return err 53 | } 54 | } 55 | return nil 56 | } 57 | 58 | // Load returns variables from CLI arguments, environment variables, 59 | // the Terraform configuration, and tfvars files. 60 | // 61 | // Note about value types, which LTF adheres to: 62 | // https://www.terraform.io/language/values/variables#complex-typed-values 63 | // For convenience, Terraform defaults to interpreting -var and environment 64 | // variable values as literal strings... However, if a root module variable 65 | // uses a type constraint to require a complex value (list, set, map, object, 66 | // or tuple), Terraform will instead attempt to parse its value using the same 67 | // syntax used within variable definitions files... 68 | func Load(args *arguments.Arguments, dirs []string, chdir string) (vars Variables, err error) { 69 | vars = Variables{} 70 | 71 | // Parse the Terraform config to get variable types and defaults. 72 | module, diags := tfconfig.LoadModule(chdir) 73 | if err := diags.Err(); err != nil { 74 | return nil, err 75 | } 76 | for _, v := range module.Variables { 77 | value := "" 78 | if v.Default != nil { 79 | value, err = marshalValue(v.Default) 80 | if err != nil { 81 | return nil, fmt.Errorf("loading %s default value: %w", v.Name, err) 82 | } 83 | } 84 | nv, err := New(v.Name, v.Type, value) 85 | if err != nil { 86 | return nil, fmt.Errorf("loading %s variable: %w", v.Name, err) 87 | } 88 | nv.Sensitive = v.Sensitive 89 | vars[v.Name] = nv 90 | } 91 | 92 | // Load variables that environment variables will not able to override 93 | // due to Terraform's variables precedence rules. 94 | // These will be considered "frozen" values. 95 | 96 | // Load tfvars from the configuration directory. 97 | // Terraform will use these values over TF_VAR_name so freeze them. 98 | if v, err := readVariablesDir(chdir); err != nil { 99 | return nil, err 100 | } else { 101 | if err := vars.SetValues(v, true); err != nil { 102 | return nil, err 103 | } 104 | } 105 | 106 | // Load variables from CLI arguments. 107 | // Terraform will prefer these values over TF_VAR_name so freeze them 108 | // so LTF can return an error if something tries to set a different 109 | // value using TF_VAR_name. 110 | if v, err := readVariablesArgs(args.Virtual); err != nil { 111 | return nil, err 112 | } else { 113 | for name, value := range v { 114 | if _, err := vars.SetValue(name, value, true); err != nil { 115 | return nil, err 116 | } 117 | } 118 | } 119 | 120 | // Load variables from *.tfvars and *.tfvars.json files. 121 | // Use directories in reverse order so variables in deeper directories 122 | // overwrite variables in parent directories. 123 | for i := len(dirs) - 1; i >= 0; i-- { 124 | dir := dirs[i] 125 | if dir == chdir { 126 | // Files in chdir were handled earlier. 127 | continue 128 | } 129 | if v, err := readVariablesDir(dir); err != nil { 130 | return nil, err 131 | } else { 132 | for name, value := range v { 133 | if _, err := vars.SetValue(name, value, false); err != nil { 134 | return nil, fmt.Errorf("loading from dir %s: %w", dir, err) 135 | } 136 | } 137 | } 138 | } 139 | 140 | return vars, nil 141 | } 142 | 143 | func filterVariableFiles(files []string) (matches []string) { 144 | // Returns variables files in the correct order of precedence. 145 | // https://www.terraform.io/language/values/variables#variable-definition-precedence 146 | 147 | sort.Strings(files) 148 | 149 | // 1. The terraform.tfvars file, if present. 150 | // 2. The terraform.tfvars.json file, if present. 151 | autoFiles := []string{} 152 | for _, name := range files { 153 | if name == "terraform.tfvars" || name == "terraform.tfvars.json" { 154 | matches = append(matches, name) 155 | } else if matched, _ := path.Match("*.auto.tfvars", name); matched { 156 | autoFiles = append(autoFiles, name) 157 | } else if matched, _ := path.Match("*.auto.tfvars.json", name); matched { 158 | autoFiles = append(autoFiles, name) 159 | } 160 | } 161 | 162 | // 3. Any *.auto.tfvars or *.auto.tfvars.json files, 163 | // processed in lexical order of their filenames. 164 | matches = append(matches, autoFiles...) 165 | 166 | return matches 167 | } 168 | 169 | // marshalValue returns the JSON encoding of v, 170 | // unless it is a string in which case it returns it as-is. 171 | // The result is suitable for use as a TF_VAR_name environment variable. 172 | func marshalValue(v interface{}) (string, error) { 173 | if str, ok := v.(string); ok { 174 | return str, nil 175 | } else { 176 | jsonBytes, err := json.Marshal(v) 177 | if err != nil { 178 | return "", fmt.Errorf("marshal to environment variable: %w", err) 179 | } 180 | return string(jsonBytes), nil 181 | } 182 | } 183 | 184 | func readVariablesArgs(args []string) (map[string]string, error) { 185 | result := map[string]string{} 186 | for _, arg := range args { 187 | if strings.HasPrefix(arg, "-var=") { 188 | s := strings.SplitN(arg, "=", 3) 189 | if len(s) != 3 { 190 | return nil, fmt.Errorf("invalid argument: %s", arg) 191 | } 192 | name := s[1] 193 | value := s[2] 194 | result[name] = value 195 | } else if strings.HasPrefix(arg, "-var-file=") { 196 | s := strings.SplitN(arg, "=", 2) 197 | if len(s) != 2 { 198 | return nil, fmt.Errorf("invalid argument: %s", arg) 199 | } 200 | file := s[1] 201 | v, err := readVariablesFile(file) 202 | if err != nil { 203 | return nil, err 204 | } 205 | for name, value := range v { 206 | result[name] = value 207 | } 208 | } 209 | } 210 | return result, nil 211 | } 212 | 213 | func readVariablesDir(dir string) (map[string]string, error) { 214 | result := map[string]string{} 215 | 216 | files, err := filesystem.ReadNames(dir) 217 | if err != nil { 218 | return nil, err 219 | } 220 | 221 | for _, filename := range filterVariableFiles(files) { 222 | vars, err := readVariablesFile(path.Join(dir, filename)) 223 | if err != nil { 224 | return nil, err 225 | } 226 | for name, value := range vars { 227 | result[name] = value 228 | } 229 | } 230 | 231 | return result, nil 232 | } 233 | 234 | func readVariablesFile(filename string) (map[string]string, error) { 235 | result := map[string]string{} 236 | 237 | bytes, err := ioutil.ReadFile(filename) 238 | if err != nil { 239 | return nil, err 240 | } 241 | 242 | var jsonBytes []byte 243 | 244 | if strings.HasSuffix(filename, ".json") { 245 | jsonBytes = bytes 246 | } else { 247 | jsonBytes, err = convert.Bytes(bytes, filename, convert.Options{}) 248 | if err != nil { 249 | return nil, fmt.Errorf("readVariablesFile converting hcl to json: %w", err) 250 | } 251 | } 252 | 253 | vars := map[string]interface{}{} 254 | if err := json.Unmarshal(jsonBytes, &vars); err != nil { 255 | return nil, fmt.Errorf("readVariablesFile writing json: %w", err) 256 | } 257 | 258 | for name, val := range vars { 259 | env, err := marshalValue(val) 260 | if err != nil { 261 | return nil, fmt.Errorf("readVariablesFile reading json: %w", err) 262 | } 263 | result[name] = env 264 | } 265 | 266 | return result, nil 267 | } 268 | -------------------------------------------------------------------------------- /internal/variable/variables_test.go: -------------------------------------------------------------------------------- 1 | package variable 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path" 7 | "testing" 8 | 9 | "github.com/matryer/is" 10 | "github.com/raymondbutcher/ltf" 11 | "github.com/raymondbutcher/ltf/internal/arguments" 12 | "github.com/zclconf/go-cty/cty" 13 | ) 14 | 15 | func TestLoad(t *testing.T) { 16 | is := is.New(t) 17 | 18 | // Arrange 19 | 20 | tempDir, err := os.MkdirTemp("", "ltf-test-") 21 | is.NoErr(err) // error creating temporary directory 22 | defer os.RemoveAll(tempDir) 23 | 24 | contents, err := ioutil.ReadFile("variables_test.tf") 25 | is.NoErr(err) // error reading file 26 | err = ioutil.WriteFile(path.Join(tempDir, "main.tf"), contents, 06666) 27 | is.NoErr(err) // error creating file 28 | 29 | contents, err = ioutil.ReadFile("variables_test.tfvars") 30 | is.NoErr(err) // error reading file 31 | err = ioutil.WriteFile(path.Join(tempDir, "terraform.tfvars"), contents, 06666) 32 | is.NoErr(err) // error creating file 33 | 34 | args, err := arguments.New([]string{"ltf"}, ltf.NewEnviron()) 35 | is.NoErr(err) // error creating arguments 36 | 37 | // Act 38 | 39 | vars, err := Load(args, []string{tempDir}, tempDir) 40 | is.NoErr(err) // error loading variables 41 | 42 | // Assert 43 | 44 | is.Equal(vars["bool_default_value"].StringValue, "true") 45 | is.Equal(vars["bool_default_value"].AnyValue, cty.BoolVal(true)) 46 | 47 | is.Equal(vars["bool_no_value"].StringValue, "") 48 | is.Equal(vars["bool_no_value"].AnyValue, cty.NilVal) 49 | 50 | is.Equal(vars["bool_value"].StringValue, "true") 51 | is.Equal(vars["bool_value"].AnyValue, cty.BoolVal(true)) 52 | 53 | is.Equal(vars["list_default_value"].StringValue, "[true]") 54 | is.Equal(vars["list_default_value"].AnyValue, cty.TupleVal([]cty.Value{cty.BoolVal(true)})) 55 | 56 | is.Equal(vars["list_no_value"].StringValue, "") 57 | is.Equal(vars["list_no_value"].AnyValue, cty.NilVal) 58 | 59 | is.Equal(vars["list_value"].StringValue, "[true,true]") 60 | is.Equal(vars["list_value"].AnyValue, cty.TupleVal([]cty.Value{cty.BoolVal(true), cty.BoolVal(true)})) 61 | 62 | is.Equal(vars["string_default_value"].StringValue, "string_default_value") 63 | is.Equal(vars["string_default_value"].AnyValue, cty.StringVal("string_default_value")) 64 | 65 | is.Equal(vars["string_no_value"].StringValue, "") 66 | is.Equal(vars["string_no_value"].AnyValue, cty.StringVal("")) 67 | 68 | is.Equal(vars["string_value"].StringValue, "string_value") 69 | is.Equal(vars["string_value"].AnyValue, cty.StringVal("string_value")) 70 | 71 | is.Equal(vars["untyped_no_value"].StringValue, "") 72 | is.Equal(vars["untyped_no_value"].AnyValue, cty.StringVal("")) 73 | 74 | is.Equal(vars["untyped_default_list_value"].StringValue, `["untyped_default_list_value"]`) 75 | is.Equal(vars["untyped_default_list_value"].AnyValue, cty.StringVal(`["untyped_default_list_value"]`)) 76 | 77 | is.Equal(vars["untyped_bool_value"].StringValue, "true") 78 | is.Equal(vars["untyped_bool_value"].AnyValue, cty.StringVal("true")) 79 | 80 | is.Equal(vars["untyped_string_value"].StringValue, "untyped_string_value") 81 | is.Equal(vars["untyped_string_value"].AnyValue, cty.StringVal("untyped_string_value")) 82 | } 83 | -------------------------------------------------------------------------------- /internal/variable/variables_test.tf: -------------------------------------------------------------------------------- 1 | variable "bool_default_value" { 2 | type = bool 3 | default = true 4 | } 5 | 6 | variable "bool_no_value" { type = bool } 7 | 8 | variable "bool_value" { type = bool } 9 | 10 | ### 11 | 12 | variable "list_default_value" { 13 | type = list(bool) 14 | default = [true] 15 | } 16 | 17 | variable "list_no_value" { type = list(bool) } 18 | 19 | variable "list_value" { type = list(bool) } 20 | 21 | ### 22 | 23 | variable "string_default_value" { 24 | type = string 25 | default = "string_default_value" 26 | } 27 | 28 | variable "string_no_value" { type = string } 29 | 30 | variable "string_value" { type = string } 31 | 32 | ### 33 | 34 | variable "untyped_no_value" {} 35 | 36 | variable "untyped_default_list_value" { 37 | default = ["untyped_default_list_value"] 38 | } 39 | 40 | variable "untyped_bool_value" {} 41 | 42 | variable "untyped_string_value" {} 43 | -------------------------------------------------------------------------------- /internal/variable/variables_test.tfvars: -------------------------------------------------------------------------------- 1 | bool_value = true 2 | 3 | list_value = [ 4 | true, 5 | true, 6 | ] 7 | 8 | string_value = "string_value" 9 | 10 | untyped_bool_value = true 11 | 12 | untyped_string_value = "untyped_string_value" 13 | --------------------------------------------------------------------------------