├── .circleci └── config.yml ├── .github ├── CODEOWNERS └── CONTRIBUTING.md ├── .gitignore ├── .rubocop.yml ├── CHANGELOG.md ├── Dockerfile ├── Gemfile ├── Guardfile ├── LICENSE ├── README.md ├── bin └── landscape ├── doc ├── after.png └── before.png ├── grammar └── terraform_plan.treetop ├── lib ├── terraform_landscape.rb └── terraform_landscape │ ├── arguments_parser.rb │ ├── cli.rb │ ├── constants.rb │ ├── errors.rb │ ├── output.rb │ ├── printer.rb │ ├── terraform_plan.rb │ └── version.rb ├── spec ├── printer_spec.rb ├── spec_helper.rb ├── support │ └── normalize_indent.rb └── terraform_plan_spec.rb └── terraform_landscape.gemspec /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | build: 5 | docker: 6 | - image: circleci/ruby:2.5 7 | 8 | working_directory: ~/repo 9 | 10 | steps: 11 | - checkout 12 | 13 | # Download and cache dependencies 14 | - restore_cache: 15 | keys: 16 | - v1-dependencies-{{ checksum "Gemfile" }} 17 | # fallback to using the latest cache if no exact match is found 18 | - v1-dependencies- 19 | 20 | - run: 21 | name: install dependencies 22 | command: | 23 | bundle install --jobs=4 --retry=3 --path vendor/bundle 24 | 25 | - save_cache: 26 | paths: 27 | - ./vendor/bundle 28 | key: v1-dependencies-{{ checksum "Gemfile" }} 29 | 30 | - run: 31 | name: run tests 32 | command: | 33 | bundle exec rspec --format progress \ 34 | --format RspecJunitFormatter \ 35 | --out /tmp/test-results/rspec.xml \ 36 | 37 | - run: 38 | name: rubocop 39 | command: bundle exec rubocop -D 40 | 41 | - store_test_results: 42 | path: /tmp/test-results 43 | - store_artifacts: 44 | path: /tmp/test-results 45 | destination: test-results 46 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Defines the owners of various files in this project. 2 | # Each line is a file pattern followed by one or more owners. 3 | 4 | * @grahamjenson @krobertson @sds 5 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Terraform Landscape 2 | 3 | ## Code of Conduct 4 | 5 | All interactions with this project follow our [Code of Conduct][code-of-conduct]. 6 | By participating, you are expected to honor this code. Violators can be banned 7 | from further participation in this project, or potentially all Coinbase projects. 8 | 9 | [code-of-conduct]: https://github.com/coinbase/code-of-conduct 10 | 11 | ## Bug Reports 12 | 13 | * Ensure your issue [has not already been reported][1]. It may already be fixed! 14 | * Include the steps you carried out to produce the problem. 15 | * Include the behavior you observed along with the behavior you expected, and 16 | why you expected it. 17 | * Include any relevant stack traces or debugging output. 18 | 19 | ## Feature Requests 20 | 21 | We welcome feedback with or without pull requests. If you have an idea for how 22 | to improve the project, great! All we ask is that you take the time to write a 23 | clear and concise explanation of what need you are trying to solve. If you have 24 | thoughts on _how_ it can be solved, include those too! 25 | 26 | The best way to see a feature added, however, is to submit a pull request. 27 | 28 | ## Pull Requests 29 | 30 | * Before creating your pull request, it's usually worth asking if the code 31 | you're planning on writing will actually be considered for merging. You can 32 | do this by [opening an issue][1] and asking. It may also help give the 33 | maintainers context for when the time comes to review your code. 34 | 35 | * Ensure your [commit messages are well-written][2]. This can double as your 36 | pull request message, so it pays to take the time to write a clear message. 37 | 38 | * Add tests for your feature. You should be able to look at other tests for 39 | examples. If you're unsure, don't hesitate to [open an issue][1] and ask! 40 | 41 | * Submit your pull request! 42 | 43 | ### Development Setup 44 | 45 | Install dependencies 46 | 47 | ```bash 48 | bundle install 49 | ``` 50 | 51 | Run tests 52 | ```bash 53 | bundle exec rspec 54 | ``` 55 | 56 | Run tests in watch mode 57 | ```bash 58 | bundle exec guard 59 | ``` 60 | 61 | 62 | ## Support Requests 63 | 64 | For security reasons, any communication referencing support tickets for Coinbase 65 | products will be ignored. The request will have its content redacted and will 66 | be locked to prevent further discussion. 67 | 68 | All support requests must be made via [our support team][3]. 69 | 70 | [1]: https://github.com/coinbase/terraform-landscape/issues 71 | [2]: https://medium.com/brigade-engineering/the-secrets-to-great-commit-messages-106fc0a92a25 72 | [3]: https://support.coinbase.com/customer/en/portal/articles/2288496-how-can-i-contact-coinbase-support- 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Gemfile.lock 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | Metrics/AbcSize: 2 | Enabled: false 3 | 4 | Metrics/CyclomaticComplexity: 5 | Enabled: false 6 | 7 | Metrics/BlockLength: 8 | Exclude: 9 | - 'spec/**/*_spec.rb' 10 | 11 | Metrics/LineLength: 12 | Max: 90 13 | 14 | Metrics/MethodLength: 15 | Max: 20 16 | 17 | Metrics/PerceivedComplexity: 18 | Enabled: false 19 | 20 | Style/BracesAroundHashParameters: 21 | Enabled: false 22 | 23 | Style/ClassAndModuleChildren: 24 | Enabled: false 25 | 26 | Style/PercentLiteralDelimiters: 27 | PreferredDelimiters: 28 | '%w': '[]' 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Terraform Landscape Change Log 2 | 3 | ## 0.3.4 4 | 5 | * Fix syntax errors when running on Ruby 3 6 | 7 | ## 0.3.3 8 | 9 | * Fix handling of Windows newlines in preprocessing step 10 | 11 | ## 0.3.2 12 | 13 | * Fix handling of UTF-8 strings in Terraform plans 14 | 15 | ## 0.3.1 16 | 17 | * Fix handling of initialization messages for included modules 18 | 19 | ## 0.3.0 20 | 21 | * Display original Terraform output when Landscape encounters an unhandled exception 22 | * Drop dependency on `string_undump` gem in favor of built in `String#undump` method 23 | introduced in Ruby 2.5 24 | * Require Ruby 2.5 or newer 25 | 26 | ## 0.2.2 27 | 28 | * Fix output parser to show changed sensitive values 29 | * Fix plan parser to not extract attributes using `eval` 30 | * Include warning messages in output 31 | 32 | ## 0.2.1 33 | 34 | * Include period after `No changes` to maximize output compatibility 35 | * Fix output parser to work with Terraform workspaces 36 | * Fix output parser to work around multi-byte UTF-8 characters in certain scenarios 37 | 38 | ## 0.2.0 39 | 40 | * Sort JSON by keys before generating diff 41 | 42 | ## 0.1.18 43 | 44 | * Allow confirming `terraform apply` prompt 45 | 46 | ## 0.1.17 47 | 48 | * Fix handling of dashed line separators after state refresh output 49 | 50 | ## 0.1.16 51 | 52 | * Fix handling of initialization messages output by `terraform init` 53 | 54 | ## 0.1.15 55 | 56 | * Update the support for unquoted bracketed output to work with `` fields 57 | 58 | ## 0.1.14 59 | 60 | * Fix handling of `This plan does nothing` output 61 | 62 | ## 0.1.13 63 | 64 | * Fix processing of resource changes with `(new resource required)` explanation 65 | 66 | ## 0.1.12 67 | 68 | * Fix processing attribute names that include colons 69 | 70 | ## 0.1.11 71 | 72 | * Fix handling of `` attribute values with Terraform 0.10.4+ 73 | 74 | ## 0.1.10 75 | 76 | * Fix handling of attribute names with spaces 77 | 78 | ## 0.1.9 79 | 80 | * Fix handling of additional indentation in Terraform 0.10.0 output 81 | 82 | ## 0.1.8 83 | 84 | * Fix handling of Terraform plan outputs when `-out` flag not specified 85 | 86 | ## 0.1.7 87 | 88 | * Gracefully handle case where Terraform output does not contain postface 89 | 90 | ## 0.1.6 91 | 92 | * Fix handling of read action resources (`<=`) 93 | 94 | ## 0.1.5 95 | 96 | * Fix handling of Windows line endings 97 | 98 | ## 0.1.4 99 | 100 | * Fix handling of repeated resources with index numbers 101 | * Fix changing resource attributes from empty string to JSON 102 | * Fix handling of consecutive resources with no attributes 103 | 104 | ## 0.1.3 105 | 106 | * Fix handling of resources rebuilt due to attribute changes with 107 | `(forces new resource)` in output 108 | 109 | ## 0.1.2 110 | 111 | * Fix handling of rebuilt/tainted resources 112 | 113 | ## 0.1.1 114 | 115 | * Fix handling of resources with no attributes 116 | 117 | ## 0.1.0 118 | 119 | * Don't require `-out` flag on Terraform command 120 | * Fix handling of Terraform output with no changes 121 | 122 | ## 0.0.1 123 | 124 | * Initial release 125 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.8 2 | 3 | RUN apk --no-cache add \ 4 | ruby-bundler=1.16.2-r1 \ 5 | ruby-json=2.5.8-r0 \ 6 | diffutils=3.6-r1 # this is required for diffy to work on alpine 7 | 8 | RUN gem install --no-document --no-ri terraform_landscape 9 | ENTRYPOINT ["landscape"] 10 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gemspec 4 | 5 | # Development dependencies are listed below 6 | 7 | gem 'rspec', '~> 3.0' 8 | gem 'rspec_junit_formatter', '~> 0.4' 9 | gem 'rubocop', '0.51.0' 10 | 11 | group 'autotest' do 12 | gem 'guard-rspec' 13 | gem 'ruby_gntp' 14 | end 15 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | rspec_options = { 2 | cmd: 'bundle exec rspec', 3 | all_on_start: true 4 | } 5 | 6 | guard :rspec, **rspec_options do 7 | require 'guard/rspec/dsl' 8 | dsl = Guard::RSpec::Dsl.new(self) 9 | 10 | # RSpec files 11 | rspec = dsl.rspec 12 | watch(rspec.spec_helper) { rspec.spec_dir } 13 | watch(rspec.spec_support) { rspec.spec_dir } 14 | watch(rspec.spec_files) { rspec.spec_dir } 15 | 16 | # Ruby files 17 | ruby = dsl.ruby 18 | watch(ruby.lib_files) { rspec.spec_dir } 19 | 20 | notification :gntp 21 | end 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Coinbase, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Terraform Landscape 2 | 3 | [![Gem Version](https://badge.fury.io/rb/terraform_landscape.svg)](http://badge.fury.io/rb/terraform_landscape) 4 | [![CircleCI](https://circleci.com/gh/coinbase/terraform-landscape.svg?style=svg)](https://circleci.com/gh/coinbase/terraform-landscape) 5 | 6 | Terraform Landscape is a tool for reformatting the output of `terraform plan` 7 | to be easier to read and understand. 8 | 9 | #### Before 10 | Original Terraform plan output 11 | 12 | ### After 13 | Improved Terraform plan output 14 | 15 | * [Requirements](#requirements) 16 | * [Installation](#installation) 17 | * [Usage](#usage) 18 | 19 | ## Requirements 20 | 21 | * Ruby 2.5+ 22 | * Terraform 0.11.x (see [#101](https://github.com/coinbase/terraform-landscape/issues/101) for details) 23 | 24 | ## Installation 25 | 26 | The `landscape` executable is installed via [RubyGems](https://rubygems.org/). 27 | 28 | ```bash 29 | gem install terraform_landscape 30 | ``` 31 | 32 | ### macOS 33 | 34 | Terraform Landscape is also available via [Homebrew](https://brew.sh/). 35 | 36 | ```bash 37 | brew install terraform_landscape 38 | ``` 39 | 40 | ## Usage 41 | 42 | Pipe the output of `terraform plan` into `landscape` to reformat the output. 43 | 44 | ```bash 45 | terraform plan ... | landscape 46 | ``` 47 | 48 | ## Docker 49 | 50 | Build the docker image using provided Dockerfile and use it directly: 51 | 52 | ```bash 53 | docker build . -t landscape 54 | terraform plan ... | docker run -i --rm landscape 55 | ``` 56 | 57 | ## License 58 | 59 | This project is released under the [Apache 2.0 license](LICENSE). 60 | -------------------------------------------------------------------------------- /bin/landscape: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'terraform_landscape' 4 | 5 | output = TerraformLandscape::Output.new(STDOUT) 6 | cli = TerraformLandscape::CLI.new(output) 7 | exit cli.run(ARGV) 8 | -------------------------------------------------------------------------------- /doc/after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coinbase/terraform-landscape/1558b8fa7fb46b03dffcf16f47adcd85d538b804/doc/after.png -------------------------------------------------------------------------------- /doc/before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coinbase/terraform-landscape/1558b8fa7fb46b03dffcf16f47adcd85d538b804/doc/before.png -------------------------------------------------------------------------------- /grammar/terraform_plan.treetop: -------------------------------------------------------------------------------- 1 | # Defines grammar for parsing `terraform plan` output. 2 | 3 | grammar TerraformPlan 4 | rule plan 5 | [\s]* list:resource_list "\n"* { 6 | def to_ast 7 | list.to_ast 8 | end 9 | } 10 | end 11 | 12 | rule resource_list 13 | item:resource "\n\n" list:resource_list { 14 | def to_ast 15 | [item.to_ast] + list.to_ast 16 | end 17 | } 18 | / 19 | item:resource "\n" { 20 | def to_ast 21 | [item.to_ast] 22 | end 23 | } 24 | end 25 | 26 | rule resource 27 | header:resource_header "\n" attrs:attribute_list { 28 | def to_ast 29 | header.to_ast.merge(attributes: attrs.to_ast) 30 | end 31 | } 32 | / 33 | header:resource_header { 34 | def to_ast 35 | header.to_ast.merge(attributes: {}) 36 | end 37 | } 38 | end 39 | 40 | rule resource_header 41 | ws? change:('~' / '-/+' / '-' / '+' / '<=') ws type:[a-zA-Z0-9_-]+ '.' name:[\S]+ ws '(' reason1:[^)]+ ')' ws '(' reason2:[^)]+ ')' { 42 | def to_ast 43 | { 44 | change: change.text_value.to_sym, 45 | resource_type: type.text_value, 46 | resource_name: name.text_value, 47 | reason: reason1.text_value, 48 | additional_reason: reason2.text_value, 49 | } 50 | end 51 | } 52 | / 53 | ws? change:('~' / '-/+' / '-' / '+' / '<=') ws type:[a-zA-Z0-9_-]+ '.' name:[\S]+ ws '(' reason:[^)]+ ')' { 54 | def to_ast 55 | { 56 | change: change.text_value.to_sym, 57 | resource_type: type.text_value, 58 | resource_name: name.text_value, 59 | reason: reason.text_value, 60 | } 61 | end 62 | } 63 | / 64 | ws? change:('~' / '-/+' / '-' / '+' / '<=') ws type:[a-zA-Z0-9_-]+ '.' name:[\S]+ { 65 | def to_ast 66 | { 67 | change: change.text_value.to_sym, 68 | resource_type: type.text_value, 69 | resource_name: name.text_value, 70 | } 71 | end 72 | } 73 | end 74 | 75 | rule attribute_list 76 | ws item:attribute "\n" attrs:attribute_list { 77 | def to_ast 78 | item.to_ast.merge(attrs.to_ast) 79 | end 80 | } 81 | / 82 | ws item:attribute { 83 | def to_ast 84 | item.to_ast 85 | end 86 | } 87 | end 88 | 89 | rule attribute 90 | attribute_name:(!': ' .)* ':' ws? attribute_value:[^\n]+ { 91 | def to_ast 92 | { attribute_name.text_value => sanitize_value_and_reason } 93 | end 94 | 95 | def sanitize_value_and_reason 96 | val = attribute_value.text_value 97 | 98 | # We'll perform some sanitization of the values within the parser. 99 | 100 | # Handle case where attribute has an annotation (e.g. "forces new resource") 101 | if (match = val.match(/\s+\((?[^)]+)\)$/)) 102 | reason = match['reason'] 103 | val = val[0...match.begin(0)] 104 | end 105 | 106 | # With Terraform >= 0.10.4, the and fields are 107 | # now without quotes, which will cause problem with how downstream we 108 | # process the output. Convert it to have quotes and handle < 0.10.4 as 109 | # well. 110 | val = val.gsub(%r{=> <(\w+)>$}, '=> "<\1>"') 111 | .gsub(%r{^<(\w+)>}, '"<\1>"') 112 | 113 | { value: val, reason: reason } 114 | end 115 | } 116 | end 117 | 118 | rule ws 119 | [ ]+ 120 | end 121 | end 122 | -------------------------------------------------------------------------------- /lib/terraform_landscape.rb: -------------------------------------------------------------------------------- 1 | require 'terraform_landscape/constants' 2 | require 'terraform_landscape/version' 3 | require 'terraform_landscape/output' 4 | require 'terraform_landscape/errors' 5 | require 'terraform_landscape/printer' 6 | require 'terraform_landscape/terraform_plan' 7 | require 'terraform_landscape/cli' 8 | -------------------------------------------------------------------------------- /lib/terraform_landscape/arguments_parser.rb: -------------------------------------------------------------------------------- 1 | require 'optparse' 2 | 3 | module TerraformLandscape 4 | # Handles option parsing for the command line application. 5 | class ArgumentsParser 6 | # Parses command line options into an options hash. 7 | # 8 | # @param args [Array] arguments passed via the command line 9 | # 10 | # @return [Hash] parsed options 11 | def parse(args) 12 | @options = {} 13 | @options[:command] = :pretty_print # Default command 14 | 15 | OptionParser.new do |parser| 16 | parser.banner = 'Usage: landscape [options] [plan-output-file]' 17 | 18 | add_info_options parser 19 | end.parse!(args) 20 | 21 | # Any remaining arguments are assumed to be the output file 22 | @options[:plan_output_file] = args.first 23 | 24 | @options 25 | rescue OptionParser::InvalidOption => ex 26 | raise InvalidCliOptionError, 27 | "#{ex.message}\nRun `landscape --help` to " \ 28 | 'see a list of available options.' 29 | end 30 | 31 | private 32 | 33 | # Register informational flags. 34 | def add_info_options(parser) 35 | parser.on('--[no-]color', 'Force output to be colorized') do |color| 36 | @options[:color] = color 37 | end 38 | 39 | parser.on('-d', '--debug', 'Enable debug mode for more verbose output') do 40 | @options[:debug] = true 41 | end 42 | 43 | parser.on_tail('-h', '--help', 'Display help documentation') do 44 | @options[:command] = :display_help 45 | @options[:help_message] = parser.help 46 | end 47 | 48 | parser.on_tail('-v', '--version', 'Display version') do 49 | @options[:command] = :display_version 50 | end 51 | 52 | parser.on_tail('-V', '--verbose-version', 'Display verbose version information') do 53 | @options[:command] = :display_version 54 | @options[:verbose_version] = true 55 | end 56 | end 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /lib/terraform_landscape/cli.rb: -------------------------------------------------------------------------------- 1 | require 'commander' 2 | 3 | module TerraformLandscape 4 | # Command line application interface. 5 | class CLI 6 | include Commander::Methods 7 | 8 | def initialize(output) 9 | @output = output 10 | end 11 | 12 | # Parses the given command line arguments and executes appropriate logic 13 | # based on those arguments. 14 | # 15 | # @param args [Array] command line arguments 16 | # 17 | # @return [Integer] exit status code 18 | def run(_args) 19 | program :name, 'Terraform Landscape' 20 | program :version, VERSION 21 | program :description, 'Pretty-print your Terraform plan output' 22 | 23 | define_commands 24 | 25 | run! 26 | 0 # OK 27 | end 28 | 29 | private 30 | 31 | def define_commands 32 | command :print do |c| 33 | c.action do |_args, options| 34 | print(options.__hash__) 35 | end 36 | c.description = <<-TXT 37 | Pretty-prints your Terraform plan output. 38 | 39 | If an error occurs while parsing the Terraform output, print will automatically fall back on the original Terraform output. To view the stack trace instead, provide the global --trace option. 40 | TXT 41 | end 42 | 43 | global_option '--no-color', 'Do not output any color' do 44 | String.disable_colorization = true 45 | @output.color_enabled = false 46 | end 47 | 48 | default_command :print 49 | end 50 | 51 | def print(options) 52 | printer = Printer.new(@output) 53 | printer.process_stream(ARGF, options) 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /lib/terraform_landscape/constants.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Global application constants. 4 | module TerraformLandscape 5 | HOME = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')).freeze 6 | 7 | REPO_URL = 'https://github.com/coinbase/terraform_landscape'.freeze 8 | BUG_REPORT_URL = "#{REPO_URL}/issues".freeze 9 | 10 | FALLBACK_MESSAGE = 'Terraform Landscape: a parsing error occured.' \ 11 | ' Falling back to original Terraform output...'.freeze 12 | end 13 | -------------------------------------------------------------------------------- /lib/terraform_landscape/errors.rb: -------------------------------------------------------------------------------- 1 | # Collection of errors that can be raised by the framework. 2 | module TerraformLandscape 3 | # Abstract error. Separates LintTrappings errors from other kinds of 4 | # errors in the exception hierarchy. 5 | # 6 | # @abstract 7 | class Error < StandardError 8 | # Returns the status code that should be output if this error goes 9 | # unhandled. 10 | # 11 | # Ideally these should resemble exit codes from the sysexits documentation 12 | # where it makes sense. 13 | def self.exit_status(*args) 14 | if args.any? 15 | @exit_status = args.first 16 | elsif @exit_status 17 | @exit_status 18 | else 19 | ancestors.each do |ancestor| 20 | return 70 if ancestor == TerraformLandscape::Error # No exit status defined 21 | return ancestor.exit_status if ancestor.exit_status 22 | end 23 | end 24 | end 25 | 26 | def exit_status 27 | self.class.exit_status 28 | end 29 | end 30 | 31 | # Raised when there was a problem parsing a document. 32 | class ParseError < Error; end 33 | end 34 | -------------------------------------------------------------------------------- /lib/terraform_landscape/output.rb: -------------------------------------------------------------------------------- 1 | module TerraformLandscape 2 | # Encapsulates all communication to an output source. 3 | class Output 4 | # Whether colored output via ANSI escape sequences is enabled. 5 | # @return [true,false] 6 | attr_accessor :color_enabled 7 | 8 | # Creates a logger which outputs nothing. 9 | # @return [TerraformLandscape::Output] 10 | def self.silent 11 | new(File.open(File::NULL, 'w')) 12 | end 13 | 14 | # Creates a new {SlimLint::Logger} instance. 15 | # 16 | # @param out [IO] the output destination. 17 | def initialize(out) 18 | @out = out 19 | @color_enabled = tty? 20 | end 21 | 22 | # Print the specified output. 23 | # 24 | # @param output [String] the output to send 25 | # @param newline [true,false] whether to append a newline 26 | def puts(output, newline = true) 27 | @out.print(output) 28 | @out.print("\n") if newline 29 | end 30 | 31 | # Print the specified output without a newline. 32 | # 33 | # @param output [String] the output to send 34 | def print(output) 35 | puts(output, false) 36 | end 37 | 38 | # Print the specified output in bold face. 39 | # If output destination is not a TTY, behaves the same as {#log}. 40 | # 41 | # @param args [Array] 42 | def bold(*args) 43 | color('1', *args) 44 | end 45 | 46 | # Print the specified output in a color indicative of error. 47 | # If output destination is not a TTY, behaves the same as {#log}. 48 | # 49 | # @param args [Array] 50 | def error(*args) 51 | color(31, *args) 52 | end 53 | 54 | # Print the specified output in a bold face and color indicative of error. 55 | # If output destination is not a TTY, behaves the same as {#log}. 56 | # 57 | # @param args [Array] 58 | def bold_error(*args) 59 | color('1;31', *args) 60 | end 61 | 62 | # Print the specified output in a color indicative of success. 63 | # If output destination is not a TTY, behaves the same as {#log}. 64 | # 65 | # @param args [Array] 66 | def success(*args) 67 | color(32, *args) 68 | end 69 | 70 | # Print the specified output in a color indicative of a warning. 71 | # If output destination is not a TTY, behaves the same as {#log}. 72 | # 73 | # @param args [Array] 74 | def warning(*args) 75 | color(33, *args) 76 | end 77 | 78 | # Print the specified output in a color indicating something worthy of 79 | # notice. 80 | # If output destination is not a TTY, behaves the same as {#log}. 81 | # 82 | # @param args [Array] 83 | def notice(*args) 84 | color(35, *args) 85 | end 86 | 87 | # Print the specified output in a color indicating information. 88 | # If output destination is not a TTY, behaves the same as {#log}. 89 | # 90 | # @param args [Array] 91 | def info(*args) 92 | color(36, *args) 93 | end 94 | 95 | # Print a blank line. 96 | def newline 97 | puts('') 98 | end 99 | 100 | # Whether this logger is outputting to a TTY. 101 | # 102 | # @return [true,false] 103 | def tty? 104 | @out.respond_to?(:tty?) && @out.tty? 105 | end 106 | 107 | # Connect directly to a readable stream 108 | def write_from(other_io) 109 | while (line = other_io.gets) 110 | print line 111 | end 112 | end 113 | 114 | private 115 | 116 | # Print output in the specified color. 117 | # 118 | # @param code [Integer,String] ANSI color code 119 | # @param output [String] output to print 120 | # @param newline [Boolean] whether to append a newline 121 | def color(code, output, newline = true) 122 | puts(color_enabled ? "\033[#{code}m#{output}\033[0m" : output, newline) 123 | end 124 | end 125 | end 126 | -------------------------------------------------------------------------------- /lib/terraform_landscape/printer.rb: -------------------------------------------------------------------------------- 1 | require 'stringio' 2 | 3 | module TerraformLandscape 4 | # Takes output from Terraform executable and outputs it in a prettified 5 | # format. 6 | class Printer 7 | def initialize(output) 8 | @output = output 9 | end 10 | 11 | def process_stream(io, options = {}) # rubocop:disable Metrics/MethodLength 12 | apply = nil 13 | buffer = StringIO.new 14 | original_tf_output = StringIO.new 15 | begin 16 | block_size = 1024 17 | 18 | done = false 19 | until done 20 | readable_fds, = IO.select([io]) 21 | next unless readable_fds 22 | 23 | readable_fds.each do |f| 24 | begin 25 | new_output = f.read_nonblock(block_size) 26 | original_tf_output << new_output 27 | buffer << strip_ansi(new_output) 28 | rescue IO::WaitReadable # rubocop:disable Lint/HandleExceptions 29 | # Ignore; we'll call IO.select again 30 | rescue EOFError 31 | done = true 32 | end 33 | end 34 | 35 | apply = apply_prompt(buffer.string.encode('UTF-8', 36 | invalid: :replace, 37 | replace: '')) 38 | done = true if apply 39 | end 40 | 41 | begin 42 | process_string(buffer.string) 43 | @output.print apply if apply 44 | rescue ParseError, TerraformPlan::ParseError => e 45 | raise e if options[:trace] 46 | 47 | @output.warning FALLBACK_MESSAGE 48 | @output.print original_tf_output.string 49 | end 50 | 51 | @output.write_from(io) 52 | ensure 53 | io.close 54 | end 55 | end 56 | 57 | def process_string(plan_output) # rubocop:disable Metrics/MethodLength 58 | scrubbed_output = strip_ansi(plan_output) 59 | 60 | # Our grammar assumes output with Unix line endings 61 | scrubbed_output.gsub!("\r\n", "\n") 62 | 63 | # Remove initialization messages like 64 | # "- Downloading plugin for provider "aws" (1.1.0)..." 65 | # "- module.base_network" 66 | # as these break the parser which thinks "-" is a resource deletion 67 | scrubbed_output.gsub!(/^- .*\.\.\.$/, '') 68 | scrubbed_output.gsub!(/^- module\..*$/, '') 69 | 70 | # Remove separation lines that appear after refreshing state 71 | scrubbed_output.gsub!(/^-+$/, '') 72 | 73 | if (matches = scrubbed_output.scan(/^Warning:.*$/)) 74 | matches.each do |warning| 75 | @output.puts warning.colorize(:yellow) 76 | end 77 | end 78 | 79 | # Remove preface 80 | if (match = scrubbed_output.match(/^Path:[^\n]+/)) 81 | scrubbed_output = scrubbed_output[match.end(0)..-1] 82 | elsif (match = scrubbed_output.match(/^Terraform.+following\sactions:/)) 83 | scrubbed_output = scrubbed_output[match.end(0)..-1] 84 | elsif (match = scrubbed_output.match(/^\s*(~|\+|\-)/)) 85 | scrubbed_output = scrubbed_output[match.begin(0)..-1] 86 | elsif scrubbed_output =~ /^(No changes\.|This plan does nothing)/ 87 | @output.puts 'No changes.' 88 | return 89 | else 90 | raise ParseError, 'Output does not contain proper preface' 91 | end 92 | 93 | # Remove postface 94 | if (match = scrubbed_output.match(/^Plan:[^\n]+/)) 95 | plan_summary = scrubbed_output[match.begin(0)..match.end(0)] 96 | scrubbed_output = scrubbed_output[0...match.begin(0)] 97 | end 98 | 99 | plan = TerraformPlan.from_output(scrubbed_output) 100 | plan.display(@output) 101 | @output.puts plan_summary 102 | end 103 | 104 | private 105 | 106 | def strip_ansi(string) 107 | string.gsub(/\e\[\d+m/, '') 108 | end 109 | 110 | def apply_prompt(output) 111 | return unless output =~ /Enter a value:\s+$/ 112 | output[/Do you want to perform these actions.*$/m, 0] 113 | end 114 | end 115 | end 116 | -------------------------------------------------------------------------------- /lib/terraform_landscape/terraform_plan.rb: -------------------------------------------------------------------------------- 1 | require 'colorize' 2 | require 'diffy' 3 | require 'json' 4 | require 'treetop' 5 | 6 | ######################################################################## 7 | # Represents the parsed output of `terraform plan`. 8 | # 9 | # This allows us to easily inspect the plan and present a more readable 10 | # explanation of the plan to the user. 11 | ######################################################################## 12 | class TerraformLandscape::TerraformPlan # rubocop:disable Metrics/ClassLength 13 | GRAMMAR_FILE = File.expand_path(File.join(File.dirname(__FILE__), 14 | '..', '..', 'grammar', 15 | 'terraform_plan.treetop')) 16 | 17 | CHANGE_SYMBOL_TO_COLOR = { 18 | :~ => :yellow, 19 | :- => :red, 20 | :+ => :green, 21 | :'-/+' => :yellow, 22 | :'<=' => :cyan 23 | }.freeze 24 | 25 | DEFAULT_DIFF_CONTEXT_LINES = 5 26 | 27 | UNICODE_ESCAPER = proc { |s| 28 | format('\u%04X', s.codepoints[0]) 29 | } 30 | 31 | class ParseError < StandardError; end 32 | 33 | class << self 34 | def from_output(string) 35 | # Our grammar assumes output with Unix line endings 36 | string = string.gsub("\r\n", "\n") 37 | 38 | return new([]) if string.strip.empty? 39 | tree = parser.parse(string) 40 | raise ParseError, parser.failure_reason unless tree 41 | new(tree.to_ast) 42 | end 43 | 44 | private 45 | 46 | def parser 47 | @parser ||= 48 | begin 49 | Treetop.load(GRAMMAR_FILE) 50 | TerraformPlanParser.new 51 | end 52 | end 53 | end 54 | 55 | # Create a plan from an abstract syntax tree (AST). 56 | def initialize(plan_ast, options = {}) 57 | @ast = plan_ast 58 | @diff_context_lines = options.fetch(:diff_context_lines, DEFAULT_DIFF_CONTEXT_LINES) 59 | end 60 | 61 | def display(output) 62 | @out = output 63 | @ast.each do |resource| 64 | display_resource(resource) 65 | @out.newline 66 | end 67 | end 68 | 69 | private 70 | 71 | def display_resource(resource) # rubocop:disable Metrics/MethodLength 72 | change_color = CHANGE_SYMBOL_TO_COLOR[resource[:change]] 73 | 74 | resource_header = "#{resource[:change]} #{resource[:resource_type]}." \ 75 | "#{resource[:resource_name]}".colorize(change_color) 76 | 77 | if resource[:reason] 78 | resource_header += " (#{resource[:reason]})".colorize(:magenta) 79 | end 80 | 81 | if resource[:additional_reason] 82 | resource_header += " (#{resource[:additional_reason]})".colorize(:magenta) 83 | end 84 | 85 | @out.puts resource_header 86 | 87 | # Determine longest attribute name so we align all values at same indentation 88 | attribute_value_indent_amount = attribute_indent_amount_for_resource(resource) 89 | 90 | resource[:attributes].each do |attribute_name, attribute_value_and_reason| 91 | attribute_value = attribute_value_and_reason[:value] 92 | attribute_change_reason = attribute_value_and_reason[:reason] 93 | display_attribute(resource, 94 | change_color, 95 | attribute_name, 96 | attribute_value, 97 | attribute_change_reason, 98 | attribute_value_indent_amount) 99 | end 100 | end 101 | 102 | def attribute_indent_amount_for_resource(resource) 103 | longest_name_length = resource[:attributes].keys.reduce(0) do |longest, name| 104 | name.length > longest ? name.length : longest 105 | end 106 | longest_name_length + 8 107 | end 108 | 109 | def undump(value) 110 | value.encode('ASCII', fallback: UNICODE_ESCAPER).undump 111 | end 112 | 113 | def json?(value) 114 | ['{', '['].include?(value.to_s[0]) && 115 | (JSON.parse(value) rescue nil) # rubocop:disable Style/RescueModifier 116 | end 117 | 118 | def to_pretty_json(value) 119 | # Can't JSON.parse an empty string, so handle it separately 120 | return '' if value.strip.empty? 121 | 122 | sorted = recursive_sort(JSON.parse(value)) 123 | JSON.pretty_generate(sorted, 124 | { 125 | indent: ' ', 126 | space: ' ', 127 | object_nl: "\n", 128 | array_nl: "\n" 129 | }) 130 | end 131 | 132 | def recursive_sort(obj) 133 | case obj 134 | when Array 135 | obj.map { |item| recursive_sort(item) } 136 | when Hash 137 | obj.keys.sort.each_with_object({}) do |key, hash| 138 | hash[key] = recursive_sort(obj[key]) 139 | end 140 | else 141 | obj 142 | end 143 | end 144 | 145 | def display_diff(old, new, indent) 146 | @out.print Diffy::Diff.new(old, new, { context: @diff_context_lines }) 147 | .to_s(String.disable_colorization ? :text : :color) 148 | .gsub("\n", "\n" + indent) 149 | .strip 150 | end 151 | 152 | def display_attribute( # rubocop:disable Metrics/ParameterLists 153 | resource, 154 | change_color, 155 | attribute_name, 156 | attribute_value, 157 | attribute_change_reason, 158 | attribute_value_indent_amount 159 | ) 160 | attribute_value_indent = ' ' * attribute_value_indent_amount 161 | 162 | if %i[~ -/+].include?(resource[:change]) 163 | display_modified_attribute(change_color, 164 | attribute_name, 165 | attribute_value, 166 | attribute_change_reason, 167 | attribute_value_indent, 168 | attribute_value_indent_amount) 169 | else 170 | display_added_or_removed_attribute(change_color, 171 | attribute_name, 172 | attribute_value, 173 | attribute_value_indent, 174 | attribute_value_indent_amount) 175 | end 176 | end 177 | 178 | # rubocop:disable Metrics/ParameterLists, Metrics/MethodLength 179 | def display_modified_attribute( 180 | change_color, 181 | attribute_name, 182 | attribute_value, 183 | attribute_change_reason, 184 | attribute_value_indent, 185 | attribute_value_indent_amount 186 | ) 187 | # Since the attribute line is always of the form "old value" => "new value" 188 | attribute_value =~ /^ *(".*") *=> *(".*") *$/ 189 | old = undump(Regexp.last_match[1]) 190 | new = undump(Regexp.last_match[2]) 191 | 192 | return if old == new && new != '' # Don't show unchanged attributes 193 | 194 | @out.print " #{attribute_name}:".ljust(attribute_value_indent_amount, ' ') 195 | .colorize(change_color) 196 | 197 | if json?(new) 198 | # Value looks like JSON, so prettify it to make it more readable 199 | fancy_old = "#{to_pretty_json(old)}\n" 200 | fancy_new = "#{to_pretty_json(new)}\n" 201 | display_diff(fancy_old, fancy_new, attribute_value_indent) 202 | elsif old.include?("\n") || new.include?("\n") 203 | # Multiline content, so display nicer diff 204 | display_diff("#{old}\n", "#{new}\n", attribute_value_indent) 205 | else 206 | # Typical values, so just show before/after 207 | @out.print '"' + old.colorize(:red) + '"' 208 | @out.print ' => '.colorize(:light_black) 209 | @out.print '"' + new.colorize(:green) + '"' 210 | end 211 | 212 | if attribute_change_reason 213 | @out.print " (#{attribute_change_reason})".colorize(:magenta) 214 | end 215 | 216 | @out.newline 217 | end 218 | 219 | def display_added_or_removed_attribute( 220 | change_color, 221 | attribute_name, 222 | attribute_value, 223 | attribute_value_indent, 224 | attribute_value_indent_amount 225 | ) 226 | @out.print " #{attribute_name}:".ljust(attribute_value_indent_amount, ' ') 227 | .colorize(change_color) 228 | 229 | evaluated_string = undump(attribute_value) 230 | if json?(evaluated_string) 231 | @out.print to_pretty_json(evaluated_string).gsub("\n", 232 | "\n#{attribute_value_indent}") 233 | .colorize(change_color) 234 | else 235 | @out.print "\"#{evaluated_string.colorize(change_color)}\"" 236 | end 237 | 238 | @out.newline 239 | end 240 | end 241 | -------------------------------------------------------------------------------- /lib/terraform_landscape/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Defines the gem version. 4 | module TerraformLandscape 5 | VERSION = '0.3.4'.freeze 6 | end 7 | -------------------------------------------------------------------------------- /spec/printer_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative './spec_helper' 2 | require 'terraform_landscape/output' 3 | require 'terraform_landscape/printer' 4 | 5 | describe TerraformLandscape::Printer do 6 | let(:output_io) do 7 | StringIO.new 8 | end 9 | let(:printer) do 10 | output = TerraformLandscape::Output.new(output_io) 11 | TerraformLandscape::Printer.new(output) 12 | end 13 | 14 | before(:all) do 15 | String.disable_colorization = true 16 | end 17 | 18 | after(:all) do 19 | String.disable_colorization = false 20 | end 21 | 22 | describe '#process_string' do 23 | subject do 24 | printer.process_string(terraform_output) 25 | output_io.string 26 | end 27 | 28 | context 'when there are no changes' do 29 | let(:terraform_output) { normalize_indent(<<-TXT) } 30 | Acquiring state lock. This may take a few moments... 31 | Refreshing Terraform state in-memory prior to plan... 32 | The refreshed state will be used to calculate this plan, but will not be 33 | persisted to local or remote state storage. 34 | 35 | aws_iam_role.role: Refreshing state... (ID: role) 36 | No changes. Infrastructure is up-to-date. 37 | 38 | This means that Terraform did not detect any differences between your 39 | configuration and real physical resources that exist. As a result, Terraform 40 | doesn't need to do anything. 41 | Releasing state lock. This may take a few moments... 42 | TXT 43 | 44 | it { should == normalize_indent(<<-OUT) } 45 | No changes. 46 | OUT 47 | end 48 | 49 | context 'when plan does nothing' do 50 | let(:terraform_output) { normalize_indent(<<-TXT) } 51 | Acquiring state lock. This may take a few moments... 52 | Refreshing Terraform state in-memory prior to plan... 53 | The refreshed state will be used to calculate this plan, but will not be 54 | persisted to local or remote state storage. 55 | 56 | aws_iam_role.role: Refreshing state... (ID: role) 57 | This plan does nothing. 58 | 59 | This means that Terraform did not detect any differences between your 60 | configuration and real physical resources that exist. As a result, Terraform 61 | doesn't need to do anything. 62 | Releasing state lock. This may take a few moments... 63 | TXT 64 | 65 | it { should == normalize_indent(<<-OUT) } 66 | No changes. 67 | OUT 68 | end 69 | 70 | context 'when output contains a pre- and post-face' do 71 | let(:terraform_output) { normalize_indent(<<-TXT) } 72 | Path: terraform.tfplan 73 | 74 | ~ some_resource_type.some_resource_name 75 | some_attribute_name: "3" => "4" 76 | 77 | Plan: 0 to add, 1 to change, 0 to destroy. 78 | Releasing state lock. This may take a few moments... 79 | TXT 80 | 81 | it { should == normalize_indent(<<-OUT) } 82 | ~ some_resource_type.some_resource_name 83 | some_attribute_name: "3" => "4" 84 | 85 | Plan: 0 to add, 1 to change, 0 to destroy. 86 | 87 | OUT 88 | end 89 | 90 | context 'when output contains a legend of the resource operations' do 91 | let(:terraform_output) { normalize_indent(<<-TXT) } 92 | Resource actions are indicated with the following symbols: 93 | + create 94 | ~ update in-place 95 | 96 | Terraform will perform the following actions: 97 | 98 | ~ some_resource_type.some_resource_name 99 | some_attribute_name: "3" => "4" 100 | 101 | Plan: 0 to add, 1 to change, 0 to destroy. 102 | Releasing state lock. This may take a few moments... 103 | TXT 104 | 105 | it { should == normalize_indent(<<-OUT) } 106 | ~ some_resource_type.some_resource_name 107 | some_attribute_name: "3" => "4" 108 | 109 | Plan: 0 to add, 1 to change, 0 to destroy. 110 | 111 | OUT 112 | end 113 | 114 | context 'when output does not contain a Path' do 115 | let(:terraform_output) { normalize_indent(<<-TXT) } 116 | Note: You didn't specify an "-out" parameter to save this plan, so when 117 | "apply" is called, Terraform can't guarantee this is what will execute. 118 | 119 | ~ some_resource_type.some_resource_name 120 | some_attribute_name: "3" => "4" 121 | 122 | Plan: 0 to add, 1 to change, 0 to destroy. 123 | Releasing state lock. This may take a few moments... 124 | TXT 125 | 126 | it { should == normalize_indent(<<-OUT) } 127 | ~ some_resource_type.some_resource_name 128 | some_attribute_name: "3" => "4" 129 | 130 | Plan: 0 to add, 1 to change, 0 to destroy. 131 | 132 | OUT 133 | end 134 | 135 | context 'when output does not contain a pre- or post-face' do 136 | let(:terraform_output) { normalize_indent(<<-TXT) } 137 | ~ some_resource_type.some_resource_name 138 | some_attribute_name: "3" => "4" 139 | TXT 140 | 141 | it { should == normalize_indent(<<-OUT) } 142 | ~ some_resource_type.some_resource_name 143 | some_attribute_name: "3" => "4" 144 | 145 | 146 | OUT 147 | end 148 | 149 | context 'when output contains initialization messages' do 150 | let(:terraform_output) { normalize_indent(<<-TXT) } 151 | Initializing provider plugins... 152 | - Checking for available provider plugins on https://releases.hashicorp.com... 153 | - Downloading plugin for provider "aws" (1.1.0)... 154 | 155 | The following providers do not have any version constraints in configuration, 156 | so the latest version was installed. 157 | 158 | To prevent automatic upgrades to new major versions that may contain breaking 159 | changes, it is recommended to add version = "..." constraints to the 160 | corresponding provider blocks in configuration, with the constraint strings 161 | suggested below. 162 | 163 | * provider.aws: version = "~> 1.1" 164 | 165 | Terraform has been successfully initialized! 166 | 167 | You may now begin working with Terraform. Try running "terraform plan" to see 168 | any changes that are required for your infrastructure. All Terraform commands 169 | should now work. 170 | 171 | If you ever set or change modules or backend configuration for Terraform, 172 | rerun this command to reinitialize your working directory. If you forget, other 173 | commands will detect it and remind you to do so if necessary. 174 | 175 | No changes. Infrastructure is up-to-date. 176 | 177 | This means that Terraform did not detect any differences between your 178 | configuration and real physical resources that exist. As a result, no 179 | actions need to be performed. 180 | TXT 181 | 182 | it { should == normalize_indent(<<-OUT) } 183 | No changes. 184 | OUT 185 | end 186 | 187 | context 'when output contains module initialization messages' do 188 | let(:terraform_output) { normalize_indent(<<-TXT) } 189 | Initializing modules... 190 | - module.base_network 191 | Getting source "../modules/base_network" 192 | - module.ecs_service 193 | Found version 0.3.0 of ecs-service on registry.terraform.io 194 | Getting source "ecs-service" 195 | 196 | Initializing the backend... 197 | 198 | Successfully configured the backend "s3"! Terraform will automatically 199 | use this backend unless the backend configuration changes. 200 | 201 | Initializing provider plugins... 202 | - Checking for available provider plugins on https://releases.hashicorp.com... 203 | - Downloading plugin for provider "aws" (1.1.0)... 204 | 205 | The following providers do not have any version constraints in configuration, 206 | so the latest version was installed. 207 | 208 | To prevent automatic upgrades to new major versions that may contain breaking 209 | changes, it is recommended to add version = "..." constraints to the 210 | corresponding provider blocks in configuration, with the constraint strings 211 | suggested below. 212 | 213 | * provider.aws: version = "~> 1.1" 214 | 215 | Terraform has been successfully initialized! 216 | 217 | You may now begin working with Terraform. Try running "terraform plan" to see 218 | any changes that are required for your infrastructure. All Terraform commands 219 | should now work. 220 | 221 | If you ever set or change modules or backend configuration for Terraform, 222 | rerun this command to reinitialize your working directory. If you forget, other 223 | commands will detect it and remind you to do so if necessary. 224 | 225 | No changes. Infrastructure is up-to-date. 226 | 227 | This means that Terraform did not detect any differences between your 228 | configuration and real physical resources that exist. As a result, no 229 | actions need to be performed. 230 | TXT 231 | 232 | it { should == normalize_indent(<<-OUT) } 233 | No changes. 234 | OUT 235 | end 236 | 237 | context 'when output contains a separator after refreshing state' do 238 | let(:terraform_output) { normalize_indent(<<-TXT) } 239 | Refreshing Terraform state in-memory prior to plan... 240 | The refreshed state will be used to calculate this plan, but will not be 241 | persisted to local or remote state storage. 242 | 243 | aws_vpc.poc: Refreshing state... (ID: ##vpc-xxxxxxxxxxxxx) 244 | data.aws_iam_policy_document.flowlogs: Refreshing state... 245 | data.aws_iam_policy_document.rds_assume_policy: Refreshing state... 246 | data.aws_iam_policy_document.flowlogs_assume_role_policy: Refreshing state... 247 | aws_iam_role.rds: Refreshing state... (ID: xxxxxxxxxxxxxxxxxRole) 248 | aws_iam_role.flowlogs: Refreshing state... (ID: xxxxxxxxxxxxxxRole) 249 | aws_iam_role_policy.flowlogs: Refreshing state... (ID: xxxxxxxxxxxxxCreatePolicy) 250 | aws_iam_role_policy_attachment.rds: Refreshing state... (ID: xxxxxxxxxxxxxxRole-20171030050803915500000001) 251 | 252 | ------------------------------------------------------------------------ 253 | 254 | No changes. Infrastructure is up-to-date. 255 | 256 | This means that Terraform did not detect any differences between your 257 | configuration and real physical resources that exist. As a result, no 258 | actions need to be performed. 259 | TXT 260 | 261 | it { should == normalize_indent(<<-OUT) } 262 | No changes. 263 | OUT 264 | end 265 | 266 | context 'when output contains a warning before refreshing state' do 267 | let(:terraform_output) { normalize_indent(<<-TXT) } 268 | Warning: data.aws_region.this: "current": [DEPRECATED] Defaults to current provider region if no other filtering is enabled 269 | 270 | Refreshing Terraform state in-memory prior to plan... 271 | The refreshed state will be used to calculate this plan, but will not be 272 | persisted to local or remote state storage. 273 | 274 | aws_vpc.poc: Refreshing state... (ID: ##vpc-xxxxxxxxxxxxx) 275 | data.aws_iam_policy_document.flowlogs: Refreshing state... 276 | data.aws_iam_policy_document.rds_assume_policy: Refreshing state... 277 | data.aws_iam_policy_document.flowlogs_assume_role_policy: Refreshing state... 278 | aws_iam_role.rds: Refreshing state... (ID: xxxxxxxxxxxxxxxxxRole) 279 | aws_iam_role.flowlogs: Refreshing state... (ID: xxxxxxxxxxxxxxRole) 280 | aws_iam_role_policy.flowlogs: Refreshing state... (ID: xxxxxxxxxxxxxCreatePolicy) 281 | aws_iam_role_policy_attachment.rds: Refreshing state... (ID: xxxxxxxxxxxxxxRole-20171030050803915500000001) 282 | 283 | ------------------------------------------------------------------------ 284 | 285 | No changes. Infrastructure is up-to-date. 286 | 287 | This means that Terraform did not detect any differences between your 288 | configuration and real physical resources that exist. As a result, no 289 | actions need to be performed. 290 | TXT 291 | 292 | it { should == normalize_indent(<<-OUT) } 293 | Warning: data.aws_region.this: "current": [DEPRECATED] Defaults to current provider region if no other filtering is enabled 294 | No changes. 295 | OUT 296 | end 297 | end 298 | 299 | describe '#process_stream' do 300 | subject do 301 | output_io.string 302 | end 303 | 304 | around(:each) do |example| 305 | Timeout.timeout(2) do 306 | example.run 307 | end 308 | end 309 | 310 | it 'processes a completed stream' do 311 | terraform_output = normalize_indent(<<-TXT) 312 | Path: terraform.tfplan 313 | 314 | ~ some_resource_type.some_resource_name 315 | some_attribute_name: "3" => "4" 316 | 317 | Plan: 0 to add, 1 to change, 0 to destroy. 318 | Releasing state lock. This may take a few moments... 319 | TXT 320 | 321 | outstream, instream = IO.pipe 322 | terraform_output.split("\n").each do |line| 323 | instream.puts(line) 324 | end 325 | instream.close 326 | printer.process_stream(outstream) 327 | 328 | should == normalize_indent(<<-OUT) 329 | ~ some_resource_type.some_resource_name 330 | some_attribute_name: "3" => "4" 331 | 332 | Plan: 0 to add, 1 to change, 0 to destroy. 333 | 334 | OUT 335 | end 336 | 337 | it "processes an apply prompt that's still open" do 338 | terraform_output = normalize_indent(<<-TXT) 339 | Path: terraform.tfplan 340 | 341 | ~ some_resource_type.some_resource_name 342 | some_attribute_name: "3" => "4" 343 | 344 | Plan: 0 to add, 1 to change, 0 to destroy. 345 | 346 | Do you want to perform these actions? 347 | Terraform will perform the actions described above. 348 | Only 'yes' will be accepted to approve. 349 | 350 | Enter a value: 351 | TXT 352 | 353 | begin 354 | outstream, instream = IO.pipe 355 | 356 | process = Thread.new do 357 | printer.process_stream(outstream) 358 | end 359 | 360 | terraform_output.split("\n").each do |line| 361 | instream.puts(line) 362 | end 363 | 364 | sleep(0.2) 365 | 366 | should == normalize_indent(<<-OUT) 367 | ~ some_resource_type.some_resource_name 368 | some_attribute_name: "3" => "4" 369 | 370 | Plan: 0 to add, 1 to change, 0 to destroy. 371 | 372 | Do you want to perform these actions? 373 | Terraform will perform the actions described above. 374 | Only 'yes' will be accepted to approve. 375 | 376 | Enter a value: 377 | OUT 378 | ensure 379 | # finish off the input stream and check that the process ends 380 | instream.close 381 | process.join 382 | end 383 | end 384 | 385 | it 'falls back on the original Terraform output when a ParseError occurs' do 386 | terraform_output = 'gibberishhsirebbiggibberish' 387 | outstream, instream = IO.pipe 388 | terraform_output.split("\n").each do |line| 389 | instream.puts(line) 390 | end 391 | instream.close 392 | printer.process_stream(outstream) 393 | should == TerraformLandscape::FALLBACK_MESSAGE + "\n" + terraform_output + "\n" 394 | end 395 | 396 | it 'returns stack trace when a ParseError occurs and the trace option is provided' do 397 | terraform_output = 'gibberishhsirebbiggibberish' 398 | outstream, instream = IO.pipe 399 | terraform_output.split("\n").each do |line| 400 | instream.puts(line) 401 | end 402 | instream.close 403 | expect { printer.process_stream(outstream, { trace: true }) } 404 | .to raise_error(TerraformLandscape::ParseError) 405 | end 406 | end 407 | end 408 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'rspec' 2 | require 'timeout' 3 | require 'terraform_landscape' 4 | 5 | Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |f| require f } 6 | -------------------------------------------------------------------------------- /spec/support/normalize_indent.rb: -------------------------------------------------------------------------------- 1 | module IndentNormalizer 2 | # Strips off excess leading indentation from each line so we can use Heredocs 3 | # for writing code without having the leading indentation included. 4 | def normalize_indent(code) 5 | leading_indent = code[/^(\s*)/, 1] 6 | code.lstrip.gsub(/\n#{leading_indent}/, "\n") 7 | end 8 | end 9 | 10 | RSpec.configure do |_config| 11 | include IndentNormalizer 12 | end 13 | -------------------------------------------------------------------------------- /spec/terraform_plan_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative './spec_helper' 2 | require 'terraform_landscape/terraform_plan' 3 | 4 | describe TerraformLandscape::TerraformPlan do 5 | describe '#display' do 6 | before(:all) do 7 | String.disable_colorization = true 8 | end 9 | 10 | after(:all) do 11 | String.disable_colorization = false 12 | end 13 | 14 | subject do 15 | output_io = StringIO.new 16 | output = TerraformLandscape::Output.new(output_io) 17 | described_class.from_output(terraform_output).display(output) 18 | output_io.string 19 | end 20 | 21 | context 'when there is no output' do 22 | let(:terraform_output) { '' } 23 | it { should be_empty } 24 | end 25 | 26 | context 'when output contains only whitespace' do 27 | let(:terraform_output) { " \n " } 28 | it { should be_empty } 29 | end 30 | 31 | context 'when output contains a single resource with one attribute' do 32 | let(:terraform_output) { normalize_indent(<<-TXT) } 33 | ~ some_resource_type.some_resource_name 34 | some_attribute_name: "3" => "4" 35 | TXT 36 | 37 | it { should == normalize_indent(<<-OUT) } 38 | ~ some_resource_type.some_resource_name 39 | some_attribute_name: "3" => "4" 40 | 41 | OUT 42 | end 43 | 44 | context 'when output contains a single resource with one UTF-8 attribute' do 45 | let(:terraform_output) { normalize_indent(<<-TXT) } 46 | ~ some_resource_type.some_resource_name 47 | some_attribute_name: "3" => "こんにちは" 48 | TXT 49 | 50 | it { should == normalize_indent(<<-OUT) } 51 | ~ some_resource_type.some_resource_name 52 | some_attribute_name: "3" => "こんにちは" 53 | 54 | OUT 55 | end 56 | 57 | context 'when output contains a resource with an index number' do 58 | let(:terraform_output) { normalize_indent(<<-TXT) } 59 | + some_resource_type.some_resource_name.0 60 | 61 | TXT 62 | 63 | it { should == normalize_indent(<<-OUT) } 64 | + some_resource_type.some_resource_name.0 65 | 66 | OUT 67 | end 68 | 69 | context 'when output contains a single resource with no attributes' do 70 | let(:terraform_output) { normalize_indent(<<-TXT) } 71 | - some_resource_type.some_resource_name 72 | 73 | TXT 74 | 75 | it { should == normalize_indent(<<-OUT) } 76 | - some_resource_type.some_resource_name 77 | 78 | OUT 79 | end 80 | 81 | context 'when output contains a multiple resources with no attributes' do 82 | let(:terraform_output) { normalize_indent(<<-TXT) } 83 | + some_resource_type.some_resource_name 84 | 85 | + some_resource_type.some_resource_name 86 | 87 | TXT 88 | 89 | it { should == normalize_indent(<<-OUT) } 90 | + some_resource_type.some_resource_name 91 | 92 | + some_resource_type.some_resource_name 93 | 94 | OUT 95 | end 96 | 97 | context 'when output contains resources separate by Windows newlines' do 98 | let(:terraform_output) { normalize_indent(<<-TXT) } 99 | + some_resource_type.some_resource_name\r\n 100 | + some_resource_type.some_resource_name\r\n 101 | TXT 102 | 103 | it { should == normalize_indent(<<-OUT) } 104 | + some_resource_type.some_resource_name 105 | 106 | + some_resource_type.some_resource_name 107 | 108 | OUT 109 | end 110 | 111 | context 'when output contains a single resource with multiple attributes' do 112 | let(:terraform_output) { normalize_indent(<<-TXT) } 113 | ~ some_resource_type.some_resource_name 114 | some_attribute_name: "3" => "4" 115 | another_attribute_name: "6" => "7" 116 | yet_another_attribute_name: "9" => "7" 117 | TXT 118 | 119 | it { should == normalize_indent(<<-OUT) } 120 | ~ some_resource_type.some_resource_name 121 | some_attribute_name: "3" => "4" 122 | another_attribute_name: "6" => "7" 123 | yet_another_attribute_name: "9" => "7" 124 | 125 | OUT 126 | end 127 | 128 | context 'when output contains a rebuilt resource' do 129 | let(:terraform_output) { normalize_indent(<<-TXT) } 130 | -/+ random_id.abc (tainted) 131 | b64: "e20SLHAH5CXBCw" => "" 132 | b64_std: "e20SLHAH5CXBCw==" => "" 133 | b64_url: "e20SLHAH5CXBCw" => "" 134 | 135 | TXT 136 | 137 | it { should == normalize_indent(<<-OUT) } 138 | -/+ random_id.abc (tainted) 139 | b64: "e20SLHAH5CXBCw" => "" 140 | b64_std: "e20SLHAH5CXBCw==" => "" 141 | b64_url: "e20SLHAH5CXBCw" => "" 142 | 143 | OUT 144 | end 145 | 146 | context 'when output contains a rebuilt resource and no quotes' do 147 | let(:terraform_output) { normalize_indent(<<-TXT) } 148 | -/+ random_id.abc (tainted) 149 | b64: "e20SLHAH5CXBCw" => 150 | b64_std: "e20SLHAH5CXBCw==" => 151 | b64_url: "e20SLHAH5CXBCw" => 152 | 153 | TXT 154 | 155 | it { should == normalize_indent(<<-OUT) } 156 | -/+ random_id.abc (tainted) 157 | b64: "e20SLHAH5CXBCw" => "" 158 | b64_std: "e20SLHAH5CXBCw==" => "" 159 | b64_url: "e20SLHAH5CXBCw" => "" 160 | 161 | OUT 162 | end 163 | 164 | context 'when output contains a rebuilt resource with additional reason' do 165 | let(:terraform_output) { normalize_indent(<<-TXT) } 166 | -/+ null_resource.foo (tainted) (new resource required) 167 | id: "123456789" => (forces new resource) 168 | triggers.%: "1" => "2" 169 | 170 | TXT 171 | 172 | it { should == normalize_indent(<<-OUT) } 173 | -/+ null_resource.foo (tainted) (new resource required) 174 | id: "123456789" => "" (forces new resource) 175 | triggers.%: "1" => "2" 176 | 177 | OUT 178 | end 179 | 180 | context 'when output contains a resource read action' do 181 | let(:terraform_output) { normalize_indent(<<-TXT) } 182 | <= data.external.ext 183 | program.#: "2" 184 | program.0: "echo" 185 | program.1: "hello" 186 | query.%: "" 187 | result.%: "" 188 | 189 | TXT 190 | 191 | it { should == normalize_indent(<<-OUT) } 192 | <= data.external.ext 193 | program.#: "2" 194 | program.0: "echo" 195 | program.1: "hello" 196 | query.%: "" 197 | result.%: "" 198 | 199 | OUT 200 | end 201 | 202 | context 'when output contains an attribute change forcing a rebuild' do 203 | let(:terraform_output) { normalize_indent(<<-TXT) } 204 | -/+ template_file.demo 205 | rendered: "" => "" 206 | template: "" => "" (forces new resource) 207 | 208 | TXT 209 | 210 | it { should == normalize_indent(<<-OUT) } 211 | -/+ template_file.demo 212 | rendered: "" => "" 213 | template: "" => "" (forces new resource) 214 | 215 | OUT 216 | end 217 | 218 | context 'when output contains an attribute change forcing a rebuild without quotes' do 219 | let(:terraform_output) { normalize_indent(<<-TXT) } 220 | -/+ template_file.demo 221 | rendered: "" => 222 | template: "" => (forces new resource) 223 | 224 | TXT 225 | 226 | it { should == normalize_indent(<<-OUT) } 227 | -/+ template_file.demo 228 | rendered: "" => "" 229 | template: "" => "" (forces new resource) 230 | 231 | OUT 232 | end 233 | 234 | context 'when output contains an attribute containing the string ' do 235 | let(:terraform_output) { normalize_indent(<<-TXT) } 236 | -/+ template_file.demo 237 | rendered: "" => "This string contains " 238 | bendered: "" => "This string contains => with an arrow" 239 | template: "" => "This string contains in it" (forces new resource) 240 | 241 | TXT 242 | 243 | it { should == normalize_indent(<<-OUT) } 244 | -/+ template_file.demo 245 | rendered: "" => "This string contains " 246 | bendered: "" => "This string contains => with an arrow" 247 | template: "" => "This string contains in it" (forces new resource) 248 | 249 | OUT 250 | end 251 | 252 | context 'when output contains multiple modified resources' do 253 | let(:terraform_output) { normalize_indent(<<-TXT) } 254 | ~ some_resource_type.some_resource_name 255 | some_attribute_name: "3" => "4" 256 | another_attribute_name: "6" => "7" 257 | yet_another_attribute_name: "9" => "7" 258 | 259 | ~ another_resource_type.another_resource_name 260 | some_attribute_name: "8" => "4" 261 | another_attribute_name: "foo" => "bar" 262 | yet_another_attribute_name: "hello" => "world" 263 | TXT 264 | 265 | it { should == normalize_indent(<<-OUT) } 266 | ~ some_resource_type.some_resource_name 267 | some_attribute_name: "3" => "4" 268 | another_attribute_name: "6" => "7" 269 | yet_another_attribute_name: "9" => "7" 270 | 271 | ~ another_resource_type.another_resource_name 272 | some_attribute_name: "8" => "4" 273 | another_attribute_name: "foo" => "bar" 274 | yet_another_attribute_name: "hello" => "world" 275 | 276 | OUT 277 | end 278 | 279 | context 'when output attribute name contains a space' do 280 | let(:terraform_output) { normalize_indent(<<-TXT) } 281 | + some_resource_type.some_resource_name 282 | some_attribute_name: "2" 283 | some_attribute.with space: "blah" 284 | TXT 285 | 286 | it { should == normalize_indent(<<-OUT) } 287 | + some_resource_type.some_resource_name 288 | some_attribute_name: "2" 289 | some_attribute.with space: "blah" 290 | 291 | OUT 292 | end 293 | 294 | context 'when added resource contains an attribute with JSON' do 295 | let(:terraform_output) { normalize_indent(<<-TXT) } 296 | + aws_iam_policy.user-my-test 297 | arn: "" 298 | name: "user-my-test" 299 | path: "/" 300 | policy: "{\\"Statement\\":[{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:dynamodb:us-east-1:123456789012:table/my-table\\"],\\"Action\\":[\\"dynamodb:*\\",\\"s3:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:s3:::my-s3-development\\"],\\"Action\\":[\\"s3:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Deny\\",\\"Resource\\":[\\"*\\"],\\"Action\\":[\\"dynamodb:DeleteTable\\",\\"s3:DeleteBucket\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}}],\\"Version\\":\\"2012-10-17\\"}" 301 | TXT 302 | 303 | it { should == normalize_indent(<<-OUT) } 304 | + aws_iam_policy.user-my-test 305 | arn: "" 306 | name: "user-my-test" 307 | path: "/" 308 | policy: { 309 | "Statement": [ 310 | { 311 | "Action": [ 312 | "dynamodb:*", 313 | "s3:*" 314 | ], 315 | "Condition": { 316 | "Bool": { 317 | "aws:SecureTransport": "true" 318 | } 319 | }, 320 | "Effect": "Allow", 321 | "Resource": [ 322 | "arn:aws:dynamodb:us-east-1:123456789012:table/my-table" 323 | ] 324 | }, 325 | { 326 | "Action": [ 327 | "s3:*" 328 | ], 329 | "Condition": { 330 | "Bool": { 331 | "aws:SecureTransport": "true" 332 | } 333 | }, 334 | "Effect": "Allow", 335 | "Resource": [ 336 | "arn:aws:s3:::my-s3-development" 337 | ] 338 | }, 339 | { 340 | "Action": [ 341 | "dynamodb:DeleteTable", 342 | "s3:DeleteBucket" 343 | ], 344 | "Condition": { 345 | "Bool": { 346 | "aws:SecureTransport": "true" 347 | } 348 | }, 349 | "Effect": "Deny", 350 | "Resource": [ 351 | "*" 352 | ] 353 | } 354 | ], 355 | "Version": "2012-10-17" 356 | } 357 | 358 | OUT 359 | end 360 | 361 | context 'when modified resource contains an attribute with JSON' do 362 | let(:terraform_output) { normalize_indent(<<-TXT) } 363 | ~ aws_iam_policy.my-user-test 364 | policy: "{\\"Statement\\":[{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:dynamodb:us-east-1:123456789012:table/my-user-test\\"],\\"Action\\":[\\"dynamodb:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:s3:::my-s3-development\\",\\"arn:aws:s3:::my-s3-development/*\\"],\\"Action\\":[\\"s3:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Deny\\",\\"Resource\\":[\\"*\\"],\\"Action\\":[\\"dynamodb:DeleteTable\\",\\"s3:DeleteBucket\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}}],\\"Version\\":\\"2012-10-17\\"}\" => \"{\\"Statement\\":[{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:dynamodb:us-east-1:123456789012:table/my-user-test\\"],\\"Action\\":[\\"dynamodb:*\\",\\"s3:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Allow\\",\\"Resource\\":[\\"arn:aws:s3:::my-s3-development\\"],\\"Action\\":[\\"s3:*\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}},{\\"Effect\\":\\"Deny\\",\\"Resource\\":[\\"*\\"],\\"Action\\":[\\"dynamodb:DeleteTable\\",\\"s3:DeleteBucket\\"],\\"Condition\\":{\\"Bool\\":{\\"aws:SecureTransport\\":\\"true\\"}}}],\\"Version\\":\\"2012-10-17\\"}" 365 | TXT 366 | 367 | it { should == normalize_indent(<<-OUT) } 368 | ~ aws_iam_policy.my-user-test 369 | policy: { 370 | "Statement": [ 371 | { 372 | "Action": [ 373 | - "dynamodb:*" 374 | + "dynamodb:*", 375 | + "s3:*" 376 | ], 377 | "Condition": { 378 | "Bool": { 379 | "aws:SecureTransport": "true" 380 | } 381 | "aws:SecureTransport": "true" 382 | } 383 | }, 384 | "Effect": "Allow", 385 | "Resource": [ 386 | - "arn:aws:s3:::my-s3-development", 387 | - "arn:aws:s3:::my-s3-development/*" 388 | + "arn:aws:s3:::my-s3-development" 389 | ] 390 | }, 391 | { 392 | "Action": [ 393 | "dynamodb:DeleteTable", 394 | 395 | OUT 396 | end 397 | 398 | context 'when computed output is included without quotes' do 399 | let(:terraform_output) { normalize_indent(<<-TXT) } 400 | + some_resource_type.some_resource_name 401 | id: 402 | some_attribute_name: "foo" 403 | TXT 404 | 405 | it { should == normalize_indent(<<-OUT) } 406 | + some_resource_type.some_resource_name 407 | id: "" 408 | some_attribute_name: "foo" 409 | 410 | OUT 411 | end 412 | 413 | context 'when sensitive output is included without quotes' do 414 | let(:terraform_output) { normalize_indent(<<-TXT) } 415 | + some_resource_type.some_resource_name 416 | id: 417 | some_attribute_name: "foo" 418 | TXT 419 | 420 | it { should == normalize_indent(<<-OUT) } 421 | + some_resource_type.some_resource_name 422 | id: "" 423 | some_attribute_name: "foo" 424 | 425 | OUT 426 | end 427 | 428 | context 'when changed sensitive output is included without quotes' do 429 | let(:terraform_output) { normalize_indent(<<-TXT) } 430 | ~ some_resource_type.some_resource_name 431 | value: => (attribute changed) 432 | TXT 433 | 434 | it { should == normalize_indent(<<-OUT) } 435 | ~ some_resource_type.some_resource_name 436 | value: "" => "" (attribute changed) 437 | 438 | OUT 439 | end 440 | 441 | context 'when generic bracketed output is included without quotes' do 442 | let(:terraform_output) { normalize_indent(<<-TXT) } 443 | + some_resource_type.some_resource_name 444 | id: 445 | some_attribute_name: "foo" 446 | TXT 447 | 448 | it { should == normalize_indent(<<-OUT) } 449 | + some_resource_type.some_resource_name 450 | id: "" 451 | some_attribute_name: "foo" 452 | 453 | OUT 454 | end 455 | 456 | context 'when resouce contains tags and various characters' do 457 | let(:terraform_output) { normalize_indent(<<-TXT) } 458 | + some_resource_type.some_resource_name 459 | some_attribute_name: "foo" 460 | tags.%: "1" 461 | tags.foo:bar: "zip:zap" 462 | TXT 463 | 464 | it { should == normalize_indent(<<-OUT) } 465 | + some_resource_type.some_resource_name 466 | some_attribute_name: "foo" 467 | tags.%: "1" 468 | tags.foo:bar: "zip:zap" 469 | 470 | OUT 471 | end 472 | 473 | context 'when added resource contains an attribute with ruby string interpolation' do 474 | let(:terraform_output) { normalize_indent(<<-TXT) } 475 | + some_resource_type.some_resource_name 476 | some_attribute_name: "\#{host}" 477 | TXT 478 | 479 | it { should == normalize_indent(<<-OUT) } 480 | + some_resource_type.some_resource_name 481 | some_attribute_name: "\#{host}" 482 | 483 | OUT 484 | end 485 | 486 | context 'when output contains a single resource with ruby string interpolation' do 487 | let(:terraform_output) { normalize_indent(<<-TXT) } 488 | ~ some_resource_type.some_resource_name 489 | some_attribute_name: "\#{host}" => "\#{path}" 490 | TXT 491 | 492 | it { should == normalize_indent(<<-OUT) } 493 | ~ some_resource_type.some_resource_name 494 | some_attribute_name: "\#{host}" => "\#{path}" 495 | 496 | OUT 497 | end 498 | end 499 | end 500 | -------------------------------------------------------------------------------- /terraform_landscape.gemspec: -------------------------------------------------------------------------------- 1 | $LOAD_PATH << File.expand_path('../lib', __FILE__) 2 | require 'terraform_landscape/constants' 3 | require 'terraform_landscape/version' 4 | 5 | Gem::Specification.new do |s| 6 | s.name = 'terraform_landscape' 7 | s.version = TerraformLandscape::VERSION 8 | s.license = 'Apache-2.0' 9 | s.summary = 'Pretty-print Terraform plan output' 10 | s.description = 'Improve output of Terraform plans with color and indentation' 11 | s.authors = ['Coinbase', 'Shane da Silva'] 12 | s.email = ['shane@coinbase.com'] 13 | s.homepage = TerraformLandscape::REPO_URL 14 | 15 | s.require_paths = %w[lib] 16 | 17 | s.executables = ['landscape'] 18 | 19 | s.files = Dir['bin/**/*'] + 20 | Dir['lib/**/*.rb'] + 21 | Dir['grammar/**/*.treetop'] 22 | 23 | s.required_ruby_version = '>= 2.5' 24 | 25 | s.add_dependency 'colorize', '~> 0.7' 26 | s.add_dependency 'commander', '~> 4.4' 27 | s.add_dependency 'diffy', '~> 3.0' 28 | s.add_dependency 'treetop', '~> 1.6' 29 | end 30 | --------------------------------------------------------------------------------