Class: Chef::Knife::RoleSync

Inherits:
Chef::Knife show all
Defined in:
lib/chef/knife/role_sync.rb

Overview

RoleSync class

Instance Method Summary collapse

Instance Method Details

#compare(role, chef_role, local_role) ⇒ Object



45
46
47
48
49
50
# File 'lib/chef/knife/role_sync.rb', line 45

def compare(role, chef_role, local_role)
  msg = "--> Checking #{role}".ljust(50)
  opts = config[:abbrev] ? {} : { array_path: true }
  diff = ::HashDiff.diff(chef_role, local_role, opts)
  diff.empty? ? show_success(msg) : show_error(msg, diff)
end

#find_role_file(role) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/chef/knife/role_sync.rb', line 52

def find_role_file(role)
  config_path = Chef::Config[:role_path]
  role_paths = config_path.is_a?(String) ? [config_path] : config_path
  role_paths.map do |path|
    path_glob =
      File.join(Chef::Util::PathHelper.escape_glob_dir(path), '**')
    path_glob << "/#{role.gsub(/[_-]/, '{-,_}')}.{json,rb}"
    Dir.glob(path_glob)
  end.flatten
end

#loaderObject



41
42
43
# File 'lib/chef/knife/role_sync.rb', line 41

def loader
  @loader ||= Knife::Core::ObjectLoader.new(Chef::Role, ui)
end

#role_from_chef(role) ⇒ Object



63
64
65
66
67
# File 'lib/chef/knife/role_sync.rb', line 63

def role_from_chef(role)
  Chef::Role.load(role).to_hash
rescue Net::HTTPServerException
  ui.error("Role '#{role}' could not be found on chef server")
end

#role_from_file(role) ⇒ Object



69
70
71
72
73
74
75
76
77
78
# File 'lib/chef/knife/role_sync.rb', line 69

def role_from_file(role)
  files = find_role_file(role)
  if files.empty?
    ui.error("Role '#{role}' could not be found on disk")
  elsif files.count > 1
    ui.error("Duplicate file role for '#{role}'")
  else
    loader.object_from_file(files.first).to_hash
  end
end

#runObject



80
81
82
83
84
85
86
87
88
89
# File 'lib/chef/knife/role_sync.rb', line 80

def run
  roles = name_args.empty? ? Chef::Role.list.keys : name_args
  roles.each do |role|
    chef_role = role_from_chef(role)
    local_role = role_from_file(role)
    next if chef_role.nil? || local_role.nil?

    compare(role, chef_role, local_role)
  end
end

#show_error(msg, diff) ⇒ Object



95
96
97
98
# File 'lib/chef/knife/role_sync.rb', line 95

def show_error(msg, diff)
  ui.info(msg + ui.color('difference(s) found', :yellow))
  pp(diff) if config[:diff]
end

#show_success(msg) ⇒ Object



91
92
93
# File 'lib/chef/knife/role_sync.rb', line 91

def show_success(msg)
  ui.info(msg + ui.color('properly synchronized.', :green))
end