Replace Webhook URL on All PagerDuty Services

Replace Webhook URL on All PagerDuty Services

by Ryan Hoskin

JavaScript

//Replace Webhook URL on All PagerDuty Services

old_url = "https://enter_the_url_to_replace.com";

PDJS = new PDJSobj({
    subdomain: "REDACTED",
    token: "REDACTED",
})
get_webhooks = function(service_id) {
    PDJS.api({
        res: "webhooks",
        type: "GET",
        data: {
            webhook_object: {
                id: service_id,
                type: "service",
            }
        },
    
        success: function (json) {
            if(json.total > 0) {
                $.each(json.webhooks, function(key, webhook) {
                    if (webhook.url == old_url) {
                        webhook_object = webhook.webhook_object
                        service_id = webhook_object.id
                        update_webhook (service_id, webhook.id)
                    }
                    else {
                        console.log("url does not match: " + webhook.url);
                    }
                });
            }
        }
    })
}

update_webhook = function(service_id, webhook_id) {
    PDJS.api({
        res: "webhooks/" + webhook_id,
        type: "PUT",
        data: {
            webhook_object: {
                id: service_id,
                type: "service",
                object: {
                    id: service_id,
                    type: "service"
                }
            },
            id: webhook_id,
            name: "Enter a Name Here",
            url: "https://enter_the_new_url.com"
        },
        success: function(json) {
            console.log(webhook_id)
            console.log(json)
        }
    })
}

PDJS.api_all({
    res: "services",
    final_success: function (data) {
        jQuery.each(data.services, function (index, service) {
            get_webhooks(service.id)
        })
    }
})