module ChefConfig::Mixin::Credentials

Helper methods for working with credentials files.

@since 13.7 @api internal

Public Instance Methods

credentials_file_path() click to toggle source

Compute the path to the credentials file.

@since 14.4 @return [String]

# File lib/chef-config/mixin/credentials.rb, line 56
def credentials_file_path
  return Chef::Config[:credentials] if defined?(Chef::Config) && Chef::Config.key?(:credentials)

  PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "credentials").freeze
end
credentials_profile(profile = nil) click to toggle source

Compute the active credentials profile name.

The lookup order is argument (from –profile), environment variable ($CHEF_PROFILE), context file (~/.chef/context), and then “default” as a fallback.

@since 14.4 @param profile [String, nil] Optional override for the active profile,

normally set via a command-line option.

@return [String]

# File lib/chef-config/mixin/credentials.rb, line 39
def credentials_profile(profile = nil)
  context_file = PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "context").freeze
  if !profile.nil?
    profile
  elsif ENV.include?("CHEF_PROFILE")
    ENV["CHEF_PROFILE"]
  elsif File.file?(context_file)
    File.read(context_file).strip
  else
    "default"
  end
end
load_credentials(profile = nil) click to toggle source

Load and process the active credentials.

@see WorkstationConfigLoader#apply_credentials @param profile [String, nil] Optional override for the active profile,

normally set via a command-line option.

@return [void]

# File lib/chef-config/mixin/credentials.rb, line 88
def load_credentials(profile = nil)
  profile = credentials_profile(profile)
  cred_config = parse_credentials_file
  return if cred_config.nil? # No credentials, nothing to do here.

  if cred_config[profile].nil?
    # Unknown profile name. For "default" just silently ignore, otherwise
    # raise an error.
    return if profile == "default"

    raise ChefConfig::ConfigurationError, "Profile #{profile} doesn't exist. Please add it to #{credentials_file_path}."
  end
  apply_credentials(cred_config[profile], profile)
end
parse_credentials_file() click to toggle source

Load and parse the credentials file.

Returns ‘nil` if the credentials file is unavailable.

@since 14.4 @return [String, nil]

# File lib/chef-config/mixin/credentials.rb, line 68
def parse_credentials_file
  credentials_file = credentials_file_path
  return nil unless File.file?(credentials_file)

  begin
    Tomlrb.load_file(credentials_file)
  rescue => e
    # TOML's error messages are mostly rubbish, so we'll just give a generic one
    message = "Unable to parse Credentials file: #{credentials_file}\n"
    message << e.message
    raise ChefConfig::ConfigurationError, message
  end
end