Skip to content

Instantly share code, notes, and snippets.

@dougireton
Last active November 4, 2018 02:41
Show Gist options
  • Save dougireton/71f095a9047c2d5201de to your computer and use it in GitHub Desktop.
Save dougireton/71f095a9047c2d5201de to your computer and use it in GitHub Desktop.
Flexible knife.rb to support switching between multiple Chef orgs - ~/.chef/knife.rb
# Copyright 2015 Nordstrom, Inc.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
user_name = ENV['USER'] || ENV['USERNAME']
fail KeyError, 'The USER or USERNAME environment variable is not set.' unless user_name
user_name = user_name.downcase
user_home = ENV['USERPROFILE'] || ENV['HOME']
fail KeyError, 'The USERPROFILE or HOME environment variable is not set.' unless user_home
org = ENV['CHEF_ORG']
fail KeyError, 'You must set the CHEF_ORG environment variable to the name of your Chef org.' unless org
org = org.downcase
cookbooks_dir = ENV['CHEF_COOKBOOKS_DIR'] || File.join(user_home, 'chef', 'cookbooks')
chef_orgs_dir = ENV['CHEF_ORGS_DIR'] || File.join(user_home, 'chef', 'orgs')
current_org_dir = File.join(chef_orgs_dir, org)
org_override = File.join(current_org_dir, '.chef', 'knife_override.rb')
chef_server = ENV['CHEF_SERVER'] || 'my-chef-server.example.com'
chef_server_url "https://#{chef_server}/organizations/#{org}"
node_name user_name
client_key File.join(user_home, '.chef', "#{user_name}.pem")
# specify the location in which knife caches information about files
# that have been checked for valid Ruby syntax.
# TODO: this should probably move to %LocalAppData% on Windows
syntax_check_cache_path File.join(user_home, '.chef', 'syntax_check_cache')
# cookbook info
cookbook_path [cookbooks_dir]
cookbook_copyright 'MyCompany, Inc.'
data_bag_encrypt_version 2
# See this Berkshelf issue for why we can't call Chef::Config.from_file()
# https://github.com/berkshelf/berkshelf/issues/965
# This code is what Chef::Config.from_file() does.
if File.exists?(org_override) && File.readable?(org_override)
self.instance_eval(IO.read(org_override), org_override, 1)
end
@jf647
Copy link

jf647 commented Sep 16, 2015

Is there a place to add an override for all my orgs, for example knife[:vault_mode] = 'client' ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment