Class: ChefSync

Inherits:
Object
  • Object
show all
Defined in:
lib/chef_sync.rb,
lib/chef_sync/knife.rb,
lib/chef_sync/version.rb,
lib/chef_sync/chef_component.rb

Defined Under Namespace

Classes: ChefComponent, Cookbook, DataBagItem, Environment, Knife, Role

Constant Summary collapse

RESOURCE_TYPES =
[Role, Environment, DataBagItem, Cookbook]
DRYRUN_MESSAGE =
"This was a dry run. Nothing has been updated on the chef server. "
DEFAULT_LOG_MESSAGE =
"There were no changes."
VERSION =
"1.0.7"

Instance Method Summary collapse

Constructor Details

#initialize(slack = false, dryrun = true) ⇒ ChefSync

Returns a new instance of ChefSync.



18
19
20
21
22
23
# File 'lib/chef_sync.rb', line 18

def initialize(slack=false,dryrun=true)
  @slack = slack
  @dryrun = dryrun
  @summary = ""
  @log = []
end

Instance Method Details

#post_to_slackObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/chef_sync.rb', line 40

def post_to_slack
  opts = { webhook_url: ENV['CHEFSYNC_SLACK_WEBHOOK_URL'] }
  opts[:username] = ENV['CHEFSYNC_SLACK_USERNAME'] if ENV['CHEFSYNC_SLACK_USERNAME']
  opts[:channel] = ENV['CHEFSYNC_SLACK_CHANNEL'] if ENV['CHEFSYNC_SLACK_CHANNEL']

  ::Slack::Post.configure( opts )
  begin
    ::Slack::Post.post_with_attachments(self.pretext, self.slack_attachment)
  #Assuming that a RuntimeError is due to improperly configured Slack::Post.
  rescue RuntimeError => e
    puts "Couldn't post to Slack: #{e}"
  end
end

#pretextObject



74
75
76
77
78
79
80
# File 'lib/chef_sync.rb', line 74

def pretext
  if ENV['CHEFSYNC_CI_BUILD_URL'].nil? or ENV['CHEFSYNC_COMMIT_URL'].nil?
    return "chef-sync run triggered."
  else
    return "<#{ENV['CHEFSYNC_CI_BUILD_URL']}|CI build> triggered by <#{ENV['CHEFSYNC_COMMIT_URL']}|commit>."
  end
end

#runObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/chef_sync.rb', line 25

def run
  @summary = DRYRUN_MESSAGE.dup if @dryrun

  RESOURCE_TYPES.each do |resource|
    responses = resource.changes(@dryrun)
    @summary << "#{responses.count}/#{resource.total_resources} #{resource.resource_type}s have changed. "
    @log += responses
  end

  @log << DEFAULT_LOG_MESSAGE if @log.empty?

  self.post_to_slack if @slack
  return @summary, @log
end

#slack_attachmentObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/chef_sync.rb', line 54

def slack_attachment
  [
    {
      fallback: @summary,
      fields: [
        {
          title: 'Summary',
          value: @summary,
          short: false
        },
        {
          title: 'Changes',
          value: @log.join("\n"),
          short: false
        }
      ]
    }
  ]
end