Sending SMS with Azure functions and Twilio

Update:

As pointed out by Tao Yang, storing the Twilio credentials in the script isnt exactly best practice.

I have updated the script below to use Functions environment variables. You can create these from Settings>Manage Application settings 
[Fast publish]

Here the other day i “needed” to send a SMS when an alert was raised in Microsoft OMS. I already had a Twilio subscription so i developed a little script to send my self a text message. Later I put that script in a runbook in Azure Automation and called that from the alert. SMS received and it was all good.

Later the same evening i was trying out Azure Functions which let you run so called ‘server-less code’. Serverless or not, the code has to run on something, but you don’t need to maintain the infrastructure. I needed something to test Functions so i ported my Automation runbook in to a function.

The function accepts (in my environment) a webhook or sending a post with Json string.

And here is the code that does it. You will have to add your own Twilio config, but other than that it should work.

<#
    .DESCRIPTION
        Azure function sending SMS through Twilio.
        Depending on how you set up your function. This script will accept bot GET parameters through it's URL or a POST with JSON string sending phone and msg

        {
            "phone": "+4712345678",
            "msg": "www.adatum.no"
        }

        It will send the msg to the number you provide.

    .NOTES
        Requires an active twilio subscription and an azure functions container.
        Please add your Twilio sid, secret and phone number to the script

        Created by Martin Ehrnst
        www.adatum.no

    .CHANGELOG
        21.12.16: v1.0 initial release

#>

$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$phone = $requestBody.phone
$msg = $requestBody.msg
$sid = $env:TwilioSID
$password = ConvertTo-SecureString -String $env:TwilioPASS -AsPlainText -Force
$uri = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"
$from = $env:TwilioPhone

if ($req_query_phone) 
{
    $phone = $req_query_phone 
}

if ($req_query_msg) 
{
    $msg = $req_query_msg
}


$cred = New-Object System.Management.Automation.PsCredential($sid,$password)

$SMS = @{
    From=$from
    To=$phone
    Body=$Msg
}

$SMSEND = Invoke-RestMethod -Method Post -Uri $uri -Credential $Cred -Body $SMS
Out-File -Encoding Ascii -FilePath $res -inputObject "$smssend"

Here is a little example on how you configure your OMS alert to use it. The message contains a link to the alert search result.

1 COMMENT

Engage by commenting