Skip to content

Instantly share code, notes, and snippets.

@jrgns
Last active March 22, 2018 23:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrgns/98610aed27edeb9cab70261e6623219c to your computer and use it in GitHub Desktop.
Save jrgns/98610aed27edeb9cab70261e6623219c to your computer and use it in GitHub Desktop.
Run Ansible from Slack Ruby Bot (https://github.com/slack-ruby/slack-ruby-bot)
# deploybot/commands/ansible-play.rb
module Deploybot
module Commands
class AnsiblePlay < SlackRubyBot::Commands::Base
class AnsibleRunner
attr_reader :playbook
def initialize(playbook)
@playbook = playbook
end
def run
`#{command} 2>&1`
end
def command
"#{playbook_cmd} #{playbook_folder}/#{playbook} -i #{inventory}"
end
def playbook_folder
@playbook_folder ||= (ENV['ANSIBLE_PLAYBOOK_FOLDER'] ? ENV['ANSIBLE_PLAYBOOK_FOLDER'] : '/var/ansible/playbooks')
end
def playbook_cmd
@playbook_cmd ||= (ENV['ANSIBLE_BIN'] ? ENV['ANSIBLE_BIN'] : '/usr/bin/ansible-playbook')
end
def inventory
@inventory ||= (ENV['ANSIBLE_HOSTS_FILE'] ? ENV['ANSIBLE_HOSTS_FILE'] : '/etc/ansible/hosts')
end
def success?
$?.success?
end
end
def self.ansible(client, channel, playbook)
ar = AnsibleRunner.new(playbook)
client.say(channel: channel, text: "Trying to execute `#{ar.command}`")
output = ar.run
client.say(channel: channel, text: "```\n#{output}\n```")
if ar.success?
client.say(channel: channel, text: 'It worked!')
else
client.say(channel: channel, text: 'It didn\'t work... :(')
end
end
command 'whoami' do |client, data, match|
client.say(channel: data.channel, text: "You are <@#{data.user}> / #{data.user}")
end
match(/\!ansible (?<playbook>[^\s]+\.yml)/) do |client, data, match|
unless data.user == ENV['SLACK_AUTHED_USER']
client.say(channel: data.channel, text: "<@#{ENV['SLACK_AUTHED_USER']}> someone is screwing with me: <@#{data.user}>")
return
end
ansible(client, data.channel, match[:playbook])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment