├── .gitignore ├── .kitchen.yml ├── .rspec ├── .ruby-gemset ├── .travis.yml ├── CHANGELOG.md ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── gemfiles ├── Gemfile.chef.11.18.12 └── Gemfile.chef.12.16.42 ├── knife-solo_data_bag.gemspec ├── lib ├── chef │ └── knife │ │ ├── solo_data_bag_create.rb │ │ ├── solo_data_bag_edit.rb │ │ ├── solo_data_bag_helpers.rb │ │ ├── solo_data_bag_list.rb │ │ └── solo_data_bag_show.rb └── knife-solo_data_bag │ └── version.rb ├── spec ├── contexts │ ├── bag_name_not_provided.rb │ ├── bag_path_is_not_valid.rb │ ├── secret_string_and_secret_file_are_both_provided.rb │ └── stubbed_out_stdout_and_stderr.rb ├── spec_helper.rb └── unit │ ├── solo_data_bag_create_spec.rb │ ├── solo_data_bag_edit_spec.rb │ ├── solo_data_bag_list_spec.rb │ └── solo_data_bag_show_spec.rb └── test └── integration ├── bootstrap.sh └── data ├── cookbooks └── foo │ ├── metadata.rb │ └── recipes │ └── default.rb └── solo.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | .bundle 4 | .config 5 | .yardoc 6 | /gemfiles/*.lock 7 | Gemfile.lock 8 | Guardfile 9 | InstalledFiles 10 | _yardoc 11 | coverage 12 | doc/ 13 | lib/bundler/man 14 | pkg 15 | rdoc 16 | spec/reports 17 | test/tmp 18 | test/version_tmp 19 | tmp 20 | .kitchen/ 21 | .kitchen.local.yml 22 | test/integration/data/packages 23 | -------------------------------------------------------------------------------- /.kitchen.yml: -------------------------------------------------------------------------------- 1 | --- 2 | driver: 3 | name: vagrant 4 | 5 | provisioner: 6 | name: shell 7 | script: test/integration/bootstrap.sh 8 | 9 | platforms: 10 | - name: centos-6.4 11 | 12 | suites: 13 | - name: default 14 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --format progress 3 | -------------------------------------------------------------------------------- /.ruby-gemset: -------------------------------------------------------------------------------- 1 | knife-solo_data_bag 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.2.2 4 | - 2.3.0 5 | 6 | before_install: 7 | - gem install bundler 8 | 9 | gemfile: 10 | - ./gemfiles/Gemfile.chef.11.18.12 11 | - ./gemfiles/Gemfile.chef.12.16.42 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## head 2 | 3 | # 2.0.0 (10/12/2016) 4 | 5 | * Deprecate unsupported Ruby versions, 6 | * Support supported Ruby versions (2.2 and 2.3), 7 | * Update RSpec to 3.x, 8 | * Update other gems. 9 | 10 | # 1.1.0 (04/10/2014) 11 | 12 | * add ability to correct incorrect text when editing a data bag 13 | 14 | # 1.0.1 (03/06/2014) 15 | 16 | * fix loading of helpers (#18) 17 | 18 | # 1.0.0 (02/27/2014) 19 | * Only supports > chef 11.4. Use pre 1.0.0 versions for older chef support 20 | 21 | # 0.4.0 (05/30/2013) 22 | * Add support for creating a data bag item from a json file (--json-file) ([@joeyates](https://github.com/joeyates)) 23 | * Add support for specifying the data bag path on the command line (--data-bag-path) ([@ToQoz](https://github.com/ToQoz)) 24 | 25 | ## 0.3.2 (04/06/2013) 26 | * Send warning about overriding secret in knife.rb to STDERR instead of STDOUT (props to BK Box @gondoi) 27 | 28 | ## 0.3.1 (01/11/2013) 29 | * Write pretty json to disk (addresses #1) 30 | 31 | ## 0.3.0 (11/08/2012) 32 | * Add support for 'encrypted_data_bag_secret' in knife config (props to Anton Orel @skyeagle) 33 | 34 | ## 0.2.2 (08/07/2012) 35 | * Fixed an issue which prevented the create command from working in some cases (props to Florian Dütsch @der-flo) 36 | 37 | ## 0.2.1 (07/08/2012) 38 | * Fixed an issue with show command and JSON output format (props to Ziad Sawalha @ziadsawalha) 39 | 40 | ## 0.2.0 (07/01/2012) 41 | * Add support for specifying JSON content on the command line (props to BK Box @gondoi) 42 | 43 | ## 0.1.0 (05/17/2012) 44 | * Initial release 45 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in knife-solo_data_bag.gemspec 4 | gemspec 5 | 6 | gem 'test-kitchen', '~> 1.2' 7 | gem 'kitchen-vagrant' 8 | -------------------------------------------------------------------------------- /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 2012-13 Thomas Bishop 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 | # Knife Solo Data Bag 2 | 3 | A knife plugin to make working with data bags easier in a chef solo environment. 4 | 5 | If you are looking for a full featured chef solo management solution, you may 6 | want to check out [knife solo](https://github.com/matschaffer/knife-solo). 7 | 8 | ## Alternatives 9 | 10 | ### `knife data bag` 11 | 12 | The standard `chef` gem includes the knife command and 13 | [commands to manipulate data bags][knife-data-bag-docs]. 14 | 15 | `knife-solo_data_bag` has the following advantages over the `knife data bag` 16 | command: 17 | 18 | * allows recovery from errors when creating/editing JSON files, 19 | * allows import and export of the the contents in JSON format. 20 | 21 | [knife-data-bag-docs]: https://docs.chef.io/knife_data_bag.html "Knife data bag docs" 22 | 23 | ## Deprecation Notices 24 | 25 | * Versions >= 2 only support Ruby versions 2.2 and above. 26 | If you need o use an earlier Ruby version, use `knife-solo_data_bag` < 2.0.0. 27 | * Starting with 1.0.0, knife solo data bag only supports Chef versions >= 11.4.0. 28 | If you need support for an earlier version of chef, use a knife solo data bag version < 1.0.0. 29 | 30 | ## Build Status 31 | 32 | ![Build Status](https://secure.travis-ci.org/thbishop/knife-solo_data_bag.png) 33 | 34 | ## Installation 35 | ```sh 36 | gem install knife-solo_data_bag 37 | 38 | # or if using ChefDK 39 | chef gem install knife-solo_data_bag 40 | ``` 41 | ## Usage 42 | 43 | ### Setup 44 | 45 | With Chef >= 12.x, you need to indicate that you're running in local mode, 46 | otherwise Chef will try to connect to a server. 47 | 48 | In `.chef/knife.rb`, add: 49 | 50 | ```ruby 51 | local_mode true 52 | ``` 53 | 54 | ### Create 55 | 56 | Create a plain text data bag 57 | 58 | $ knife solo data bag create apps app_1 59 | 60 | Create an encrypted data bag with the provided string as the secret 61 | 62 | $ knife solo data bag create apps app_1 -s secret_key 63 | 64 | Create an encrypted data bag with the provided file content as the secret 65 | 66 | $ knife solo data bag create apps app_1 --secret-file 'SECRET_FILE' 67 | 68 | Create a data bag item with JSON from the command line (works with encryption) 69 | 70 | $ knife solo data bag create apps app_1 --json '{"id": "app_1", "username": "bob"}' 71 | 72 | Create a data bag item from a json file 73 | 74 | $ knife solo data bag create apps app_1 --json-file foo.json 75 | 76 | ### Edit 77 | 78 | Edit a plain text data bag 79 | 80 | $ knife solo data bag edit apps app_1 81 | 82 | Edit an encrypted data bag with the provided string as the secret 83 | 84 | $ knife solo data bag edit apps app_1 -s secret_key 85 | 86 | Edit an encrypted data bag with the provided file content as the secret 87 | 88 | $ knife solo data bag edit apps app_1 --secret-file 'SECRET_FILE' 89 | 90 | ### List 91 | 92 | List data bags 93 | 94 | $ knife solo data bag list 95 | 96 | ### Show 97 | 98 | Show the plain text content of a data bag (if this is an encrypted data bag, it will return the encrypted data) 99 | 100 | $ knife solo data bag show apps app_1 101 | 102 | Show the unencrypted content of an encrypted data bag with the provided string as the secret 103 | 104 | $ knife solo data bag show apps app_1 -s secret_key 105 | 106 | Show the unencrypted content of an encrypted data bag with the provided file content as the secret 107 | 108 | $ knife solo data bag show apps app_1 --secret-file 'SECRET_FILE' 109 | 110 | You can also display any of the above variations in JSON format with `-F json` 111 | 112 | $ knife solo data bag show apps app_1 -s secret_key -F json 113 | 114 | ### Using Data Bags in Recipes 115 | 116 | You can load your data bags inside you recipes as follows: 117 | 118 | ```ruby 119 | app_1 = Chef::EncryptedDataBagItem.load("apps", "app_1").to_hash 120 | ``` 121 | 122 | ## Notes 123 | 124 | ### Data Bag Path 125 | 126 | By default, this plugin will use the configured data_bag_path. This is 127 | defaulted to `/var/chef/data_bags` by Chef. It is possible to override this 128 | path in your Chef client config if desired. When using this plugin, it is also 129 | possible to override the path using the `--data-bag-path` argument. 130 | 131 | ### Encrypted Data Bag Secret 132 | 133 | This plugin respects the "encrypted_data_bag_secret" configuration option in 134 | knife.rb. Command line secret arguments (-s or --secret-file) will override the 135 | setting in knife.rb. 136 | 137 | ## Version Support 138 | 139 | This plugin has been tested on the following: 140 | 141 | Chef: 142 | * ~> 11.8 143 | * ~> 12.16 144 | 145 | Ruby: 146 | * 2.1.8 147 | * 2.2.2 148 | * 2.3.0 149 | 150 | OS: 151 | * OSX 152 | * Linux 153 | 154 | # Development 155 | 156 | Running tests requires an indication of the Gemfile to use: 157 | 158 | ```shell 159 | export BUNDLE_GEMFILE=$PWD/gemfiles/Gemfile.chef.11.18.12 160 | bundle 161 | bundle exec rspec 162 | ``` 163 | 164 | ## Contribute 165 | 166 | * Fork the project 167 | * Make your feature addition or bug fix (with tests and docs) in a topic branch 168 | * Bonus points for not mucking with the gemspec or version 169 | * Send a pull request 170 | 171 | ## License 172 | 173 | See LICENSE for details 174 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | require "bundler/gem_tasks" 3 | 4 | require 'rspec/core/rake_task' 5 | 6 | task :default => [:spec] 7 | 8 | desc 'Run specs' 9 | RSpec::Core::RakeTask.new do |t| 10 | t.rspec_opts = %w(--format documentation --color) 11 | end 12 | 13 | begin 14 | require 'kitchen/rake_tasks' 15 | Kitchen::RakeTasks.new 16 | rescue LoadError 17 | puts ">>>>> Kitchen gem not loaded, omitting tasks" unless ENV['CI'] 18 | end 19 | -------------------------------------------------------------------------------- /gemfiles/Gemfile.chef.11.18.12: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'chef', '11.18.12' 4 | 5 | gemspec :path => "../" 6 | -------------------------------------------------------------------------------- /gemfiles/Gemfile.chef.12.16.42: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'chef', '12.16.42' 4 | 5 | gemspec :path => "../" 6 | -------------------------------------------------------------------------------- /knife-solo_data_bag.gemspec: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | require File.expand_path('../lib/knife-solo_data_bag/version', __FILE__) 3 | 4 | Gem::Specification.new do |gem| 5 | gem.authors = ["Tommy Bishop", "Joe Yates"] 6 | gem.email = ["bishop.thomas@gmail.com", "joe.g.yates@gmail.com"] 7 | gem.description = %q{A knife plugin for working with data bags and chef solo} 8 | gem.summary = %q{A knife plugin for working with data bags and chef solo} 9 | gem.homepage = 'https://github.com/thbishop/knife-solo_data_bag' 10 | 11 | gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } 12 | gem.files = `git ls-files`.split("\n") 13 | gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") 14 | gem.name = "knife-solo_data_bag" 15 | gem.require_paths = ["lib"] 16 | gem.version = Knife::SoloDataBag::VERSION 17 | gem.add_development_dependency 'rake' 18 | gem.add_development_dependency 'rspec', '>= 3.0' 19 | gem.add_development_dependency 'fakefs' 20 | end 21 | -------------------------------------------------------------------------------- /lib/chef/knife/solo_data_bag_create.rb: -------------------------------------------------------------------------------- 1 | require 'chef/knife' 2 | 3 | class Chef 4 | class Knife 5 | 6 | class SoloDataBagCreate < Knife 7 | 8 | deps do 9 | require 'chef/data_bag' 10 | require 'fileutils' 11 | require 'chef/encrypted_data_bag_item' 12 | require 'chef/json_compat' 13 | end 14 | 15 | require 'chef/knife/solo_data_bag_helpers' 16 | include Chef::Knife::SoloDataBagHelpers 17 | 18 | banner 'knife solo data bag create BAG [ITEM] (options)' 19 | category 'solo data bag' 20 | 21 | attr_reader :bag_name, :item_name 22 | 23 | option :secret, 24 | :short => '-s SECRET', 25 | :long => '--secret SECRET', 26 | :description => 'The secret key to use to encrypt data bag item values' 27 | 28 | option :secret_file, 29 | :long => '--secret-file SECRET_FILE', 30 | :description => 'A file containing the secret key to use to encrypt data bag item values' 31 | 32 | option :json_string, 33 | :short => '-j JSON_STRING', 34 | :long => '--json JSON_STRING', 35 | :description => 'The data bag json string that can be passed at the CLI' 36 | 37 | option :json_file, 38 | :long => '--json-file JSON_FILE', 39 | :description => 'A file contining the data bag json string' 40 | 41 | option :data_bag_path, 42 | :long => '--data-bag-path DATA_BAG_PATH', 43 | :description => 'The path to data bag' 44 | 45 | def run 46 | @bag_name, @item_name = @name_args 47 | ensure_valid_arguments 48 | create_bag_directory 49 | create_bag_item if item_name 50 | end 51 | 52 | private 53 | def bag_item_content(content) 54 | return content unless should_be_encrypted? 55 | Chef::EncryptedDataBagItem.encrypt_data_bag_item content, secret_key 56 | end 57 | 58 | def create_bag_directory 59 | FileUtils.mkdir_p bag_path unless File.exists? bag_path 60 | end 61 | 62 | def create_item_object 63 | item = nil 64 | case 65 | when config[:json_string] 66 | item = Chef::DataBagItem.from_hash bag_item_content(convert_json_string) 67 | when config[:json_file] 68 | json_string = JSON.parse(File.read(config[:json_file])) 69 | item = Chef::DataBagItem.from_hash bag_item_content(json_string) 70 | else 71 | data = {'id' => item_name} 72 | pretty_name = "data_bag_item[#{item_name}]" 73 | if Gem::Version.new(Chef::VERSION) >= Gem::Version.new("12.8.1") 74 | create_object(data, pretty_name, object_class: Chef::DataBagItem) do |output| 75 | item = Chef::DataBagItem.from_hash bag_item_content(output) 76 | end 77 | else 78 | create_object(data, pretty_name) do |output| 79 | item = Chef::DataBagItem.from_hash bag_item_content(output) 80 | end 81 | end 82 | end 83 | item 84 | end 85 | 86 | def create_bag_item 87 | item = create_item_object 88 | item.data_bag bag_name 89 | persist_bag_item item 90 | end 91 | 92 | def ensure_valid_arguments 93 | validate_bag_name_provided 94 | validate_bags_path_exists 95 | validate_multiple_secrets_were_not_provided 96 | validate_json_string unless config[:json_string].nil? 97 | end 98 | 99 | end 100 | 101 | end 102 | end 103 | -------------------------------------------------------------------------------- /lib/chef/knife/solo_data_bag_edit.rb: -------------------------------------------------------------------------------- 1 | require 'tempfile' 2 | require 'chef/knife' 3 | 4 | class Chef 5 | class Knife 6 | 7 | class SoloDataBagEdit < Knife 8 | 9 | require 'chef/knife/solo_data_bag_helpers' 10 | include Chef::Knife::SoloDataBagHelpers 11 | 12 | banner 'knife solo data bag edit BAG ITEM (options)' 13 | category 'solo data bag' 14 | 15 | attr_reader :bag_name, :item_name 16 | 17 | option :secret, 18 | :short => '-s SECRET', 19 | :long => '--secret SECRET', 20 | :description => 'The secret key to use to encrypt data bag item values' 21 | 22 | option :secret_file, 23 | :long => '--secret-file SECRET_FILE', 24 | :description => 'A file containing the secret key to use to encrypt data bag item values' 25 | 26 | option :data_bag_path, 27 | :long => '--data-bag-path DATA_BAG_PATH', 28 | :description => 'The path to data bag' 29 | 30 | def run 31 | Chef::Config[:solo] = true 32 | Chef::Config[:solo_legacy_mode] = true if Gem.loaded_specs['chef'].version > Gem::Version.new('12.11.0') 33 | @bag_name, @item_name = @name_args 34 | ensure_valid_arguments 35 | edit_content 36 | end 37 | 38 | private 39 | def edit_content 40 | content = Chef::JSONCompat.to_json_pretty(existing_bag_item_content) 41 | updated_content = nil 42 | loop do 43 | unparsed = edit_text content 44 | begin 45 | updated_content = Chef::JSONCompat.from_json(unparsed) 46 | break 47 | rescue => e 48 | raise e if !is_invalid_json_error?(e) 49 | loop do 50 | ui.stdout.puts e.to_s 51 | question = "Do you want to keep editing (Y/N)? If you choose 'N', all changes will be lost" 52 | continue = ui.ask question 53 | case continue 54 | when 'Y', 'y' 55 | content = unparsed 56 | break 57 | when 'N', 'n' 58 | raise e 59 | else 60 | ui.stdout.puts 'Please answer Y or N' 61 | end 62 | end 63 | end 64 | end 65 | item = Chef::DataBagItem.from_hash format_editted_content(updated_content) 66 | item.data_bag bag_name 67 | persist_bag_item item 68 | end 69 | 70 | def edit_text(text) 71 | tf = Tempfile.new(['knife-edit', '.json']) 72 | tf.sync = true 73 | tf.puts text 74 | tf.close 75 | 76 | exit_status = Kernel.system("#{config[:editor]} #{tf.path}") 77 | raise "Please set EDITOR environment variable" if !exit_status 78 | 79 | output = File.read(tf.path) 80 | tf.unlink 81 | output 82 | end 83 | 84 | def existing_bag_item_content 85 | content = Chef::DataBagItem.load(bag_name, item_name).raw_data 86 | 87 | return content unless should_be_encrypted? 88 | Chef::EncryptedDataBagItem.new(content, secret_key).to_hash 89 | end 90 | 91 | def format_editted_content(content) 92 | return content unless should_be_encrypted? 93 | Chef::EncryptedDataBagItem.encrypt_data_bag_item content, secret_key 94 | end 95 | 96 | def ensure_valid_arguments 97 | validate_bag_name_provided 98 | validate_item_name_provided 99 | validate_bags_path_exists 100 | validate_multiple_secrets_were_not_provided 101 | end 102 | 103 | def validate_item_name_provided 104 | unless item_name 105 | show_usage 106 | ui.fatal 'You must supply a name for the item' 107 | exit 1 108 | end 109 | end 110 | 111 | def is_invalid_json_error?(exception) 112 | exception.class.to_s.end_with?("::ParseError") 113 | end 114 | 115 | end 116 | 117 | end 118 | end 119 | -------------------------------------------------------------------------------- /lib/chef/knife/solo_data_bag_helpers.rb: -------------------------------------------------------------------------------- 1 | require 'chef/knife' 2 | 3 | class Chef 4 | class Knife 5 | 6 | module SoloDataBagHelpers 7 | 8 | def bag_item_path 9 | File.expand_path File.join(bag_path, "#{item_name}.json") 10 | end 11 | 12 | def bag_path 13 | File.expand_path File.join(bags_path, bag_name) 14 | end 15 | 16 | def bags_path 17 | if config[:data_bag_path] 18 | Chef::Config[:data_bag_path] = config[:data_bag_path] 19 | end 20 | 21 | Chef::Config[:data_bag_path] 22 | end 23 | 24 | def persist_bag_item(item) 25 | File.open bag_item_path, 'w' do |f| 26 | f.write JSON.pretty_generate(item.raw_data) 27 | end 28 | end 29 | 30 | def secret_path 31 | Chef::Config[:encrypted_data_bag_secret] 32 | end 33 | 34 | def secret_key 35 | return config[:secret] if config[:secret] 36 | Chef::EncryptedDataBagItem.load_secret(config[:secret_file] || secret_path) 37 | end 38 | 39 | def should_be_encrypted? 40 | config[:secret] || config[:secret_file] || secret_path 41 | end 42 | 43 | def convert_json_string 44 | JSON.parse config[:json_string] 45 | end 46 | 47 | def validate_bag_name_provided 48 | unless bag_name 49 | show_usage 50 | ui.fatal 'You must supply a name for the data bag' 51 | exit 1 52 | end 53 | end 54 | 55 | def validate_bags_path_exists 56 | unless File.directory? bags_path 57 | raise Chef::Exceptions::InvalidDataBagPath, 58 | "Configured data bag path '#{bags_path}' is invalid" 59 | end 60 | end 61 | 62 | def validate_json_string 63 | begin 64 | JSON.parse config[:json_string], :create_additions => false 65 | rescue => error 66 | raise "Syntax error in #{config[:json_string]}: #{error.message}" 67 | end 68 | end 69 | 70 | def validate_multiple_secrets_were_not_provided 71 | if config[:secret] && config[:secret_file] 72 | show_usage 73 | ui.fatal 'Please specify either --secret or --secret-file only' 74 | exit 1 75 | elsif (config[:secret] && secret_path) || (config[:secret_file] && secret_path) 76 | ui.warn 'The encrypted_data_bag_secret option defined in knife.rb was overriden by the command line.' 77 | end 78 | end 79 | 80 | end 81 | 82 | end 83 | end 84 | -------------------------------------------------------------------------------- /lib/chef/knife/solo_data_bag_list.rb: -------------------------------------------------------------------------------- 1 | require 'chef/knife' 2 | 3 | class Chef 4 | class Knife 5 | 6 | class SoloDataBagList < Knife 7 | 8 | require 'chef/knife/solo_data_bag_helpers' 9 | include Chef::Knife::SoloDataBagHelpers 10 | 11 | banner 'knife solo data bag list (options)' 12 | category 'solo data bag' 13 | 14 | attr_reader :bag_name 15 | 16 | option :data_bag_path, 17 | :long => '--data-bag-path DATA_BAG_PATH', 18 | :description => 'The path to data bag' 19 | 20 | def run 21 | ensure_valid_arguments 22 | output format_for_display(bags) 23 | end 24 | 25 | private 26 | def bags 27 | Dir.entries(bags_path).select do |i| 28 | File.directory?(File.expand_path(File.join(bags_path, i))) && i != '.' && i != '..' 29 | end 30 | end 31 | 32 | def ensure_valid_arguments 33 | validate_bags_path_exists 34 | end 35 | 36 | end 37 | 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /lib/chef/knife/solo_data_bag_show.rb: -------------------------------------------------------------------------------- 1 | require 'chef/knife' 2 | 3 | class Chef 4 | class Knife 5 | 6 | class SoloDataBagShow < Knife 7 | 8 | require 'chef/knife/solo_data_bag_helpers' 9 | include Chef::Knife::SoloDataBagHelpers 10 | 11 | banner 'knife solo data bag show BAG [ITEM] (options)' 12 | category 'solo data bag' 13 | 14 | attr_reader :bag_name, :item_name 15 | 16 | option :secret, 17 | :short => '-s SECRET', 18 | :long => '--secret SECRET', 19 | :description => 'The secret key to use to encrypt data bag item values' 20 | 21 | option :secret_file, 22 | :long => '--secret-file SECRET_FILE', 23 | :description => 'A file containing the secret key to use to encrypt data bag item values' 24 | 25 | option :data_bag_path, 26 | :long => '--data-bag-path DATA_BAG_PATH', 27 | :description => 'The path to data bag' 28 | 29 | def run 30 | Chef::Config[:solo] = true 31 | Chef::Config[:solo_legacy_mode] = true if Gem.loaded_specs['chef'].version > Gem::Version.new('12.11.0') 32 | @bag_name, @item_name = @name_args 33 | ensure_valid_arguments 34 | display_content 35 | end 36 | 37 | private 38 | def bag_content 39 | Chef::DataBag.load bag_name 40 | end 41 | 42 | def bag_item_content 43 | if should_be_encrypted? 44 | raw = Chef::EncryptedDataBagItem.load(bag_name, item_name, secret_key) 45 | raw.to_hash 46 | else 47 | Chef::DataBagItem.load(bag_name, item_name).raw_data 48 | end 49 | end 50 | 51 | def display_content 52 | content = item_name ? bag_item_content : bag_content 53 | output format_for_display(content) 54 | end 55 | 56 | def ensure_valid_arguments 57 | validate_bag_name_provided 58 | validate_bags_path_exists 59 | validate_multiple_secrets_were_not_provided 60 | end 61 | 62 | end 63 | 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /lib/knife-solo_data_bag/version.rb: -------------------------------------------------------------------------------- 1 | module Knife 2 | module SoloDataBag 3 | VERSION = '2.1.1' 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/contexts/bag_name_not_provided.rb: -------------------------------------------------------------------------------- 1 | shared_context 'bag_name_not_provided' do 2 | context 'when a name is not supplied' do 3 | it 'should exit with an error message' do 4 | expect do 5 | @knife.run 6 | end.to raise_error(SystemExit) 7 | expect(@stdout.string).to match(/usage/i) 8 | expect(@stderr.string).to match(/name for the data bag/) 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/contexts/bag_path_is_not_valid.rb: -------------------------------------------------------------------------------- 1 | shared_context 'bag_path_is_not_valid' do |args| 2 | context 'when the data bag path is not valid' do 3 | before do 4 | allow(File). 5 | to receive(:directory?). 6 | and_call_original 7 | allow(File). 8 | to receive(:directory?). 9 | with(/data_bags/). 10 | and_return(false) 11 | @knife.name_args = ['foo'] 12 | @knife.name_args.concat Array(args) 13 | end 14 | 15 | it 'should raise an invalid data bag path exception' do 16 | expect do 17 | @knife.run 18 | end.to raise_error(Chef::Exceptions::InvalidDataBagPath) 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/contexts/secret_string_and_secret_file_are_both_provided.rb: -------------------------------------------------------------------------------- 1 | shared_context 'secret_string_and_secret_file_are_both_provided' do |args| 2 | context 'when specifying -s and --secret-file' do 3 | before do 4 | allow(File). 5 | to receive(:directory?). 6 | with(/data_bags/). 7 | and_return(true) 8 | allow(File). 9 | to receive(:directory?). 10 | and_call_original 11 | @knife.name_args = ['foo'] 12 | @knife.name_args.concat Array(args) 13 | @knife.config[:secret] = 'foobar' 14 | @knife.config[:secret_file] = 'secret.txt' 15 | end 16 | 17 | it 'should exit with an error message' do 18 | expect do 19 | @knife.run 20 | end.to raise_error(SystemExit) 21 | expect(@stdout.string).to match(/usage/i) 22 | expect(@stderr.string).to match(/either --secret or --secret-file/) 23 | end 24 | 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /spec/contexts/stubbed_out_stdout_and_stderr.rb: -------------------------------------------------------------------------------- 1 | shared_context 'stubbed_out_stdout_and_stderr' do 2 | before do 3 | @stdout = StringIO.new 4 | @stderr = StringIO.new 5 | allow(@knife.ui).to receive(:stdout) { @stdout } 6 | allow(@knife.ui).to receive(:stderr) { @stderr } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | $:.unshift File.expand_path('../../lib', __FILE__) 2 | 3 | require 'fakefs/safe' 4 | 5 | require 'chef' 6 | require 'chef/knife' 7 | require 'chef/knife/solo_data_bag_create' 8 | require 'chef/knife/solo_data_bag_edit' 9 | require 'chef/knife/solo_data_bag_list' 10 | require 'chef/knife/solo_data_bag_show' 11 | 12 | ['contexts', 'helpers', 'matchers'].each do |dir| 13 | Dir[File.expand_path(File.join(File.dirname(__FILE__),dir,'*.rb'))].each {|f| require f} 14 | end 15 | -------------------------------------------------------------------------------- /spec/unit/solo_data_bag_create_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Chef::Knife::SoloDataBagCreate do 4 | before do 5 | @knife = subject 6 | end 7 | 8 | include_context 'stubbed_out_stdout_and_stderr' 9 | 10 | describe 'run' do 11 | let(:secret_path) { '/var/chef/secret.txt' } 12 | 13 | include_context 'bag_name_not_provided' 14 | include_context 'bag_path_is_not_valid' 15 | 16 | context 'with valid arguments' do 17 | before do 18 | @bags_path = '/var/chef/data_bags' 19 | @bag_path = "#{@bags_path}/bag_1" 20 | @knife.name_args = ['bag_1'] 21 | Chef::Config[:data_bag_path] = @bags_path 22 | 23 | FakeFS.activate! 24 | FileUtils.mkdir_p @bags_path 25 | allow(Chef::EncryptedDataBagItem).to receive(:load_secret). 26 | with(secret_path). 27 | and_return('psst') 28 | end 29 | 30 | include_context 'secret_string_and_secret_file_are_both_provided' 31 | 32 | after do 33 | FakeFS.deactivate! 34 | FakeFS::FileSystem.clear 35 | end 36 | 37 | context 'if an item is not specified' do 38 | it 'should create the data bag' do 39 | @knife.run 40 | expect(File.directory?(@bags_path)).to be_truthy 41 | expect(File.directory?(@bag_path)).to be_truthy 42 | end 43 | end 44 | 45 | context 'when also specifying an item' do 46 | before do 47 | @knife.name_args << 'bar' 48 | @input_data = {'id' => 'foo', 'key_1' => 'value_1', 'key_2' => 'value_2'} 49 | @item_path = "#{@bag_path}/bar.json" 50 | allow(@knife).to receive(:create_object). 51 | and_yield(@input_data).and_return(nil) 52 | end 53 | 54 | it 'should create the data bag item' do 55 | @knife.run 56 | expect(JSON.parse(File.read(@item_path))).to eq(@input_data) 57 | end 58 | 59 | it 'should write pretty json' do 60 | @knife.run 61 | expect(File.read(@item_path)).to eq(JSON.pretty_generate(@input_data)) 62 | end 63 | 64 | context 'with --data-bag-path' do 65 | before do 66 | @override_bags_path = '/opt/bags' 67 | @override_bag_path = "#{@override_bags_path}/bag_1" 68 | @knife.config[:data_bag_path] = @override_bags_path 69 | FileUtils.mkdir_p @override_bags_path 70 | end 71 | 72 | it 'uses the data bag path from the override' do 73 | @knife.run 74 | expect(File.directory?(@override_bag_path)).to be_truthy 75 | end 76 | end 77 | 78 | context 'when encrypting with -s or --secret' do 79 | before do 80 | @knife.name_args << 'bar' 81 | @knife.config[:secret] = 'secret_key' 82 | end 83 | 84 | it 'should create the encrypted data bag item' do 85 | @knife.run 86 | content = JSON.parse(File.read(@item_path)) 87 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 88 | expect(content).to have_key(k) 89 | expect(content[k]).not_to eq(@input_data[k]) 90 | end 91 | end 92 | end 93 | 94 | context 'when encrypting with --secret-file' do 95 | 96 | before do 97 | @knife.name_args << 'bar' 98 | @knife.config[:secret_file] = secret_path 99 | end 100 | 101 | it 'should create the encrypted data bag item' do 102 | @knife.run 103 | content = JSON.parse(File.read(@item_path)) 104 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 105 | expect(content).to have_key(k) 106 | expect(content[k]).to_not eq(@input_data[k]) 107 | end 108 | end 109 | end 110 | 111 | context 'when encrypting with secret set in knife config' do 112 | before do 113 | Chef::Config[:encrypted_data_bag_secret] = secret_path 114 | end 115 | 116 | after { Chef::Config[:encrypted_data_bag_secret] = nil } 117 | 118 | it 'creates the encrypted data bag item' do 119 | @knife.run 120 | content = JSON.parse(File.read(@item_path)) 121 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 122 | expect(content).to have_key(k) 123 | expect(content[k]).to_not eq(@input_data[k]) 124 | end 125 | end 126 | 127 | end 128 | 129 | end 130 | 131 | context 'when also specifying a json string' do 132 | before do 133 | @knife.name_args << 'bar' 134 | @knife.config[:json_string] = '{"id": "foo", "sub": {"key_1": "value_1", "key_2": "value_2"}}' 135 | @input_data = {'id' => 'foo', 'sub' => {'key_1' => 'value_1', 'key_2' => 'value_2'}} 136 | @item_path = "#{@bag_path}/bar.json" 137 | end 138 | 139 | it 'should create the data bag item' do 140 | @knife.run 141 | expect(JSON.parse(File.read(@item_path))).to eq(@input_data) 142 | end 143 | 144 | context 'when encrypting with -s or --secret' do 145 | before do 146 | @knife.name_args << 'bar' 147 | @knife.config[:secret] = 'secret_key' 148 | end 149 | 150 | it 'should create the encrypted data bag item' do 151 | @knife.run 152 | content = JSON.parse(File.read(@item_path)) 153 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 154 | expect(content).to have_key(k) 155 | expect(content[k]).to_not eq(@input_data[k]) 156 | end 157 | end 158 | end 159 | 160 | context 'when encrypting with --secret-file' do 161 | before do 162 | @knife.name_args << 'bar' 163 | @knife.config[:secret_file] = secret_path 164 | end 165 | 166 | it 'should create the encrypted data bag item' do 167 | @knife.run 168 | content = JSON.parse(File.read(@item_path)) 169 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 170 | expect(content).to have_key(k) 171 | expect(content[k]).to_not eq(@input_data[k]) 172 | end 173 | end 174 | end 175 | 176 | context 'when encrypting with secret set in knife config' do 177 | before do 178 | Chef::Config[:encrypted_data_bag_secret] = secret_path 179 | end 180 | 181 | after { Chef::Config[:encrypted_data_bag_secret] = nil } 182 | 183 | it 'creates the encrypted data bag item' do 184 | @knife.run 185 | content = JSON.parse(File.read(@item_path)) 186 | @input_data.keys.reject{|i| i == 'id'}.each do |k| 187 | expect(content).to have_key(k) 188 | expect(content[k]).to_not eq(@input_data[k]) 189 | end 190 | end 191 | 192 | end 193 | end 194 | 195 | context 'when also specifying a json file' do 196 | before do 197 | @knife.name_args << 'bar' 198 | @json_path = '/var/chef/my_bag.json' 199 | @knife.config[:json_file] = @json_path 200 | @input_data = {'id' => 'foo', 'sub' => {'key_1' => 'value_1', 'key_2' => 'value_2'}} 201 | @item_path = "#{@bag_path}/bar.json" 202 | File.open(@json_path, 'w') { |f| f.write @input_data.to_json } 203 | end 204 | 205 | it 'creates the data bag item' do 206 | @knife.run 207 | expect(JSON.parse(File.read(@item_path))).to eq(@input_data) 208 | end 209 | end 210 | 211 | end 212 | 213 | end 214 | 215 | end 216 | -------------------------------------------------------------------------------- /spec/unit/solo_data_bag_edit_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | RSpec.describe Chef::Knife::SoloDataBagEdit do 4 | before do 5 | @knife = subject 6 | end 7 | 8 | include_context 'stubbed_out_stdout_and_stderr' 9 | 10 | describe 'run' do 11 | let(:bags_path) { '/var/chef/data_bags' } 12 | let(:bag_path) { "#{bags_path}/bag_1" } 13 | 14 | before do 15 | FakeFS.activate! 16 | FileUtils.mkdir_p bag_path 17 | end 18 | 19 | after do 20 | FakeFS.deactivate! 21 | FakeFS::FileSystem.clear 22 | end 23 | 24 | include_context 'bag_name_not_provided' 25 | include_context 'bag_path_is_not_valid', ['foo'] 26 | include_context 'secret_string_and_secret_file_are_both_provided', ['bar'] 27 | 28 | context 'when an item name is not provided' do 29 | before do 30 | @knife.name_args = ['bag_1'] 31 | end 32 | 33 | it 'should exit with an error message' do 34 | expect do 35 | @knife.run 36 | end.to raise_error(SystemExit) 37 | expect(@stdout.string).to match(/usage/i) 38 | expect(@stderr.string).to match(/name for the item/) 39 | end 40 | end 41 | 42 | context 'with valid arguments' do 43 | let(:tf) do 44 | double( 45 | 'Tempfile', 46 | :sync= => nil, 47 | :puts => nil, 48 | :close => nil, 49 | :path => tempfile_name, 50 | :unlink => true 51 | ) 52 | end 53 | let(:tempfile_name) { '/tmp/foo' } 54 | let(:editor) { 'vimacs' } 55 | let(:edit_command) { "#{editor} #{tempfile_name}" } 56 | 57 | before do 58 | @item_path = "#{bag_path}/foo.json" 59 | @knife.name_args = ['bag_1', 'foo'] 60 | @orig_data = {'id' => 'foo', 'who' => 'bob'} 61 | @updated_data = {'id' => 'foo', 'who' => 'sue'} 62 | @bag_item_foo = Chef::DataBagItem.from_hash @orig_data 63 | @bag_item_foo.data_bag 'bag_1' 64 | @updated_bag_item = Chef::DataBagItem.from_hash @updated_data 65 | @updated_bag_item.data_bag 'bag_1' 66 | @knife.config[:editor] = 'vimacs' 67 | 68 | allow(Chef::DataBagItem).to receive(:load). 69 | with('bag_1', 'foo'). 70 | and_return(@bag_item_foo) 71 | allow(Tempfile).to receive(:new). 72 | with(['knife-edit', '.json']). 73 | and_return(tf) 74 | allow(Kernel).to receive(:system).and_call_original 75 | allow(Kernel).to receive(:system).with(edit_command) { true } 76 | allow(File).to receive(:read).and_call_original 77 | allow(File).to receive(:read). 78 | with(tempfile_name). 79 | and_return(@updated_data.to_json) 80 | Chef::Config[:data_bag_path] = bags_path 81 | end 82 | 83 | it 'should edit the data bag item' do 84 | @knife.run 85 | expect(JSON.parse(File.read(@item_path))).to eq(@updated_data) 86 | end 87 | 88 | it 'should write pretty json' do 89 | @knife.run 90 | data = JSON.pretty_generate(:id => 'foo', :who => 'sue') 91 | expect(File.read(@item_path)).to eq(data) 92 | end 93 | 94 | context 'with --data-bag-path' do 95 | before do 96 | @override_bags_path = '/opt/bags' 97 | @override_bag_path = "#{@override_bags_path}/bag_1" 98 | @override_item_path = "#{@override_bag_path}/foo.json" 99 | @knife.config[:data_bag_path] = @override_bags_path 100 | FileUtils.mkdir_p @override_bag_path 101 | end 102 | 103 | it 'uses the data bag path from the override' do 104 | @knife.run 105 | data = JSON.parse(File.read(@override_item_path)) 106 | expect(data).to eq(@updated_data) 107 | end 108 | end 109 | 110 | context 'when encrypting with -s or --secret' do 111 | before do 112 | @knife.config[:secret] = 'secret_key' 113 | allow(Chef::EncryptedDataBagItem). 114 | to receive(:new). 115 | with(@bag_item_foo.raw_data, 'secret_key'). 116 | and_return(@updated_data) 117 | end 118 | 119 | it 'should edit the encrypted data bag item' do 120 | @knife.run 121 | content = JSON.parse(File.read(@item_path)) 122 | expect(content['who']).not_to eq(@orig_data['who']) 123 | expect(content['who']).not_to be_nil 124 | end 125 | end 126 | 127 | context 'when encrypting with --secret-file' do 128 | before do 129 | @secret_path = '/var/chef/secret.txt' 130 | @knife.config[:secret_file] = @secret_path 131 | allow(Chef::EncryptedDataBagItem).to receive(:load_secret). 132 | with(@secret_path). 133 | and_return('psst') 134 | allow(Chef::EncryptedDataBagItem). 135 | to receive(:new). 136 | with(@bag_item_foo.raw_data, 'psst'). 137 | and_return(@updated_data) 138 | end 139 | 140 | it 'should edit the encrypted data bag item' do 141 | @knife.run 142 | content = JSON.parse(File.read(@item_path)) 143 | expect(content['who']).not_to eq(@orig_data['who']) 144 | expect(content['who']).not_to be_nil 145 | end 146 | end 147 | 148 | context 'when encrypting with secret set in knife config' do 149 | before do 150 | @secret_path = '/var/chef/secret.txt' 151 | Chef::Config[:encrypted_data_bag_secret] = @secret_path 152 | allow(Chef::EncryptedDataBagItem). 153 | to receive(:load_secret). 154 | with(@secret_path). 155 | and_return('psst') 156 | allow(Chef::EncryptedDataBagItem). 157 | to receive(:new). 158 | with(@bag_item_foo.raw_data, 'psst'). 159 | and_return(@updated_data) 160 | end 161 | 162 | after { Chef::Config[:encrypted_data_bag_secret] = nil } 163 | 164 | it 'should edit the encrypted data bag item' do 165 | @knife.run 166 | content = JSON.parse(File.read(@item_path)) 167 | expect(content['who']).not_to eq(@orig_data['who']) 168 | expect(content['who']).not_to be_nil 169 | end 170 | end 171 | 172 | context 'with malformed JSON' do 173 | let(:user_wants_to_reedit) { 'Y' } 174 | let(:bad_json) { '{,badjson}' } 175 | 176 | before do 177 | @pass = 0 178 | @asked_to_continue = 0 179 | 180 | allow(File).to receive(:read).with(tempfile_name) do 181 | @pass += 1 182 | case @pass 183 | when 1 184 | '{,badjson}' 185 | else 186 | @updated_data.to_json 187 | end 188 | end 189 | 190 | allow(@knife.ui).to receive(:ask) do 191 | case @pass 192 | when 1 193 | @asked_to_continue += 1 194 | user_wants_to_reedit 195 | else 196 | nil 197 | end 198 | end 199 | end 200 | 201 | it 'asks whether to re-edit' do 202 | @knife.run 203 | expect(@asked_to_continue).to eq(1) 204 | end 205 | 206 | context 'when the user wants to re-edit' do 207 | before do 208 | allow(Kernel).to receive(:system). 209 | with(edit_command). 210 | and_return(true) 211 | end 212 | 213 | it 'the editor is re-opened' do 214 | @knife.run 215 | 216 | expect(Kernel).to have_received(:system). 217 | with(edit_command). 218 | exactly(2).times 219 | end 220 | end 221 | 222 | context "the user doesn't want to re-edit" do 223 | let(:user_wants_to_reedit) { 'N' } 224 | 225 | it 'an error is thrown' do 226 | expect do 227 | @knife.run 228 | end.to raise_error(StandardError) 229 | end 230 | end 231 | end 232 | 233 | end 234 | 235 | end 236 | 237 | end 238 | -------------------------------------------------------------------------------- /spec/unit/solo_data_bag_list_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Chef::Knife::SoloDataBagList do 4 | before do 5 | @knife = subject 6 | end 7 | 8 | include_context 'stubbed_out_stdout_and_stderr' 9 | 10 | describe 'run' do 11 | include_context 'bag_path_is_not_valid' 12 | 13 | context 'with valid arguments' do 14 | before do 15 | @bags_path = '/var/chef/data_bags' 16 | @bags = ['bag_1', 'bag_2'] 17 | 18 | FakeFS.activate! 19 | FileUtils.mkdir_p @bags_path 20 | 21 | @bags.each do |bag| 22 | FileUtils.mkdir_p "#{@bags_path}/#{bag}" 23 | end 24 | end 25 | 26 | after do 27 | FakeFS.deactivate! 28 | FakeFS::FileSystem.clear 29 | end 30 | 31 | it 'should list all of the data bags' do 32 | @knife.run 33 | expect(@stdout.string).to match(/bag_1/) 34 | expect(@stdout.string).to match(/bag_2/) 35 | end 36 | 37 | context 'with --data-bag-path' do 38 | before do 39 | @bags_path = '/opt/bags' 40 | FileUtils.mkdir_p @bags_path 41 | @bags.each { |b| FileUtils.mkdir_p "#{@bags_path}/#{b}-opt" } 42 | @knife.config[:data_bag_path] = @bags_path 43 | end 44 | 45 | it 'should list all of the data bags' do 46 | @knife.run 47 | expect(@stdout.string).to match(/bag_1-opt/) 48 | expect(@stdout.string).to match(/bag_2-opt/) 49 | end 50 | end 51 | 52 | end 53 | 54 | end 55 | 56 | end 57 | -------------------------------------------------------------------------------- /spec/unit/solo_data_bag_show_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Chef::Knife::SoloDataBagShow do 4 | before do 5 | @knife = subject 6 | end 7 | 8 | include_context 'stubbed_out_stdout_and_stderr' 9 | 10 | describe 'run' do 11 | let(:bags_path) { '/var/chef/data_bags' } 12 | let(:bag_path) { "#{bags_path}/bag_1" } 13 | 14 | before do 15 | FakeFS.activate! 16 | FileUtils.mkdir_p bag_path 17 | Chef::Config[:data_bag_path] = bags_path 18 | end 19 | 20 | after do 21 | FakeFS.deactivate! 22 | FakeFS::FileSystem.clear 23 | end 24 | 25 | include_context 'bag_name_not_provided' 26 | include_context 'bag_path_is_not_valid' 27 | include_context 'secret_string_and_secret_file_are_both_provided' 28 | 29 | context 'with valid arguments' do 30 | before do 31 | @knife.name_args = ['bag_1'] 32 | 33 | @bag_item_foo = Chef::DataBagItem.from_hash 'id' => 'foo', 'who' => 'bob' 34 | @bag_item_bar = Chef::DataBagItem.from_hash 'id' => 'bar', 'who' => 'sue' 35 | end 36 | 37 | context 'if an item is not specified' do 38 | before do 39 | bag_items = {'foo' => @bag_item_foo, 'bar' => @bag_item_bar} 40 | allow(Chef::DataBag).to receive(:load). 41 | with('bag_1'). 42 | and_return(bag_items) 43 | end 44 | 45 | it 'should show the list of items' do 46 | @knife.run 47 | expect(@stdout.string).to match(/foo/) 48 | expect(@stdout.string).to match(/bar/) 49 | end 50 | 51 | context 'with --data-bag-path' do 52 | let(:bags_path) { '/opt/bags' } 53 | 54 | before do 55 | FileUtils.mkdir_p bag_path 56 | @knife.config[:data_bag_path] = bags_path 57 | end 58 | 59 | it 'uses the data bag path from the override' do 60 | @knife.run 61 | expect(@stdout.string).to match(/foo/) 62 | expect(@stdout.string).to match(/bar/) 63 | end 64 | end 65 | 66 | end 67 | 68 | context 'when also specifying an item' do 69 | before do 70 | @knife.name_args << 'foo' 71 | end 72 | 73 | it 'should show the item' do 74 | allow(Chef::DataBagItem).to receive(:load). 75 | with('bag_1', 'foo'). 76 | and_return(@bag_item_foo) 77 | @knife.run 78 | expect(@stdout.string).to match(/id:\s+foo.+who:\s+bob/m) 79 | end 80 | 81 | context 'and with -F of json' do 82 | before do 83 | @knife.config[:format] = 'json' 84 | allow(Chef::DataBagItem).to receive(:load).with('bag_1', 'foo'). 85 | and_return(@bag_item_foo) 86 | end 87 | 88 | it 'should show the item as json' do 89 | @knife.run 90 | expect(@stdout.string).to match(/"id":\s+"foo".+"who":\s+"bob"/m) 91 | expect(@stdout.string).not_to match(/json_class/) 92 | end 93 | end 94 | 95 | context 'when encrypting with -s or --secret' do 96 | before do 97 | @knife.config[:secret] = 'SECRET' 98 | allow(Chef::EncryptedDataBagItem). 99 | to receive(:load). 100 | with('bag_1', 'foo', 'SECRET'). 101 | and_return(@bag_item_foo) 102 | end 103 | 104 | it 'should show the unencrypted item' do 105 | @knife.run 106 | expect(@stdout.string).to match(/id:\s+foo.+who:\s+bob/m) 107 | end 108 | 109 | context 'and with -F of json' do 110 | before do 111 | @knife.config[:format] = 'json' 112 | end 113 | 114 | it 'should show the unencrypted item as json' do 115 | @knife.run 116 | expect(@stdout.string).to match(/"id":\s+"foo".+"who":\s+"bob"/m) 117 | expect(@stdout.string).not_to match(/json_class/) 118 | end 119 | end 120 | end 121 | 122 | context 'when encrypting with --secret-file' do 123 | before do 124 | @knife.config[:secret_file] = '/var/tmp/secret' 125 | allow(Chef::EncryptedDataBagItem).to receive(:load_secret). 126 | with('/var/tmp/secret'). 127 | and_return('abcd') 128 | allow(Chef::EncryptedDataBagItem).to receive(:load). 129 | with('bag_1', 'foo', 'abcd'). 130 | and_return(@bag_item_foo) 131 | end 132 | 133 | it 'should show the unencrypted item' do 134 | @knife.run 135 | expect(@stdout.string).to match(/id:\s+foo.+who:\s+bob/m) 136 | end 137 | 138 | context 'and with -F of json' do 139 | before do 140 | @knife.config[:format] = 'json' 141 | end 142 | 143 | it 'should show the unencrypted item as json' do 144 | @knife.run 145 | expect(@stdout.string).to match(/"id":\s+"foo".+"who":\s+"bob"/m) 146 | expect(@stdout.string).not_to match(/json_class/) 147 | end 148 | end 149 | end 150 | 151 | context 'when encrypting with secret set in knife config' do 152 | before do 153 | @secret_path = '/var/chef/secret.txt' 154 | Chef::Config[:encrypted_data_bag_secret] = @secret_path 155 | allow(Chef::EncryptedDataBagItem).to receive(:load_secret). 156 | with(@secret_path). 157 | and_return('abcd') 158 | allow(Chef::EncryptedDataBagItem).to receive(:load). 159 | with('bag_1', 'foo', 'abcd'). 160 | and_return(@bag_item_foo) 161 | end 162 | 163 | it 'should show the unencrypted item' do 164 | @knife.run 165 | expect(@stdout.string).to match(/id:\s+foo.+who:\s+bob/m) 166 | end 167 | 168 | context 'and with -F of json' do 169 | before do 170 | @knife.config[:format] = 'json' 171 | end 172 | 173 | it 'should show the unencrypted item as json' do 174 | @knife.run 175 | expect(@stdout.string).to match(/"id":\s+"foo".+"who":\s+"bob"/m) 176 | expect(@stdout.string).not_to match(/json_class/) 177 | end 178 | end 179 | end 180 | 181 | end 182 | end 183 | 184 | end 185 | 186 | end 187 | -------------------------------------------------------------------------------- /test/integration/bootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | DATA_DIR=/tmp/kitchen/data 6 | 7 | function download_chef_version() { 8 | echo -e "Installing curl..." 9 | yum install -y curl 10 | echo "Done" 11 | 12 | echo -e "Downloading chef install script..." 13 | curl -o $DATA_DIR/chef_install.sh https://www.opscode.com/chef/install.sh 14 | chmod +x $DATA_DIR/chef_install.sh 15 | echo "Done" 16 | $DATA_DIR/chef_install.sh -v $1 17 | } 18 | 19 | for version in 11.2.0-1 11.4.4-2 11.6.2-1 11.8.2-1 11.10.0-1 11.10.2-1 11.10.4-1; do 20 | echo "##############################" 21 | echo "# Processing $version" 22 | echo "##############################" 23 | 24 | if [ ! -f $DATA_DIR/packages/chef-$version.el6.x86_64.rpm ]; then 25 | download_chef_version $version 26 | else 27 | rpm -ivh --quiet $DATA_DIR/packages/chef-$version*.rpm 28 | fi 29 | 30 | echo -e "Installing knife-solo_data_bag..." 31 | /opt/chef/embedded/bin/gem install -q $DATA_DIR/packages/*.gem --no-ri --no-rdoc 32 | echo "Done" 33 | 34 | knife solo data bag create foo bar --data-bag-path $DATA_DIR/data_bags -j '{ "id": "bar", "my": "data" }' 35 | 36 | chef-solo -c $DATA_DIR/solo.rb -o foo -l info 37 | 38 | knife solo data bag show foo bar --data-bag-path $DATA_DIR/data_bags 39 | 40 | echo -e "Cleaning up..." 41 | rpm -e --quiet chef 42 | 43 | rm -fr /opt/chef 44 | rm -fr /tmp/kitchend/data/data_bags/foo 45 | echo "Done" 46 | done 47 | 48 | exit 0 49 | -------------------------------------------------------------------------------- /test/integration/data/cookbooks/foo/metadata.rb: -------------------------------------------------------------------------------- 1 | name 'foo' 2 | version '0.1.0' 3 | -------------------------------------------------------------------------------- /test/integration/data/cookbooks/foo/recipes/default.rb: -------------------------------------------------------------------------------- 1 | item = data_bag_item('foo', 'bar') 2 | 3 | unless item['my'] == 'data' 4 | Chef::Application.fatal! "data is incorrect. item == #{item.inspect}" 5 | end 6 | -------------------------------------------------------------------------------- /test/integration/data/solo.rb: -------------------------------------------------------------------------------- 1 | cookbook_path ['/tmp/kitchen/data/cookbooks'] 2 | data_bag_path '/tmp/kitchen/data/data_bags' 3 | --------------------------------------------------------------------------------