├── .drone.yml ├── .gitignore ├── .rspec ├── .rubocop.relaxed.yml ├── .rubocop.yml ├── .travis.yml ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── README.md ├── Rakefile ├── bin └── mortar ├── build ├── drone │ ├── create_release.sh │ └── ubuntu_xenial.sh └── travis │ └── macos.sh ├── examples ├── basic │ ├── deployment.yml │ └── service.yml ├── config │ ├── config.yaml │ ├── pod.yml.erb │ └── shot.yaml ├── force-deployment │ └── deployment.yml.erb ├── overlays │ ├── echo-metal.yml │ ├── foo │ │ └── pod.yml.erb │ ├── partial │ │ └── echo.yml │ └── prod │ │ ├── pod.yml │ │ └── svc.yml └── templates │ ├── env_vars │ └── pod.yml.erb │ └── variables │ ├── loops.yml.erb │ └── pod-vars.yml.erb ├── kontena-mortar.gemspec ├── kontena-mortar.png ├── lib ├── extensions │ └── recursive_open_struct │ │ └── each.rb ├── mortar.rb └── mortar │ ├── command.rb │ ├── config.rb │ ├── describe_command.rb │ ├── fire_command.rb │ ├── install_completions_command.rb │ ├── list_command.rb │ ├── mixins │ ├── client_helper.rb │ ├── resource_helper.rb │ └── tty_helper.rb │ ├── root_command.rb │ ├── version.rb │ ├── yaml_file.rb │ └── yank_command.rb ├── opt └── bash-completion.sh └── spec ├── config_spec.rb ├── fire_spec.rb ├── fixtures └── config │ ├── config.yaml │ ├── config_empty.yaml │ ├── config_extra_keys.yaml │ ├── config_labels.yaml │ ├── config_labels_error.yaml │ ├── config_overlays.yaml │ └── config_overlays_error.yaml ├── helpers └── fixture_helpers.rb ├── mortar_spec.rb └── spec_helper.rb /.drone.yml: -------------------------------------------------------------------------------- 1 | kind: pipeline 2 | name: amd64 3 | 4 | platform: 5 | os: linux 6 | arch: amd64 7 | steps: 8 | - name: test 9 | image: ruby:2.6 10 | commands: 11 | - gem install bundler -v 2.0.2 12 | - bundle install --path bundler 13 | - bundle exec rspec spec/ 14 | - bundle exec rubocop lib/ 15 | - name: docker_latest 16 | image: plugins/docker 17 | settings: 18 | registry: quay.io 19 | username: 20 | from_secret: docker_username 21 | password: 22 | from_secret: docker_password 23 | repo: quay.io/kontena/mortar 24 | dockerfile: Dockerfile 25 | auto_tag: true 26 | when: 27 | branch: ['master'] 28 | event: ['push'] 29 | - name: docker_release 30 | image: plugins/docker 31 | settings: 32 | registry: quay.io 33 | username: 34 | from_secret: docker_username 35 | password: 36 | from_secret: docker_password 37 | repo: quay.io/kontena/mortar 38 | dockerfile: Dockerfile 39 | auto_tag: true 40 | when: 41 | event: ['tag'] 42 | - name: release-gem 43 | image: ruby:2.4 44 | environment: 45 | RUBYGEMS_AUTH: 46 | from_secret: rubygems_auth 47 | commands: 48 | - mkdir -p ~/.gem 49 | - echo $RUBYGEMS_AUTH | base64 -d > ~/.gem/credentials && chmod 0600 ~/.gem/credentials 50 | - gem build kontena-mortar.gemspec 51 | - gem push *.gem 52 | when: 53 | event: ['tag'] 54 | - name: create_gh_release 55 | image: ubuntu:xenial 56 | environment: 57 | GITHUB_TOKEN: 58 | from_secret: github_token 59 | commands: 60 | - ./build/drone/create_release.sh 61 | when: 62 | event: tag 63 | - name: build_xenial 64 | image: ubuntu:xenial 65 | environment: 66 | CPPFLAGS: '-P' 67 | GITHUB_TOKEN: 68 | from_secret: github_token 69 | commands: 70 | - ./build/drone/ubuntu_xenial.sh 71 | when: 72 | event: tag 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | 10 | # rspec failure tracking 11 | .rspec_status 12 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | --require spec_helper 4 | -------------------------------------------------------------------------------- /.rubocop.relaxed.yml: -------------------------------------------------------------------------------- 1 | # Relaxed.Ruby.Style 2 | ## Version 2.2 3 | 4 | Style/Alias: 5 | Enabled: false 6 | StyleGuide: http://relaxed.ruby.style/#stylealias 7 | 8 | Style/AsciiComments: 9 | Enabled: false 10 | StyleGuide: http://relaxed.ruby.style/#styleasciicomments 11 | 12 | Style/BeginBlock: 13 | Enabled: false 14 | StyleGuide: http://relaxed.ruby.style/#stylebeginblock 15 | 16 | Style/BlockDelimiters: 17 | Enabled: false 18 | StyleGuide: http://relaxed.ruby.style/#styleblockdelimiters 19 | 20 | Style/CommentAnnotation: 21 | Enabled: false 22 | StyleGuide: http://relaxed.ruby.style/#stylecommentannotation 23 | 24 | Style/Documentation: 25 | Enabled: false 26 | StyleGuide: http://relaxed.ruby.style/#styledocumentation 27 | 28 | Layout/DotPosition: 29 | Enabled: false 30 | StyleGuide: http://relaxed.ruby.style/#layoutdotposition 31 | 32 | Style/DoubleNegation: 33 | Enabled: false 34 | StyleGuide: http://relaxed.ruby.style/#styledoublenegation 35 | 36 | Style/EndBlock: 37 | Enabled: false 38 | StyleGuide: http://relaxed.ruby.style/#styleendblock 39 | 40 | Style/FormatString: 41 | Enabled: false 42 | StyleGuide: http://relaxed.ruby.style/#styleformatstring 43 | 44 | Style/IfUnlessModifier: 45 | Enabled: false 46 | StyleGuide: http://relaxed.ruby.style/#styleifunlessmodifier 47 | 48 | Style/Lambda: 49 | Enabled: false 50 | StyleGuide: http://relaxed.ruby.style/#stylelambda 51 | 52 | Style/ModuleFunction: 53 | Enabled: false 54 | StyleGuide: http://relaxed.ruby.style/#stylemodulefunction 55 | 56 | Style/MultilineBlockChain: 57 | Enabled: false 58 | StyleGuide: http://relaxed.ruby.style/#stylemultilineblockchain 59 | 60 | Style/NegatedIf: 61 | Enabled: false 62 | StyleGuide: http://relaxed.ruby.style/#stylenegatedif 63 | 64 | Style/NegatedWhile: 65 | Enabled: false 66 | StyleGuide: http://relaxed.ruby.style/#stylenegatedwhile 67 | 68 | Style/ParallelAssignment: 69 | Enabled: false 70 | StyleGuide: http://relaxed.ruby.style/#styleparallelassignment 71 | 72 | Style/PercentLiteralDelimiters: 73 | Enabled: false 74 | StyleGuide: http://relaxed.ruby.style/#stylepercentliteraldelimiters 75 | 76 | Style/PerlBackrefs: 77 | Enabled: false 78 | StyleGuide: http://relaxed.ruby.style/#styleperlbackrefs 79 | 80 | Style/Semicolon: 81 | Enabled: false 82 | StyleGuide: http://relaxed.ruby.style/#stylesemicolon 83 | 84 | Style/SignalException: 85 | Enabled: false 86 | StyleGuide: http://relaxed.ruby.style/#stylesignalexception 87 | 88 | Style/SingleLineBlockParams: 89 | Enabled: false 90 | StyleGuide: http://relaxed.ruby.style/#stylesinglelineblockparams 91 | 92 | Style/SingleLineMethods: 93 | Enabled: false 94 | StyleGuide: http://relaxed.ruby.style/#stylesinglelinemethods 95 | 96 | Layout/SpaceBeforeBlockBraces: 97 | Enabled: false 98 | StyleGuide: http://relaxed.ruby.style/#layoutspacebeforeblockbraces 99 | 100 | Layout/SpaceInsideParens: 101 | Enabled: false 102 | StyleGuide: http://relaxed.ruby.style/#layoutspaceinsideparens 103 | 104 | Style/SpecialGlobalVars: 105 | Enabled: false 106 | StyleGuide: http://relaxed.ruby.style/#stylespecialglobalvars 107 | 108 | Style/StringLiterals: 109 | Enabled: false 110 | StyleGuide: http://relaxed.ruby.style/#stylestringliterals 111 | 112 | # Style/TrailingCommaInArguments: 113 | # Enabled: false 114 | # StyleGuide: http://relaxed.ruby.style/#styletrailingcommainarguments 115 | # 116 | # Style/TrailingCommaInArrayLiteral: 117 | # Enabled: false 118 | # StyleGuide: http://relaxed.ruby.style/#styletrailingcommainarrayliteral 119 | # 120 | # Style/TrailingCommaInHashLiteral: 121 | # Enabled: false 122 | # StyleGuide: http://relaxed.ruby.style/#styletrailingcommainhashliteral 123 | 124 | Style/WhileUntilModifier: 125 | Enabled: false 126 | StyleGuide: http://relaxed.ruby.style/#stylewhileuntilmodifier 127 | 128 | Style/WordArray: 129 | Enabled: false 130 | StyleGuide: http://relaxed.ruby.style/#stylewordarray 131 | 132 | Lint/AmbiguousRegexpLiteral: 133 | Enabled: false 134 | StyleGuide: http://relaxed.ruby.style/#lintambiguousregexpliteral 135 | 136 | Lint/AssignmentInCondition: 137 | Enabled: false 138 | StyleGuide: http://relaxed.ruby.style/#lintassignmentincondition 139 | 140 | Metrics/AbcSize: 141 | Enabled: false 142 | 143 | Metrics/BlockNesting: 144 | Enabled: false 145 | 146 | Metrics/ClassLength: 147 | Enabled: false 148 | 149 | Metrics/ModuleLength: 150 | Enabled: false 151 | 152 | Metrics/CyclomaticComplexity: 153 | Enabled: false 154 | 155 | Metrics/LineLength: 156 | Enabled: false 157 | 158 | Metrics/MethodLength: 159 | Enabled: false 160 | 161 | Metrics/ParameterLists: 162 | Enabled: false 163 | 164 | Metrics/PerceivedComplexity: 165 | Enabled: false 166 | 167 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | inherit_from: .rubocop.relaxed.yml 2 | 3 | AllCops: 4 | Exclude: 5 | - spec/**/* 6 | - Gemfile 7 | - "*.gemspec" 8 | - bundler/**/* 9 | TargetRubyVersion: 2.4 10 | 11 | Style/PercentLiteralDelimiters: 12 | PreferredDelimiters: 13 | default: () 14 | '%i': '()' 15 | '%I': '()' 16 | '%r': '{}' 17 | '%w': '()' 18 | '%W': '()' 19 | 20 | Style/FormatString: 21 | EnforcedStyle: percent 22 | 23 | Style/FrozenStringLiteralComment: 24 | EnforcedStyle: always 25 | 26 | Style/WordArray: 27 | Enabled: true 28 | MinSize: 3 29 | 30 | Style/SymbolArray: 31 | Enabled: true 32 | MinSize: 3 33 | 34 | Gemspec/OrderedDependencies: 35 | Enabled: false 36 | 37 | Style/PerlBackrefs: 38 | Enabled: true 39 | 40 | Layout/SpaceInsideParens: 41 | Enabled: true 42 | 43 | Style/SpecialGlobalVars: 44 | Enabled: true 45 | 46 | Style/Alias: 47 | Enabled: true 48 | 49 | Style/BeginBlock: 50 | Enabled: true 51 | 52 | Naming/UncommunicativeMethodParamName: 53 | AllowedNames: 54 | - cn 55 | 56 | Metrics/BlockLength: 57 | Enabled: false 58 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | sudo: required 3 | cache: bundler 4 | bundler_args: --without development 5 | before_install: 6 | - gem install bundler -v 2.0.2 7 | env: 8 | global: 9 | - secure: "ODwK1K2gm4yBWSTgQ9SVyIMTheUnT55JtMKb8i8wQiKC3g74HHmiJGOMSqkCGenwF7Fc8e0BQEGHiyFDcCnuUVhU5oTDgOEEcCHiFAwDCv+tekBqCAjmccqRE5MamSZsN7myGULClaljFDKdRc5b/MN1f26bViYUq3H7m06jnW/JYn+32VenGFq1Py7QyTD1IqG2x6sC4zG7jqiIXqcM24sKO6Q49fb5KneqF+A4C2wHPpjuVmgqRcwrQKcNixPtiXs4Nn5UZEkH3ceAyXjBvElI2Bt6/sJLfB2C2/IdEob+MrKsBfGAcgSXPKGEQvMyzAkcWg7aXa65H09ta/sUe0OdgczAxeFIV26RmsHJN+/vW5b46+cgcIEnyTq0whsrKPiailEWfns7xgfY+Q4MazUJ6mbxhmRixaNSn6y1GIKqSYv5FpU/+KVfu0tdM/joOkHcNxnyIDWAnTegN0sEwMCnHEt9tkdXtMZe83B9BY2cbWM36BdW1zRHeTZj8kfHpifT34cuoiQrg2P19BLpqzIgrCMbznbXNEy/m9TisMplvY6SdpujqYhCdLd4srbzcxq2UDplWsL0QtRy+aiaPKFy24yDnKo45aBjDFI4787lxmlW96KMoXNISK2F050IxDJ5yQ0qeRY1GvTy2GWy/sSRvrr8gb+ZY9+/m2MbLqw=" 10 | stages: 11 | - name: publish binary 12 | if: tag IS present 13 | jobs: 14 | include: 15 | - stage: publish binary 16 | script: ./build/travis/macos.sh 17 | rvm: 2.6 18 | os: osx 19 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.5-alpine as build 2 | 3 | ADD . /src 4 | 5 | RUN apk --update add git build-base && \ 6 | cd /src ; gem build kontena-mortar.gemspec && \ 7 | gem install *.gem 8 | 9 | FROM ruby:2.5-alpine 10 | 11 | COPY --from=build /usr/local/bundle /usr/local/bundle 12 | 13 | ENTRYPOINT [ "/usr/local/bundle/bin/mortar" ] -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | # Specify your gem's dependencies in mortar.gemspec 3 | gemspec 4 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | kontena-mortar (0.4.7) 5 | clamp (~> 1.3) 6 | deep_merge (~> 1.2) 7 | k8s-client (~> 0.10.4) 8 | pastel (~> 0.7.2) 9 | rouge (~> 3.2) 10 | tty-table (~> 0.10.0) 11 | 12 | GEM 13 | remote: https://rubygems.org/ 14 | specs: 15 | ast (2.4.0) 16 | clamp (1.3.1) 17 | concurrent-ruby (1.1.5) 18 | deep_merge (1.2.1) 19 | diff-lcs (1.3) 20 | dry-configurable (0.8.3) 21 | concurrent-ruby (~> 1.0) 22 | dry-core (~> 0.4, >= 0.4.7) 23 | dry-container (0.7.2) 24 | concurrent-ruby (~> 1.0) 25 | dry-configurable (~> 0.1, >= 0.1.3) 26 | dry-core (0.4.9) 27 | concurrent-ruby (~> 1.0) 28 | dry-equalizer (0.2.2) 29 | dry-inflector (0.2.0) 30 | dry-logic (0.6.1) 31 | concurrent-ruby (~> 1.0) 32 | dry-core (~> 0.2) 33 | dry-equalizer (~> 0.2) 34 | dry-struct (0.5.1) 35 | dry-core (~> 0.4, >= 0.4.3) 36 | dry-equalizer (~> 0.2) 37 | dry-types (~> 0.13) 38 | ice_nine (~> 0.11) 39 | dry-types (0.13.4) 40 | concurrent-ruby (~> 1.0) 41 | dry-container (~> 0.3) 42 | dry-core (~> 0.4, >= 0.4.4) 43 | dry-equalizer (~> 0.2) 44 | dry-inflector (~> 0.1, >= 0.1.2) 45 | dry-logic (~> 0.4, >= 0.4.2) 46 | equatable (0.5.0) 47 | excon (0.71.0) 48 | hashdiff (1.0.0) 49 | ice_nine (0.11.2) 50 | jaro_winkler (1.5.3) 51 | jsonpath (0.9.9) 52 | multi_json 53 | to_regexp (~> 0.2.1) 54 | k8s-client (0.10.4) 55 | dry-struct (~> 0.5.0) 56 | dry-types (~> 0.13.0) 57 | excon (~> 0.66) 58 | hashdiff (~> 1.0.0) 59 | jsonpath (~> 0.9.5) 60 | recursive-open-struct (~> 1.1.0) 61 | yajl-ruby (~> 1.4.0) 62 | yaml-safe_load_stream (~> 0.1) 63 | multi_json (1.14.1) 64 | necromancer (0.4.0) 65 | parallel (1.17.0) 66 | parser (2.6.4.1) 67 | ast (~> 2.4.0) 68 | pastel (0.7.2) 69 | equatable (~> 0.5.0) 70 | tty-color (~> 0.4.0) 71 | rainbow (3.0.0) 72 | rake (10.5.0) 73 | recursive-open-struct (1.1.0) 74 | rouge (3.12.0) 75 | rspec (3.8.0) 76 | rspec-core (~> 3.8.0) 77 | rspec-expectations (~> 3.8.0) 78 | rspec-mocks (~> 3.8.0) 79 | rspec-core (3.8.2) 80 | rspec-support (~> 3.8.0) 81 | rspec-expectations (3.8.4) 82 | diff-lcs (>= 1.2.0, < 2.0) 83 | rspec-support (~> 3.8.0) 84 | rspec-mocks (3.8.1) 85 | diff-lcs (>= 1.2.0, < 2.0) 86 | rspec-support (~> 3.8.0) 87 | rspec-support (3.8.2) 88 | rubocop (0.74.0) 89 | jaro_winkler (~> 1.5.1) 90 | parallel (~> 1.10) 91 | parser (>= 2.6) 92 | rainbow (>= 2.2.2, < 4.0) 93 | ruby-progressbar (~> 1.7) 94 | unicode-display_width (>= 1.4.0, < 1.7) 95 | ruby-progressbar (1.10.1) 96 | strings (0.1.6) 97 | strings-ansi (~> 0.1) 98 | unicode-display_width (~> 1.5) 99 | unicode_utils (~> 1.4) 100 | strings-ansi (0.1.0) 101 | to_regexp (0.2.1) 102 | tty-color (0.4.3) 103 | tty-screen (0.6.5) 104 | tty-table (0.10.0) 105 | equatable (~> 0.5.0) 106 | necromancer (~> 0.4.0) 107 | pastel (~> 0.7.2) 108 | strings (~> 0.1.0) 109 | tty-screen (~> 0.6.4) 110 | unicode-display_width (1.6.0) 111 | unicode_utils (1.4.0) 112 | yajl-ruby (1.4.1) 113 | yaml-safe_load_stream (0.1.1) 114 | 115 | PLATFORMS 116 | ruby 117 | 118 | DEPENDENCIES 119 | bundler (~> 2.0.0) 120 | kontena-mortar! 121 | rake (~> 10.0) 122 | rspec (~> 3.0) 123 | rubocop (~> 0.57) 124 | 125 | BUNDLED WITH 126 | 2.0.2 127 | -------------------------------------------------------------------------------- /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 Kontena 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kontena Mortar 2 | 3 | ![Mortar - Manifest shooter for Kubernetes](kontena-mortar.png) 4 | 5 | Mortar is a tool to easily handle a complex set of Kubernetes resources. Using `kubectl apply -f some_folder/` is pretty straightforward for simple cases, but often, especially in CI/CD pipelines things get complex. Then on the otherhand, writing everything in Helm charts is way too complex. 6 | 7 | While we were developing [Kontena Pharos](https://kontena.io/pharos) Kubernetes distro and tooling around it, we soon realized that we really want to manage sets of resources as a single unit. This thinking got even stronger while we were transitioning many of our production solutions to run on top of Kubernetes. As this is a common problem for all Kubernetes users, Mortar was born. 8 | 9 | ## Features 10 | 11 | - [Management of sets of resources as a single unit](#shots) 12 | - [Simple templating](#templating) 13 | - [Overlays](#overlays) 14 | 15 | ## Installation 16 | 17 | ### Binaries 18 | 19 | Mortar pre-baked binaries are available for OSX and Linux. You can download them from the [releases](https://github.com/kontena/mortar/releases) page. Remember to put it in the path and change the executable bit on. 20 | 21 | ### MacOS Homebrew 22 | 23 | `$ brew install kontena/mortar/mortar` 24 | 25 | Or to install the latest development version: 26 | 27 | `$ brew install --HEAD kontena/mortar/mortar` 28 | 29 | ### Rubygems: 30 | 31 | `$ gem install kontena-mortar` 32 | 33 | To install bash/zsh auto-completions, use `mortar install-completions` after Mortar has been installed. 34 | 35 | ### Docker: 36 | 37 | `$ docker pull quay.io/kontena/mortar:latest` 38 | 39 | 40 | ## Usage 41 | 42 | ### Configuration 43 | 44 | By default mortar looks for if file `~/.kube/config` exists and uses it as the configuration. Configuration file path can be overridden with `KUBECONFIG` environment variable. 45 | 46 | For CI/CD use mortar also understands following environment variables: 47 | 48 | - `KUBE_SERVER`: kubernetes api server address, for example `https://10.10.10.10:6443` 49 | - `KUBE_TOKEN`: service account token (base64 encoded) 50 | - `KUBE_CA`: kubernetes CA certificate (base64 encoded) 51 | 52 | ### Deploying k8s yaml manifests 53 | 54 | ``` 55 | $ mortar fire [options]  56 | ``` 57 | 58 | ### Removing a deployment 59 | 60 | ``` 61 | $ mortar yank [options] 62 | ``` 63 | 64 | ### Listing all shots 65 | 66 | ``` 67 | $ mortar list [options] 68 | ``` 69 | 70 | ### Describing a shot 71 | 72 | ``` 73 | $ mortar describe [options] 74 | ``` 75 | 76 | ### Docker image 77 | 78 | You can use mortar in CI/CD pipelines (like Drone) via `quay.io/kontena/mortar:latest` image. 79 | 80 | Example config for Drone: 81 | 82 | ```yaml 83 | pipeline: 84 | deploy: 85 | image: quay.io/kontena/mortar:latest 86 | secrets: [ kube_token, kube_ca, kube_server ] 87 | commands: 88 | - mortar fire k8s/ my-app 89 | 90 | ``` 91 | 92 | ## Namespaces 93 | 94 | **Namespace is mandatory to be set on the resources** 95 | 96 | Currently Mortar will not add any default namespaces into the resources it shoots. Therefore it is mandatory for the user to set the namespaces in all namespaced resources shot with Mortar. See [this](https://github.com/kontena/mortar/issues/10) issue for details and track the fix. 97 | 98 | ## Shots 99 | 100 | Mortar manages a set of resources as a single unit, we call them *shots*. A shot can have as many resources as your application needs, there's no limit to that. Much like you'd do with `kubectl apply -f my_dir/`, but Mortar actually injects information into the resources it shoots into your Kubernetes cluster. This added information, labels and annotations, will be used later on by Mortar itself or can be used with `kubectl` too. This allows the management of many resources as a single application. 101 | 102 | Most importantly, Mortar is able to use this information when re-shooting your applications. One of the most difficult parts when using plain `kubectl apply ...` approach is the fact that it's super easy to leave behind some lingering resources. Say you have some `deployments` and a `service` in your application, each defined in their own `yaml` file. Now you remove the service and re-apply with `kubectl apply -f my_resources/`. The service will live on in your cluster. With Mortar, you don't have to worry. With the extra labels and annotations Mortar injects into the resources, it's also able to automatically prune the "un-necessary" resources from the cluster. The automatic pruning is done with `--prune` option. 103 | 104 | See basic example [here](/examples/basic). 105 | 106 | ## Overlays 107 | 108 | One of the most powerful features of Mortar is it's ability to support *overlays*. An overlay is a variant of the set of resources you are managing. A variant might be for example the same application running on many different environments like production, test, QA an so on. A variant might also be a separate application "instance" for each customer. Or what ever the need is. Overlays in Mortar are inspired by [kustomize](https://github.com/kubernetes-sigs/kustomize). 109 | 110 | Given a folder & file structure like: 111 | ``` 112 | echoservice-metallb/ 113 | ├── echo-metal.yml 114 | ├── foo 115 | │   └── pod.yml.erb 116 | └── prod 117 | ├── pod.yml 118 | └── svc.yml 119 | ``` 120 | 121 | where overlays (`prod` & `foo`) contain same resources as the base folder, mortar now merges all resources together. Merging is done in the order overlays are given in the command. Resources are considered to be the same resource if all of these match: `kind`, `apiVersion`, `metadata.name` and `metadata.namespace`. 122 | 123 | If there are new resources in the overlay dirs, they are taken into the shot as-is. 124 | 125 | You'd select overlays taken into processing with `--overlay option`. 126 | 127 | **Note:** Overlays are taken in in the order defined, so make sure you define them in correct order. 128 | 129 | The resources in the overlays do not have to be complete, it's enough that the "identifying" fields are the same. 130 | 131 | See example of overlays [here](/examples/overlays). 132 | 133 | ## Templating 134 | 135 | Mortar also support templating for the resource definitons. The templating language used is [ERB](https://en.wikipedia.org/wiki/ERuby). It's pretty simple templating language but yet powerful enough for Kubernetes resource templating. 136 | 137 | **Note:** Mortar will process the resource definitions as ERB even if the filename does not have the `.erb` extension. This means that Ruby code in an innocent looking `.yml` file will be evaluated using the current user's access privileges on the local machine. Running untrusted code is dangerous and so is deploying untrusted manifests, make sure you know what you're deploying. 138 | 139 | ### Variables 140 | 141 | There are two ways to introduce variables into the templating. 142 | 143 | See examples at [examples/templates](examples/templates). 144 | 145 | #### Environment variables 146 | 147 | As for any process, environment variables are also available for Mortar during template processing. 148 | 149 | ```yaml 150 | kind: Pod 151 | apiVersion: v1 152 | metadata: 153 | name: nginx 154 | labels: 155 | name: nginx 156 | namespace: default 157 | spec: 158 | containers: 159 | - name: nginx 160 | image: nginx:<%= ENV["NGINX_VERSION"] || "latest" %> 161 | ports: 162 | - containerPort: 80 163 | ``` 164 | 165 | #### Variables via options 166 | 167 | Another option to use variables is via command-line options. Use `mortar --var foo=bar my-app resources/`. 168 | 169 | Each of the variables defined will be available in the template via `var.`. 170 | 171 | ```yaml 172 | kind: Pod 173 | apiVersion: v1 174 | metadata: 175 | name: nginx 176 | labels: 177 | name: nginx 178 | namespace: default 179 | spec: 180 | containers: 181 | - name: nginx 182 | image: nginx:latest 183 | ports: 184 | - containerPort: <%= port.number %> 185 | name: <%= port.name %> 186 | ``` 187 | 188 | You could shoot this resource with `mortar --var port.name=some-port --var port.number=80 my-app resources/pod.yml.erb` 189 | 190 | ### Shot configuration file 191 | 192 | It is also possible to pass [variables](#variables), [overlays](#overlays) and [labels](#labels) through a configuration file. As your templates complexity and the amount of variables used grows, it might be easier to manage the variables with an yaml configuration file. The config file has the following syntax: 193 | 194 | ```yaml 195 | variables: 196 | ports: 197 | - name: http 198 | number: 80 199 | - name: https 200 | number: 443 201 | overlays: 202 | - foo 203 | - bar 204 | ``` 205 | 206 | `variables`, `overlays` and `labels` are optional. 207 | 208 | For variables the hash is translated into a `RecursiveOpenStruct` object. What that means is that you can access each element with dotted path notation, just like the vars given through `--var` option. And of course arrays can be looped etc.. Check examples folder how to use variables effectively. 209 | 210 | The configuration file can be given using `-c` option to `mortar fire` command. By default Mortar will look for `shot.yml` or `shot.yaml` files present in current working directory. 211 | 212 | ### Labels 213 | 214 | It's possible to set global labels for all resources in a shot via options or configuration file. 215 | 216 | #### Labels via options 217 | 218 | Use `mortar --label foo=bar my-app resource` to set label to all resources in a shot. 219 | 220 | #### Labels via configuration file 221 | 222 | ```yaml 223 | labels: 224 | foo: bar 225 | bar: baz 226 | ``` 227 | 228 | ## Contributing 229 | 230 | Bug reports and pull requests are welcome on GitHub at https://github.com/kontena/mortar. 231 | 232 | ## License 233 | 234 | Copyright (c) 2018 Kontena, Inc. 235 | 236 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 237 | 238 | http://www.apache.org/licenses/LICENSE-2.0 239 | 240 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 241 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "rspec/core/rake_task" 5 | 6 | RSpec::Core::RakeTask.new(:spec) 7 | 8 | task default: :spec 9 | -------------------------------------------------------------------------------- /bin/mortar: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # add lib to libpath (only needed when running from the sources) 5 | require 'pathname' 6 | lib_path = File.expand_path('../../lib', Pathname.new(__FILE__).realpath) 7 | $LOAD_PATH.unshift lib_path unless $LOAD_PATH.include?(lib_path) 8 | 9 | require 'mortar' 10 | $0 = 'mortar' 11 | $stdout.sync = true 12 | 13 | Mortar::RootCommand.run 14 | -------------------------------------------------------------------------------- /build/drone/create_release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ue 4 | 5 | apt-get update -y 6 | apt-get install -y -q curl bzip2 7 | 8 | # ship to github 9 | curl -sL https://github.com/aktau/github-release/releases/download/v0.7.2/linux-amd64-github-release.tar.bz2 | tar -xjO > /usr/local/bin/github-release 10 | chmod +x /usr/local/bin/github-release 11 | 12 | if [[ $DRONE_TAG =~ .+-.+ ]]; then 13 | /usr/local/bin/github-release release \ 14 | --user kontena \ 15 | --repo mortar \ 16 | --tag $DRONE_TAG \ 17 | --name $DRONE_TAG \ 18 | --description "Pre-release, only for testing" \ 19 | --draft \ 20 | --pre-release 21 | else 22 | /usr/local/bin/github-release release \ 23 | --user kontena \ 24 | --repo mortar \ 25 | --draft \ 26 | --tag $DRONE_TAG \ 27 | --name $DRONE_TAG 28 | fi -------------------------------------------------------------------------------- /build/drone/ubuntu_xenial.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ue 4 | 5 | # build binary 6 | apt-get update -y 7 | apt-get install -y -q squashfs-tools build-essential ruby bison ruby-dev git-core texinfo curl 8 | curl -sL https://github.com/kontena/ruby-packer/releases/download/0.5.0%2Bextra7/rubyc-0.5.0+extra7-linux-amd64.gz | gunzip > /usr/local/bin/rubyc 9 | chmod +x /usr/local/bin/rubyc 10 | gem install bundler 11 | version=${DRONE_TAG#"v"} 12 | package="mortar-linux-amd64-${version}" 13 | mkdir -p /root/mortar-build.tmp 14 | rubyc -o $package -d /root/mortar-build.tmp mortar 15 | rm -rf /root/mortar-build.tmp 16 | ./$package --version 17 | 18 | # ship to github 19 | curl -sL https://github.com/aktau/github-release/releases/download/v0.7.2/linux-amd64-github-release.tar.bz2 | tar -xjO > /usr/local/bin/github-release 20 | chmod +x /usr/local/bin/github-release 21 | /usr/local/bin/github-release upload \ 22 | --user kontena \ 23 | --repo mortar \ 24 | --tag $DRONE_TAG \ 25 | --name $package \ 26 | --file ./$package 27 | -------------------------------------------------------------------------------- /build/travis/macos.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ue 4 | 5 | brew install squashfs 6 | curl -sL https://github.com/kontena/ruby-packer/releases/download/0.5.0%2Bextra7/rubyc-0.5.0+extra7-osx-amd64.gz | gunzip > /usr/local/bin/rubyc 7 | chmod +x /usr/local/bin/rubyc 8 | version=${TRAVIS_TAG#"v"} 9 | package="mortar-darwin-amd64-${version}" 10 | rubyc -o $package mortar 11 | ./$package --version 12 | 13 | # ship to github 14 | curl -sL https://github.com/aktau/github-release/releases/download/v0.7.2/darwin-amd64-github-release.tar.bz2 | tar -xjO > /usr/local/bin/github-release 15 | chmod +x /usr/local/bin/github-release 16 | /usr/local/bin/github-release upload \ 17 | --user kontena \ 18 | --repo mortar \ 19 | --tag $TRAVIS_TAG \ 20 | --name $package \ 21 | --file ./$package 22 | 23 | mkdir -p upload 24 | mv $package upload/ 25 | -------------------------------------------------------------------------------- /examples/basic/deployment.yml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: myapp 5 | namespace: default 6 | spec: 7 | selector: 8 | matchLabels: 9 | app: myapp 10 | template: 11 | metadata: 12 | labels: 13 | app: myapp 14 | spec: 15 | containers: 16 | - name: myapp 17 | image: nginx:latest 18 | ports: 19 | - containerPort: 80 20 | -------------------------------------------------------------------------------- /examples/basic/service.yml: -------------------------------------------------------------------------------- 1 | kind: Service 2 | apiVersion: v1 3 | metadata: 4 | name: myapp 5 | namespace: default 6 | spec: 7 | selector: 8 | app: myapp 9 | ports: 10 | - port: 80 11 | targetPort: 80 12 | -------------------------------------------------------------------------------- /examples/config/config.yaml: -------------------------------------------------------------------------------- 1 | variables: 2 | ports: 3 | - name: http 4 | number: 80 5 | - name: https 6 | number: 443 7 | -------------------------------------------------------------------------------- /examples/config/pod.yml.erb: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: nginx 5 | labels: 6 | name: nginx 7 | namespace: default 8 | spec: 9 | containers: 10 | - name: nginx 11 | image: nginx:latest 12 | ports: 13 | <% var.ports.each { |port| %> 14 | - containerPort: <%= port.number %> 15 | name: <%= port.name %> 16 | <% } %> 17 | -------------------------------------------------------------------------------- /examples/config/shot.yaml: -------------------------------------------------------------------------------- 1 | variables: 2 | ports: 3 | - name: http 4 | number: 80 5 | - name: https 6 | number: 443 7 | -------------------------------------------------------------------------------- /examples/force-deployment/deployment.yml.erb: -------------------------------------------------------------------------------- 1 | # An dynamic annotation can be used to force Kubernetes to deploy pods. 2 | # In this example mortar will set DRONE_BUILD_NUMBER environment variable as a value of 'build' annotation. 3 | # Basically annotation can be, for example, datetime, commit sha or any unique value 4 | apiVersion: apps/v1 5 | kind: Deployment 6 | metadata: 7 | name: nginx 8 | namespace: default 9 | labels: 10 | app: nginx 11 | spec: 12 | selector: 13 | matchLabels: 14 | app: nginx 15 | strategy: 16 | template: 17 | metadata: 18 | labels: 19 | app: nginx 20 | annotations: 21 | build: "<%= ENV['DRONE_BUILD_NUMBER'] %>" 22 | spec: 23 | containers: 24 | - image: docker.io/nginx:alpine 25 | imagePullPolicy: Always 26 | name: nginx 27 | ports: 28 | - containerPort: 80 -------------------------------------------------------------------------------- /examples/overlays/echo-metal.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: extensions/v1beta1 3 | kind: Deployment 4 | metadata: 5 | name: echoserver 6 | namespace: default 7 | spec: 8 | replicas: 1 9 | template: 10 | metadata: 11 | labels: 12 | app: echoserver 13 | spec: 14 | containers: 15 | - image: gcr.io/google_containers/echoserver:1.0 16 | imagePullPolicy: Always 17 | name: echoserver 18 | ports: 19 | - containerPort: 8080 20 | --- 21 | apiVersion: v1 22 | kind: Service 23 | metadata: 24 | name: echoserver 25 | namespace: default 26 | annotations: 27 | metallb.universe.tf/address-pool: default 28 | spec: 29 | type: LoadBalancer 30 | ports: 31 | - port: 80 32 | targetPort: 8080 33 | protocol: TCP 34 | selector: 35 | app: echoserver -------------------------------------------------------------------------------- /examples/overlays/foo/pod.yml.erb: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: myapp 5 | labels: 6 | name: myapp 7 | foo: <%= var.foo.bar %> 8 | spec: 9 | containers: 10 | - name: myapp 11 | image: foobar 12 | ports: 13 | - containerPort: 8080 14 | 15 | -------------------------------------------------------------------------------- /examples/overlays/partial/echo.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: extensions/v1beta1 3 | kind: Deployment 4 | metadata: 5 | name: echoserver 6 | namespace: default 7 | labels: 8 | partial: works too :) -------------------------------------------------------------------------------- /examples/overlays/prod/pod.yml: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: myapp 5 | labels: 6 | name: myapp 7 | spec: 8 | containers: 9 | - name: myapp 10 | image: foobar 11 | ports: 12 | - containerPort: 8080 13 | 14 | -------------------------------------------------------------------------------- /examples/overlays/prod/svc.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: echoserver 5 | annotations: 6 | environment: production 7 | spec: 8 | type: LoadBalancer 9 | ports: 10 | - port: 80 11 | targetPort: 8080 12 | protocol: TCP 13 | selector: 14 | app: echoserver -------------------------------------------------------------------------------- /examples/templates/env_vars/pod.yml.erb: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: nginx 5 | labels: 6 | name: nginx 7 | namespace: default 8 | spec: 9 | containers: 10 | - name: nginx 11 | image: nginx:<%= ENV["NGINX_VERSION"] || "latest" %> 12 | ports: 13 | - containerPort: 80 14 | -------------------------------------------------------------------------------- /examples/templates/variables/loops.yml.erb: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: nginx 5 | labels: 6 | name: nginx 7 | namespace: default 8 | spec: 9 | containers: 10 | - name: nginx 11 | image: nginx:latest 12 | ports: 13 | <%# Easy to loop through some variables with the dotted notation 14 | # Run this with example mortar --var port.one=80 --var port.two=8080 15 | %> 16 | <% var.port.each do |name, number| %> 17 | - containerPort: <%= number %> 18 | name: <%= name %> 19 | <% end %> 20 | -------------------------------------------------------------------------------- /examples/templates/variables/pod-vars.yml.erb: -------------------------------------------------------------------------------- 1 | kind: Pod 2 | apiVersion: v1 3 | metadata: 4 | name: nginx 5 | labels: 6 | name: nginx 7 | namespace: default 8 | spec: 9 | containers: 10 | - name: nginx 11 | image: nginx:latest 12 | ports: 13 | <%# Variables can be accessed by the name easily %> 14 | - containerPort: <%= var.port.number %> 15 | name: <%= var.port.name %> 16 | -------------------------------------------------------------------------------- /kontena-mortar.gemspec: -------------------------------------------------------------------------------- 1 | 2 | lib = File.expand_path("../lib", __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require "mortar/version" 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "kontena-mortar" 8 | spec.version = Mortar::VERSION 9 | spec.authors = ["Kontena, Inc"] 10 | spec.email = ["info@kontena.io"] 11 | 12 | spec.summary = "Kubernetes manifest shooter" 13 | spec.description = "Kubernetes manifest shooter" 14 | spec.homepage = "https://github.com/kontena/mortar" 15 | spec.license = "Apache-2.0" 16 | 17 | # Specify which files should be added to the gem when it is released. 18 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 19 | spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do 20 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 21 | end 22 | spec.bindir = "bin" 23 | spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } 24 | spec.require_paths = ["lib"] 25 | 26 | spec.post_install_message = "To install shell auto-completions, use:\n mortar install-completions" 27 | 28 | spec.add_runtime_dependency "clamp", "~> 1.3" 29 | spec.add_runtime_dependency "k8s-client", "~> 0.10.4" 30 | spec.add_runtime_dependency "rouge", "~> 3.2" 31 | spec.add_runtime_dependency "deep_merge", "~> 1.2" 32 | spec.add_runtime_dependency "pastel", "~> 0.7.2" 33 | spec.add_runtime_dependency "tty-table", "~> 0.10.0" 34 | spec.add_development_dependency "bundler", "~> 2.0.0" 35 | spec.add_development_dependency "rake", "~> 10.0" 36 | spec.add_development_dependency "rspec", "~> 3.0" 37 | spec.add_development_dependency "rubocop", "~> 0.57" 38 | end 39 | 40 | -------------------------------------------------------------------------------- /kontena-mortar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kontena/mortar/3f85f19340d73b84330487c0f90008caaf289c81/kontena-mortar.png -------------------------------------------------------------------------------- /lib/extensions/recursive_open_struct/each.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Extensions 4 | module RecursiveOpenStruct 5 | module Each 6 | def each 7 | to_h.each { |k, v| yield k.to_s, v } 8 | end 9 | end 10 | end 11 | end 12 | 13 | # Monkey-patch the above module into RecursiveOpenStruct 14 | RecursiveOpenStruct.include Extensions::RecursiveOpenStruct::Each 15 | -------------------------------------------------------------------------------- /lib/mortar.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "clamp" 4 | require "deep_merge" 5 | require "mortar/version" 6 | require "mortar/root_command" 7 | require "mortar/config" 8 | 9 | autoload :K8s, "k8s-client" 10 | autoload :YAML, "yaml" 11 | autoload :ERB, "erb" 12 | autoload :Rouge, "rouge" 13 | autoload :RecursiveOpenStruct, "recursive-open-struct" 14 | autoload :Pastel, "pastel" 15 | autoload :Pathname, "pathname" 16 | autoload :FileUtils, "fileutils" 17 | 18 | module TTY 19 | autoload :Table, 'tty-table' 20 | end 21 | 22 | require "extensions/recursive_open_struct/each" 23 | 24 | module Mortar 25 | end 26 | -------------------------------------------------------------------------------- /lib/mortar/command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "clamp" 4 | 5 | module Mortar 6 | class Command < Clamp::Command 7 | LABEL = 'mortar.kontena.io/shot' 8 | CHECKSUM_ANNOTATION = 'mortar.kontena.io/shot-checksum' 9 | 10 | option ["-d", "--debug"], :flag, "debug" 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /lib/mortar/config.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | class Config 5 | class ConfigError < StandardError; end 6 | 7 | def self.load(path) 8 | cfg = YAML.safe_load(File.read(path)) 9 | 10 | raise ConfigError, "Failed to load config, check config file syntax" unless cfg.is_a? Hash 11 | raise ConfigError, "Failed to load config, overlays needs to be an array" if cfg.key?('overlays') && !cfg['overlays'].is_a?(Array) 12 | 13 | if cfg.key?('labels') 14 | raise ConfigError, "Failed to load config, labels needs to be a hash" if !cfg['labels'].is_a?(Hash) 15 | raise ConfigError, "Failed to load config, label values need to be strings" if cfg['labels'].values.any? { |value| !value.is_a?(String) } 16 | end 17 | 18 | new( 19 | variables: cfg['variables'] || {}, 20 | overlays: cfg['overlays'] || [], 21 | labels: cfg['labels'] || {} 22 | ) 23 | end 24 | 25 | def initialize(variables: {}, overlays: [], labels: {}) 26 | @variables = variables 27 | @overlays = overlays 28 | @labels = labels 29 | end 30 | 31 | # @param other [Hash] 32 | # @return [RecursiveOpenStruct] 33 | def variables(other = {}) 34 | hash = @variables.dup 35 | hash.deep_merge!(other) 36 | RecursiveOpenStruct.new(hash, recurse_over_arrays: true) 37 | end 38 | 39 | # @param other [Array] 40 | # @return [Array] 41 | def overlays(other = []) 42 | return @overlays unless other 43 | 44 | (@overlays + other).uniq.compact 45 | end 46 | 47 | # @param other [Hash] 48 | # @return [RecursiveOpenStruct] 49 | def labels(other = {}) 50 | hash = @labels.dup 51 | hash.merge!(other) 52 | RecursiveOpenStruct.new(hash, preserve_original_keys: true) 53 | end 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /lib/mortar/describe_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "command" 4 | require_relative "mixins/client_helper" 5 | require_relative "mixins/tty_helper" 6 | 7 | module Mortar 8 | class DescribeCommand < Mortar::Command 9 | include Mortar::ClientHelper 10 | include Mortar::TTYHelper 11 | include Mortar::ResourceHelper 12 | 13 | parameter "NAME", "deployment name" 14 | 15 | option ["-o", "--output"], "OUTPUT", "Output format", default: 'table' 16 | 17 | def execute 18 | resources = client.list_resources(labelSelector: { LABEL => name }).select{ |r| 19 | r.metadata.labels&.dig(LABEL) == name 20 | }.uniq{ |r| 21 | # Kube api returns same object from many api versions... 22 | "#{r.kind}/#{r.metadata.name}/#{r.metadata.namespace}" 23 | }.sort{ |a, b| # Sort resources so that non namespaced objects are outputted firts 24 | if a.metadata.namespace == b.metadata.namespace 25 | 1 26 | elsif a.metadata.namespace.nil? && !b.metadata.namespace.nil? 27 | -1 28 | else 29 | 0 30 | end 31 | } 32 | 33 | case output 34 | when 'table' 35 | table(resources) 36 | when 'yaml' 37 | puts resources_output(resources) 38 | when 'json' 39 | puts json_output(resources) 40 | else 41 | signal_usage_error "Unknown output format: #{output}" 42 | end 43 | end 44 | 45 | def table(resources) 46 | table = TTY::Table.new %w(NAMESPACE KIND NAME), [] 47 | resources.each do |r| 48 | table << [r.metadata.namespace || '', r.kind, r.metadata.name] 49 | end 50 | puts table.render(:basic) 51 | end 52 | 53 | def json_output(resources) 54 | json = JSON.pretty_generate(resources.map(&:to_hash)) 55 | return json unless $stdout.tty? 56 | 57 | lexer = Rouge::Lexers::JSON.new 58 | rouge = Rouge::Formatters::Terminal256.new(Rouge::Themes::Github.new) 59 | rouge.format(lexer.lex(json)) 60 | end 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /lib/mortar/fire_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "base64" 4 | require_relative "command" 5 | require_relative "yaml_file" 6 | require_relative "mixins/resource_helper" 7 | require_relative "mixins/client_helper" 8 | require_relative "mixins/tty_helper" 9 | 10 | module Mortar 11 | class FireCommand < Mortar::Command 12 | include Mortar::ResourceHelper 13 | include Mortar::ClientHelper 14 | include Mortar::TTYHelper 15 | 16 | parameter "SRC", "source file or directory" 17 | parameter "NAME", "deployment name" 18 | 19 | option ["--var"], "VAR", "set template variables", multivalued: true 20 | option ["--label"], "LABEL", "extra labels that are set to all resources", multivalued: true 21 | option ["--output"], :flag, "only output generated yaml" 22 | option ["--[no-]prune"], :flag, "automatically delete removed resources", default: true 23 | option ["--overlay"], "OVERLAY", "overlay dirs", multivalued: true 24 | option ["-c", "--config"], "CONFIG", "variable and overlay configuration file" 25 | 26 | def default_config 27 | %w{shot.yml shot.yaml}.find { |path| 28 | File.readable?(path) 29 | } 30 | end 31 | 32 | def load_config 33 | if config 34 | signal_usage_error("Cannot read config file from #{path}") unless File.readable?(config) 35 | 36 | @configuration = Config.load(config) 37 | else 38 | # No config provided nor the default config file present 39 | @configuration = Config.new(variables: {}, overlays: []) 40 | end 41 | end 42 | 43 | def execute 44 | signal_usage_error("#{src} does not exist") unless File.exist?(src) 45 | 46 | load_config 47 | 48 | resources = process_overlays 49 | resources = inject_extra_labels(resources, process_extra_labels) 50 | 51 | if output? 52 | puts resources_output(resources) 53 | exit 54 | end 55 | 56 | if resources.empty? 57 | warn 'nothing to do!' 58 | exit 59 | end 60 | 61 | K8s::Stack.new( 62 | name, resources, 63 | debug: debug?, 64 | label: LABEL, 65 | checksum_annotation: CHECKSUM_ANNOTATION 66 | ).apply(client, prune: prune?) 67 | 68 | puts "shot '#{pastel.cyan(name)}' successfully!" if $stdout.tty? 69 | end 70 | 71 | def process_overlays 72 | # Reject any resource that do not have kind set 73 | # Basically means the config or other random yml files found 74 | resources = load_resources(src).reject { |r| r.kind.nil? } 75 | @configuration.overlays(overlay_list).each do |overlay| 76 | overlay_resources = from_files(overlay) 77 | overlay_resources.each do |overlay_resource| 78 | match = false 79 | resources = resources.map { |r| 80 | if same_resource?(r, overlay_resource) 81 | match = true 82 | r.merge(overlay_resource.to_hash) 83 | else 84 | r 85 | end 86 | } 87 | resources << overlay_resource unless match 88 | end 89 | end 90 | 91 | resources 92 | end 93 | 94 | # @return [Hash] 95 | def extra_labels 96 | return @extra_labels if @extra_labels 97 | 98 | @extra_labels = {} 99 | label_list.each do |label| 100 | key, value = label.split('=') 101 | @extra_labels[key] = value 102 | end 103 | 104 | @extra_labels 105 | end 106 | 107 | # @return [Hash] 108 | def process_extra_labels 109 | @configuration.labels(extra_labels) 110 | end 111 | 112 | # @param resources [Array] 113 | # @param labels [Hash] 114 | # @return [Array] 115 | def inject_extra_labels(resources, labels) 116 | resources.map { |resource| 117 | resource.merge( 118 | metadata: { 119 | labels: labels.to_hash 120 | } 121 | ) 122 | } 123 | end 124 | 125 | # @return [RecursiveOpenStruct] 126 | def variables_struct 127 | @variables_struct ||= @configuration.variables(variables_hash) 128 | end 129 | 130 | def variables_hash 131 | set_hash = {} 132 | var_list.each do |var| 133 | k, v = var.split("=", 2) 134 | set_hash[k] = v 135 | end 136 | 137 | dotted_path_to_hash(set_hash) 138 | end 139 | 140 | def dotted_path_to_hash(hash) 141 | h = hash.map do |pkey, pvalue| 142 | pkey.to_s.split(".").reverse.inject(pvalue) do |value, key| 143 | { key.to_s => value } 144 | end 145 | end 146 | # Safer to return just empty hash instead of nil 147 | return {} if h.empty? 148 | 149 | h.inject(&:deep_merge) 150 | end 151 | end 152 | end 153 | -------------------------------------------------------------------------------- /lib/mortar/install_completions_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | class InstallCompletionsCommand < Mortar::Command 5 | include Mortar::TTYHelper 6 | 7 | DEFAULT_PATHS = [ 8 | '/etc/bash_completion.d/mortar.bash', 9 | '/usr/local/etc/bash_completion.d/mortar.bash', 10 | '/usr/share/zsh/site-functions/_mortar', 11 | '/usr/local/share/zsh/site-functions/_mortar', 12 | '/usr/local/share/zsh-completions/_mortar', 13 | File.join(Dir.home, '.bash_completion.d', 'mortar.bash') 14 | ].freeze 15 | 16 | COMPLETION_FILE_PATH = File.expand_path( 17 | '../../opt/bash-completion.sh', 18 | Pathname.new(__dir__).realpath 19 | ).freeze 20 | 21 | banner 'Installs bash/zsh auto completion script' 22 | 23 | option '--remove', :flag, 'Remove completion script from known locations' 24 | 25 | def execute 26 | return uninstall if remove? 27 | 28 | installed = [] 29 | 30 | DEFAULT_PATHS.each do |path| 31 | next unless File.directory?(File.dirname(path)) 32 | 33 | begin 34 | FileUtils.ln_sf(COMPLETION_FILE_PATH, path) 35 | installed << path 36 | rescue Errno::EACCES, Errno::EPERM 37 | nil # To keep Mr. Rubocop happy 38 | end 39 | end 40 | 41 | if installed.empty? 42 | warn "Installation failed" 43 | warn "Try with sudo or set up user bash completions in ~/.bash_completion to include files from ~/.bash_completion.d" 44 | exit 1 45 | else 46 | puts "Completions installed to:" 47 | installed.each do |path| 48 | puts " - #{path}" 49 | end 50 | puts 51 | puts "The completions will be reloaded when you start a new shell." 52 | puts "To load now, use:" 53 | puts pastel.cyan(" source \"#{COMPLETION_FILE_PATH}\"") 54 | exit 0 55 | end 56 | end 57 | 58 | def uninstall 59 | failures = false 60 | DEFAULT_PATHS.each do |path| 61 | begin 62 | if File.exist?(path) 63 | File.unlink(path) 64 | puts "Removed #{path}" 65 | end 66 | rescue Errno::EACCESS, Errno::EPERM 67 | failures = true 68 | warn "Failed to remove #{path} : permission denied" 69 | end 70 | end 71 | exit 1 unless failures 72 | end 73 | end 74 | end 75 | -------------------------------------------------------------------------------- /lib/mortar/list_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "command" 4 | require_relative "mixins/client_helper" 5 | require_relative "mixins/tty_helper" 6 | 7 | module Mortar 8 | class ListCommand < Mortar::Command 9 | include Mortar::ClientHelper 10 | include Mortar::TTYHelper 11 | 12 | option ['-q', '--quiet'], :flag, "only output shot names" 13 | 14 | def execute 15 | shots = Hash.new(0) 16 | 17 | client.list_resources(labelSelector: LABEL).select{ |r| 18 | r.metadata.labels&.dig(LABEL) 19 | }.uniq{ |r| 20 | # Kube api returns same object from many api versions... 21 | "#{r.kind}/#{r.metadata.name}/#{r.metadata.namespace}" 22 | }.each do |resource| 23 | shot_name = resource.metadata.labels&.dig(LABEL) 24 | shots[shot_name] += 1 25 | end 26 | 27 | if quiet? 28 | shots.each_key do |k| 29 | puts k 30 | end 31 | else 32 | table = TTY::Table.new %w(NAME RESOURCES), shots.to_a 33 | puts table.render(:basic) 34 | end 35 | end 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /lib/mortar/mixins/client_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | module ClientHelper 5 | # @return [K8s::Client] 6 | def client 7 | @client ||= create_client 8 | end 9 | 10 | def create_client 11 | if ENV['KUBE_TOKEN'] && ENV['KUBE_CA'] && ENV['KUBE_SERVER'] 12 | K8s::Client.new(K8s::Transport.config(build_kubeconfig_from_env)) 13 | elsif ENV['KUBECONFIG'] 14 | K8s::Client.config(K8s::Config.load_file(ENV['KUBECONFIG'])) 15 | elsif File.exist?(File.join(Dir.home, '.kube', 'config')) 16 | K8s::Client.config(K8s::Config.load_file(File.join(Dir.home, '.kube', 'config'))) 17 | else 18 | K8s::Client.in_cluster_config 19 | end 20 | end 21 | 22 | # @return [K8s::Config] 23 | def build_kubeconfig_from_env 24 | token = ENV['KUBE_TOKEN'] 25 | token = Base64.strict_decode64(token) 26 | 27 | K8s::Config.new( 28 | clusters: [ 29 | { 30 | name: 'kubernetes', 31 | cluster: { 32 | server: ENV['KUBE_SERVER'], 33 | certificate_authority_data: ENV['KUBE_CA'] 34 | } 35 | } 36 | ], 37 | users: [ 38 | { 39 | name: 'mortar', 40 | user: { 41 | token: token 42 | } 43 | } 44 | ], 45 | contexts: [ 46 | { 47 | name: 'mortar', 48 | context: { 49 | cluster: 'kubernetes', 50 | user: 'mortar' 51 | } 52 | } 53 | ], 54 | preferences: {}, 55 | current_context: 'mortar' 56 | ) 57 | rescue ArgumentError 58 | signal_usage_error "KUBE_TOKEN env doesn't seem to be base64 encoded!" 59 | end 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /lib/mortar/mixins/resource_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | module ResourceHelper 5 | # @param filename [String] file path 6 | # @return [Array] 7 | def from_files(path) 8 | Dir.glob("#{path}/*.{yml,yaml,yml.erb,yaml.erb}").sort.map { |file| 9 | from_file(file) 10 | }.flatten 11 | end 12 | 13 | # @param filename [String] file path 14 | # @return [Array] 15 | def from_file(filename) 16 | variables = { name: name, var: variables_struct } 17 | resources = YamlFile.new(filename).load(variables) 18 | resources.map { |r| K8s::Resource.new(r) } 19 | rescue Mortar::YamlFile::ParseError => e 20 | signal_usage_error e.message 21 | end 22 | 23 | def load_resources(src) 24 | File.directory?(src) ? from_files(src) : from_file(src) 25 | end 26 | 27 | # Checks if the two resource refer to the same resource. Two resources refer to same only if following match: 28 | # - namespace 29 | # - apiVersion 30 | # - kind 31 | # - name (in metadata) 32 | # @param a [K8s::Resource] 33 | # @param b [K8s::Resource] 34 | # @return [TrueClass] 35 | def same_resource?(resource_a, resource_b) 36 | resource_a.namespace == resource_b.namespace && 37 | resource_a.apiVersion == resource_b.apiVersion && 38 | resource_a.kind == resource_b.kind && 39 | resource_a.metadata[:name] == resource_b.metadata[:name] 40 | end 41 | 42 | # @param resources [Array] 43 | # @return [String] 44 | def resources_output(resources) 45 | yaml = +'' 46 | resources.each do |resource| 47 | yaml << ::YAML.dump(stringify_hash(resource.to_hash)) 48 | end 49 | return yaml unless $stdout.tty? 50 | 51 | lexer = Rouge::Lexers::YAML.new 52 | rouge = Rouge::Formatters::Terminal256.new(Rouge::Themes::Github.new) 53 | rouge.format(lexer.lex(yaml)) 54 | end 55 | 56 | # Stringifies all hash keys 57 | # @return [Hash] 58 | def stringify_hash(hash) 59 | JSON.parse(JSON.dump(hash)) 60 | end 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /lib/mortar/mixins/tty_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | module TTYHelper 5 | # @return [Pastel] 6 | def pastel 7 | @pastel ||= Pastel.new 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /lib/mortar/root_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "clamp" 4 | require_relative "fire_command" 5 | require_relative "yank_command" 6 | require_relative "describe_command" 7 | require_relative "list_command" 8 | require_relative "install_completions_command" 9 | 10 | Clamp.allow_options_after_parameters = true 11 | 12 | module Mortar 13 | class RootCommand < Clamp::Command 14 | banner "mortar - Kubernetes manifest shooter" 15 | 16 | option ['-v', '--version'], :flag, "print mortar version" do 17 | puts "mortar #{Mortar::VERSION}" 18 | exit 0 19 | end 20 | 21 | subcommand "fire", "Fire a shot (of k8s manifests)", FireCommand 22 | subcommand "yank", "Yank a shot (of k8s manifests)", YankCommand 23 | subcommand "describe", "Describe a shot (of k8s manifests)", DescribeCommand 24 | subcommand "list", "List shots (of k8s manifests)", ListCommand 25 | 26 | subcommand "install-completions", "Install shell autocompletions", InstallCompletionsCommand 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /lib/mortar/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | VERSION = "0.4.7" 5 | end 6 | -------------------------------------------------------------------------------- /lib/mortar/yaml_file.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Mortar 4 | # Reads YAML files and optionally performs ERB evaluation 5 | class YamlFile 6 | class Namespace 7 | def initialize(variables) 8 | variables.each do |key, value| 9 | singleton_class.send(:define_method, key) { value } 10 | end 11 | end 12 | 13 | def with_binding(&block) 14 | yield binding 15 | end 16 | end 17 | 18 | ParseError = Class.new(StandardError) 19 | 20 | attr_reader :content, :filename 21 | 22 | # @param input [String,IO] A IO/File object, a path to a file or string content 23 | # @param override_filename [String] use string as the filename for parse errors 24 | def initialize(input, override_filename: nil) 25 | @filename = override_filename 26 | if input.respond_to?(:read) 27 | @content = input.read 28 | @filename ||= input.respond_to?(:path) ? input.path : input.to_s 29 | else 30 | @filename ||= input.to_s 31 | @content = File.read(input) 32 | end 33 | end 34 | 35 | # @return [Array] 36 | def load(variables = {}) 37 | result = YAML.load_stream(read(variables), @filename) 38 | if result.is_a?(String) 39 | raise ParseError, "File #{"#{@filename} " if @filename}does not appear to be in YAML format" 40 | end 41 | 42 | result 43 | rescue Psych::SyntaxError => e 44 | raise ParseError, e.message 45 | end 46 | 47 | def dirname 48 | File.dirname(@filename) 49 | end 50 | 51 | def basename 52 | File.basename(@filename) 53 | end 54 | 55 | def read(variables = {}) 56 | Namespace.new(variables).with_binding do |ns_binding| 57 | ERB.new(@content, nil, '-').tap { |e| e.location = [@filename, nil] }.result(ns_binding) 58 | end 59 | rescue StandardError, ScriptError => e 60 | raise ParseError, "#{e.class.name} : #{e.message} (#{e.backtrace.first.gsub(/:in `with_binding'/, '')})" 61 | end 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /lib/mortar/yank_command.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "command" 4 | require_relative "mixins/client_helper" 5 | require_relative "mixins/tty_helper" 6 | 7 | module Mortar 8 | class YankCommand < Mortar::Command 9 | include Mortar::ClientHelper 10 | include Mortar::TTYHelper 11 | 12 | parameter "NAME", "deployment name" 13 | 14 | option ["--force"], :flag, "use force" 15 | 16 | def execute 17 | unless force? 18 | if $stdin.tty? 19 | print "enter '#{pastel.cyan(name)}' to confirm yank: " 20 | begin 21 | signal_error("confirmation did not match #{pastel.cyan(name)}.") unless $stdin.gets.chomp == name 22 | rescue Interrupt 23 | puts 24 | abort 'Canceled' 25 | end 26 | else 27 | signal_usage_error '--force required when running in a non-interactive mode' 28 | end 29 | end 30 | 31 | K8s::Stack.new( 32 | name, [], 33 | debug: debug?, 34 | label: LABEL, 35 | checksum_annotation: CHECKSUM_ANNOTATION 36 | ).prune(client, keep_resources: false) 37 | 38 | puts "yanked #{pastel.cyan(name)} successfully!" if $stdout.tty? 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /opt/bash-completion.sh: -------------------------------------------------------------------------------- 1 | if [[ -n ${ZSH_VERSION-} ]]; then 2 | autoload -U +X bashcompinit && bashcompinit 3 | fi 4 | 5 | _mortar () { 6 | local cur prev ret 7 | COMPREPLY=() 8 | cur="${COMP_WORDS[COMP_CWORD]}" 9 | prev="${COMP_WORDS[COMP_CWORD-1]}" 10 | 11 | if [ "$COMP_CWORD" = "1" ]; then 12 | if [[ ${cur} == -* ]] ; then 13 | COMPREPLY=( $(compgen -W "--help --version" -- ${cur}) ) 14 | return 15 | fi 16 | 17 | COMPREPLY=( $(compgen -W "fire yank describe list" -- ${cur}) ) 18 | return 19 | else 20 | case "${COMP_WORDS[1]}" in 21 | fire) 22 | if [[ ${cur} == -* ]] ; then 23 | COMPREPLY=( $(compgen -W "--var --output --prune --overlay --force --debug --help" -- ${cur}) ) 24 | elif [ "$prev" = "--overlay" ]; then 25 | if command -v compopt &> /dev/null; then 26 | COMPREPLY=( $(compgen -d -S "/" -- "${COMP_WORDS[COMP_CWORD]}") ) 27 | compopt -o nospace 28 | fi 29 | fi 30 | ;; 31 | yank) 32 | if [[ ${cur} == -* ]] ; then 33 | COMPREPLY=( $(compgen -W "--force --debug --help" -- ${cur}) ) 34 | fi 35 | ;; 36 | describe) 37 | if [[ ${cur} == -* ]] ; then 38 | COMPREPLY=( $(compgen -W "--output --debug --help" -- ${cur}) ) 39 | elif [ "$prev" = "--output" ]; then 40 | COMPREPLY=( $(compgen -W "table yaml json" -- ${cur}) ) 41 | fi 42 | ;; 43 | list) 44 | if [[ ${cur} == -* ]] ; then 45 | COMPREPLY=( $(compgen -W "--quiet --debug --help" -- ${cur}) ) 46 | fi 47 | ;; 48 | esac 49 | fi 50 | } 51 | 52 | complete -o default -F _mortar mortar 53 | 54 | -------------------------------------------------------------------------------- /spec/config_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe Mortar::Config do 2 | describe '#self.load' do 3 | it 'raises on empty config' do 4 | expect { 5 | described_class.load(fixture_path('config/config_empty.yaml')) 6 | }.to raise_error(Mortar::Config::ConfigError, 'Failed to load config, check config file syntax') 7 | end 8 | 9 | it 'loads vars from file' do 10 | cfg = described_class.load(fixture_path('config/config.yaml')) 11 | vars = cfg.variables 12 | expect(vars.foo).to eq('bar') 13 | expect(vars.some.deeper).to eq('variable') 14 | expect(cfg.overlays).to eq([]) 15 | expect(cfg.labels.to_h).to eq({}) 16 | end 17 | 18 | it 'loads overlays from file' do 19 | cfg = described_class.load(fixture_path('config/config_overlays.yaml')) 20 | expect(cfg.overlays).to eq(['foo', 'bar']) 21 | end 22 | 23 | it 'loads labels from file' do 24 | cfg = described_class.load(fixture_path('config/config_labels.yaml')) 25 | expect(cfg.labels.foo).to eq('bar') 26 | end 27 | 28 | it 'raises on non array overlays' do 29 | expect { 30 | described_class.load(fixture_path('config/config_overlays_error.yaml')) 31 | }.to raise_error(Mortar::Config::ConfigError, 'Failed to load config, overlays needs to be an array') 32 | end 33 | 34 | it 'raises on non hash labels' do 35 | expect { 36 | described_class.load(fixture_path('config/config_labels_error.yaml')) 37 | }.to raise_error(Mortar::Config::ConfigError, 'Failed to load config, labels needs to be a hash') 38 | end 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/fire_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe Mortar::FireCommand do 2 | 3 | describe '#variables_struct' do 4 | let(:subject) do 5 | subject = described_class.new('') 6 | subject.load_config # Load the empty config 7 | subject 8 | end 9 | 10 | it 'has each' do 11 | subject.parse(["test-shot", "/foobar", "--var", "foo=bar", "--var", "bar=baz"]) 12 | 13 | vars = subject.variables_struct 14 | keys = [] 15 | vars.each do |k,v| 16 | keys << k 17 | end 18 | expect(keys).to eq(["foo", "bar"]) 19 | end 20 | 21 | it 'has each for nested vars' do 22 | subject.parse(["test-shot", "/foobar", "--var", "port.foo=80", "--var", "port.bar=8080"]) 23 | 24 | vars = subject.variables_struct 25 | ports = [] 26 | vars.port.each do |k,v| 27 | ports << { k => v} 28 | end 29 | expect(ports).to eq([{'foo' => '80'}, { 'bar' => '8080'}]) 30 | end 31 | 32 | it 'produces proper struct even without any vars' do 33 | subject.parse(["test-shot", "/foobar", "--var", "port.foo=80", "--var", "port.bar=8080"]) 34 | 35 | vars = subject.variables_struct 36 | ports = [] 37 | vars.port.each do |k,v| 38 | ports << { k => v} 39 | end 40 | expect(ports).to eq([{'foo' => '80'}, { 'bar' => '8080'}]) 41 | end 42 | 43 | it 'overrides only given config file variable' do 44 | subject.parse(["test-shot", "/foobar", "-c", fixture_path('config/config.yaml'), "--var", "some.deeper=deep"]) 45 | subject.load_config 46 | 47 | vars = subject.variables_struct 48 | keys = [] 49 | vars.some.each do |k,v| 50 | keys << { k => v} 51 | end 52 | expect(keys).to eq([{'deeper' => 'deep'}, {'deepest' => 'variable'}]) 53 | end 54 | 55 | it 'appends config file variable' do 56 | subject.parse(["test-shot", "/foobar", "-c", fixture_path('config/config.yaml'), "--var", "some.deep=variable"]) 57 | subject.load_config 58 | 59 | vars = subject.variables_struct 60 | keys = [] 61 | vars.some.each do |k,v| 62 | keys << { k => v} 63 | end 64 | expect(keys).to eq([{'deeper' => 'variable'}, { 'deepest' => 'variable'}, { 'deep' => 'variable' }]) 65 | end 66 | end 67 | 68 | describe "#build_kubeconfig_from_env" do 69 | let(:subject) { described_class.new('') } 70 | it 'shows error in token not base64 encoded' do 71 | ENV['KUBE_TOKEN'] = 'foobar' 72 | expect(subject).to receive(:signal_usage_error).with("KUBE_TOKEN env doesn't seem to be base64 encoded!") 73 | subject.build_kubeconfig_from_env 74 | end 75 | 76 | it 'returns valid config with decoded token' do 77 | ENV['KUBE_TOKEN'] = Base64.strict_encode64('foobar') 78 | expect(subject).not_to receive(:puts) 79 | cfg = subject.build_kubeconfig_from_env 80 | expect(cfg.user.token).to eq('foobar') 81 | end 82 | 83 | end 84 | 85 | describe "#variables_hash" do 86 | it 'return empty hash with no vars' do 87 | subject = described_class.new('') 88 | subject.parse(["test-shot", "/foobar"]) 89 | expect(subject.variables_hash).to eq({}) 90 | end 91 | end 92 | 93 | describe "#extra_labels" do 94 | let(:subject) { described_class.new('') } 95 | 96 | it 'returns empty hash by default' do 97 | expect(subject.extra_labels).to eq({}) 98 | end 99 | 100 | it 'returns label has if label options are given' do 101 | subject.parse(["--label", "foo=bar", "--label", "bar=baz", "foobar", "foobar"]) 102 | expect(subject.extra_labels).to eq({ 103 | "foo" => "bar", "bar" => "baz" 104 | }) 105 | end 106 | end 107 | 108 | describe "#inject_extra_labels" do 109 | let(:subject) { described_class.new('') } 110 | let(:resources) do 111 | [ 112 | K8s::Resource.new({ 113 | metadata: { 114 | labels: { 115 | userlabel: 'test' 116 | } 117 | } 118 | }), 119 | K8s::Resource.new({ 120 | metadata: { 121 | name: 'foo' 122 | } 123 | }) 124 | ] 125 | end 126 | 127 | it 'injects labels to resources' do 128 | extra_labels = { "foo" => "bar", "bar" => "baz" } 129 | result = subject.inject_extra_labels(resources, extra_labels) 130 | expect(result.first.metadata.labels.to_h).to eq({ 131 | bar: "baz", 132 | foo: "bar", 133 | userlabel: "test" 134 | }) 135 | end 136 | end 137 | end 138 | -------------------------------------------------------------------------------- /spec/fixtures/config/config.yaml: -------------------------------------------------------------------------------- 1 | variables: 2 | foo: bar 3 | some: 4 | deeper: variable 5 | deepest: variable 6 | 7 | -------------------------------------------------------------------------------- /spec/fixtures/config/config_empty.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kontena/mortar/3f85f19340d73b84330487c0f90008caaf289c81/spec/fixtures/config/config_empty.yaml -------------------------------------------------------------------------------- /spec/fixtures/config/config_extra_keys.yaml: -------------------------------------------------------------------------------- 1 | variables: 2 | foo: bar 3 | some: 4 | deeper: variable 5 | extra: keys should be ignored 6 | -------------------------------------------------------------------------------- /spec/fixtures/config/config_labels.yaml: -------------------------------------------------------------------------------- 1 | labels: 2 | foo: bar 3 | -------------------------------------------------------------------------------- /spec/fixtures/config/config_labels_error.yaml: -------------------------------------------------------------------------------- 1 | labels: 2 | - foo=bar 3 | -------------------------------------------------------------------------------- /spec/fixtures/config/config_overlays.yaml: -------------------------------------------------------------------------------- 1 | overlays: 2 | - foo 3 | - bar 4 | 5 | -------------------------------------------------------------------------------- /spec/fixtures/config/config_overlays_error.yaml: -------------------------------------------------------------------------------- 1 | overlays: 2 | foo: bar 3 | 4 | -------------------------------------------------------------------------------- /spec/helpers/fixture_helpers.rb: -------------------------------------------------------------------------------- 1 | module FixtureHelpers 2 | FIXTURES_PATH = File.join(File.dirname(__FILE__), '../fixtures') 3 | 4 | # @return [String] file path 5 | def fixture_path(*path) 6 | File.join(FIXTURES_PATH, *path) 7 | end 8 | 9 | # @return [String] file contents 10 | def fixture(*path) 11 | File.read(fixture_path(*path)) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /spec/mortar_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe Mortar do 2 | it "has a version number" do 3 | expect(Mortar::VERSION).not_to be nil 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require "bundler/setup" 2 | require "mortar" 3 | 4 | require_relative 'helpers/fixture_helpers' 5 | 6 | RSpec.configure do |config| 7 | # Enable flags like --only-failures and --next-failure 8 | config.example_status_persistence_file_path = ".rspec_status" 9 | 10 | # Disable RSpec exposing methods globally on `Module` and `main` 11 | config.disable_monkey_patching! 12 | 13 | config.expect_with :rspec do |c| 14 | c.syntax = :expect 15 | end 16 | 17 | config.include FixtureHelpers 18 | end 19 | --------------------------------------------------------------------------------