RabbitMQ admin script based on REST API

Here I use the ruby script below to create a vhost for user, with the corresponding permissions setup. It can delete the vhost and user as well. The script is based on RabbitMQ’s restful admin API.

require "rabbitmq/http/client"
require 'securerandom'

class MQManage

    def initialize(admin_host,mq_host,mq_port,mq_user,mq_pass)
        @mq_host = mq_host
        @mq_port = mq_port
        endpoint = "http://#{admin_host}:15672"
        @client = RabbitMQ::HTTP::Client.new(endpoint, :username => mq_user, :password => mq_pass)
    end

    def create_mq_dsn
        vhost = "/" + SecureRandom.hex(6)
        user = SecureRandom.hex(6)
        pass = SecureRandom.hex(8)
        @client.create_vhost(vhost)
        @client.update_user(user, :tags => "autodeploy", :password => pass)
        @client.update_permissions_of(vhost, user, :write => ".*", :read => ".*", :configure => ".*")

        dsn = {:host => @mq_host, :port => @mq_port, :vhost => vhost, :user => user, :pass => pass}
        return dsn
    end

    def drop_mq_dsn(vhost)
        vs = @client.list_vhosts
        names = []
        vs.each do |s| names << s.name end

        if vhost == "/"
            return -1
        end

        if not names.include? vhost
            return -2
        end

        ps = @client.list_permissions(vhost)
        ps.each do |s|
           @client.delete_user(s.user)
        end

        @client.delete_vhost(vhost)
    end
end
Print Friendly, PDF & Email