Skip to content
adatum
  • Home
  •  About adatum
  •  Learn Azure Bicep
  •  SCOM Web API
Automation

Sending SMS with Azure functions and Twilio

  • 23/12/201607/01/2025
  • by Martin Ehrnst

Update:

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

pretty cool but the secret should at least be stored as application settings, not in clear text in the code. or even better – in Key Vault

— Tao Yang (@MrTaoYang) July 4, 2017

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.

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
Azure

I have moved script logging to OMS

  • 15/12/201607/01/2025
  • by Martin Ehrnst

For some time I have “rewritten” my scripts to utilize variables, connections  and other assets in Azure automation. While doing this I have moved all script logging to the cloud as well.

previously all scripts were logging to a file or to the computers event log. I have some experience with sending custom data to OMS. Using their API i have sent weather data and the technique could easily be transferred to do my script logging.

I thought about  creating a module for this for a while, but luckily, the great Mr Tao Yang already did it and it is available on GitHub, PSGallery and in Azure automation. The only thing i had to do was wrap everything in a function and call that each time i needed a log entry sent from my scripts.

Based on Tao’s OMSDataInjection module. Here’s how my function looks like

<#
    .DESCRIPTION
        Function sends a entry to OMS Log analytics.
        Used to send script log entries to OMS in a 'one liner'


    .NOTES
        Requires Tao Yang's OMSDatainjection Module: https://github.com/tyconsulting/OMSDataInjection-PSModule/releases/tag/1.1.1
        Author: Martin Ehrnst
        www.adatum.no
    
    .CHANGELOG
        06.12.16: Initial function release
    
#>

param (
    [parameter(Mandatory=$true)]
    [string]$Message,
    [parameter(Mandatory=$true)]
    [ValidateSet('Information','Warning','ERROR')]
    [string]$Severity
    )

$LogEntry = @{
  ScriptName = scriptName
  Severity = $Severity
  RanAT = $env:COMPUTERNAME
  Message  = "$Message"
  LogTime  = [Datetime]::UtcNow
}

$SendLog= New-OMSDataInjection -OMSWorkSpaceId '**************' -PrimaryKey '********************************' -LogType 'test' -UTCTimeStampField 'LogTime' -OMSDataObject $LogEntry
}

The only thing you have to before you use it is to define your script name, OMSWorkspaceID, PrimaryKey and a LogType. When all is good. Call this each time you want to send a log entry

Send-LogEntry -Message "testing 123" -Severity Warning

Here is a script, from on prem to Azure Automation to run on a Hybrid worker using this function to do the logging.

Please note that since i run through azure automation i have created a connection object and reffeer to that using instead of specifying the ID and Key.

<#
    .NAME
        Close-OldSCOMAlerts.ps1


    .DESCRIPTION
        Closes SCOM alerts based on severity, resolution state, repeat count etc. Alter settings in the configuration regions.
        The script requires OpsMgr module and Azure automation. I Reccomend storing the credentials and variables as assets and run the script on a hybrid worker.
        If you want to run locally, change the script parameters and hard code the values.


    .NOTES
        Requires Operations Manager Module and Tao Yang's OMSDatainjection Module
        Author: Martin Ehrnst
        Version: 1.1 Initial (Azure automation) Release 28.11.16
        www.adatum.no
        www.intility.no
    
    .CHANGELOG
        08.12.16: Using Tao Yang's OMSDataInjectionModule to ship script logs to OMS
        Removed local logging
    
#>

#region Configuration
$ErrorActionPreference = "Continue"
#$VerbosePreference = "Continue" #Uncomment to see verbose output
[int]$RepeatCount = 2 #Alerts with less than x repeat count will close
[int]$AlertAgeHours = 3 #Alert Age (older gets closed)
[string]$AlertSeverity = "Information" #specify alert severity you want to close
[int]$ResolutionState = 0 #0 NEW
[int]$SetState = 255 #255 CLOSED
[string]$Comment = "Alert closed by script in azure automation" #Comment to set on the closed alerts
#endregion

#region Modules
Import-Module "C:\Program Files\WindowsPowerShell\Modules\OMSDataInjection\1.1.1\OMSDataInjection.psm1"

$module = Get-Module -Name OperationsManager
if (!$module){
    Write-Verbose "Could not find SCOM Module. Importing"
    Import-Module OperationsManager -Cmdlet Get-SCOMalert, New-SCOMManagementGroupConnection, Update-SCOMAlert, Set-SCOMAlert
    }
#endregion

#region OMSLogging
    $OMSWorkspace = Get-AutomationConnection 'I2-Intility-Test'
    
    
function Send-LogEntry{
<#
    .DESCRIPTION
        Function sends a entry to OMS Log analytics.
        Used to send script log entries to OMS in a 'one liner'


    .NOTES
        Requires Tao Yang's OMSDatainjection Module: https://github.com/tyconsulting/OMSDataInjection-PSModule/releases/tag/1.1.1
        Author: Martin Ehrnst
        www.adatum.no
        www.intility.no
    
    .CHANGELOG
        06.12.16: Initial function release
    
#>
param (
    [parameter(Mandatory=$true)]
    [string]$Message,
    [parameter(Mandatory=$true)]
    [ValidateSet('Information','Warning','ERROR')]
    [string]$Severity
    )

$LogEntry = @{
  ScriptName = 'Close-OldSCOMAlerts.ps1'
  Severity = $Severity
  RanAT = $env:COMPUTERNAME
  Message  = $Message
  LogTime  = [Datetime]::UtcNow
}

$SendLog= New-OMSDataInjection -OMSConnection $OMSWorkspace -LogType 'AutomationLogs' -UTCTimeStampField 'LogTime' -OMSDataObject $LogEntry

}
#endregion

Send-LogEntry -Message "Starting azure automation runbook to close old scom alerts" -Severity Information

#region AzureConfig
    
    $SCOMOperator = Get-AutomationPSCredential -Name 'AzureAutomationSCOMOperator'
    $SCOMManagementServer = Get-AutomationVariable -Name 'SCOMProdSDKServer'

#endregion

Try {
    #Connecting to SCOM management server
    Write-Verbose "Connecting to $ManagementServer"
    New-SCOMManagementGroupConnection -ComputerName $SCOMManagementServer -Credential $SCOMOperator
    }
Catch {
    Write-Error "$_.Exception.Message"

    Send-LogEntry -Message "$_.Exception.Message" -Severity ERROR
    }

#Actual alert work
$Date = (Get-Date).AddHours(-$AlertAgeHours).ToUniversalTime() #Setting Alert age and converting to UTC

$Alerts = Get-ScomAlert | where {$_.TimeRaised -lt $Date `
    -and $_.ResolutionState -eq $ResolutionState `
    -and $_.Severity -match $AlertSeverity `
    -and $_.RepeatCount -lt $RepeatCount `
    -and $_.IsMonitorAlert -eq $false
    }
if ($Alerts){
        $count = $alerts.Count
        Send-LogEntry -Message "Closing $count alerts" -Severity Information
       
        $alerts | Set-SCOMAlert -ResolutionState $SetState -Comment $Comment
        Send-LogEntry -Message "Finished - closed $count alerts" -Severity Information
        Write-Output "closed $count alerts"
    }
else{
    Write-Output "No old alerts to close. Exiting script"
    Send-LogEntry -Message "Finished. No alerts to close" -Severity Information
    }

 

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
OMS

SCOM and OMS: The agents

  • 01/12/201607/01/2025
  • by Martin Ehrnst

Both SCOM and OMS are in most ways dependent on agents installed on each server being monitored. If you have SCOM today you probably run Microsoft Operations Manager Agent (MOM) which is shipped with SCOM 2012 media and installed through the SCOM console or a SW deployment tool ConfigMgr etc.

OMS on the other hand uses the new Microsoft Monitoring Agent (MMA) which is available for download within your OMS workspace or through MSFT download center. MMA is said to be the mother of all agents which should be used by every Microsoft software that require an agent.

NB: At some point (SCOM 2012 SP1?) the agent actually got rebranded to Microsoft Monitoring Agent. It is stil not the same you get from OMS

 

The reason for looking in to the agents is that we one situation wher we lost contact with one server belonging to a customer (a customer of my employee Intility).

It turned out that they had signed up for OMS and configured the MMA agent to. At some point this deleted our SCOM configuration and we lost monitoring on that server.

As OMS is fast forwarding these days we will have to be proactive and support agent/servers directly reporting to other OMS workspaces than the one connected to our SCOM environment.

 

After some testing here is what i found is the main differences on these agents:

Supports MOM/SCOM Agent

OMS Agent (MMA)

SCOM Workgroup X X
Multihome SCOM Workgroup X X*
OMS Reporting X (through SCOM) X
Multihome OMS Workspace X*
Hybrid Worker support X

*I do not know if there is a limitation on how many connections an agent can have, but I have tried 5 in total. 3 OMS workspaces and 2 SCOM work groups.

 

Screenshots showing MMA

Microsoft Monitoring Agent Properties Operations Manager Azure Log Analytics (OMS) Proxy Setüngs Properbes An agent can report to mulbple management groups. If you use Operations Manager integration with Active Directory Domain Services (AD DS), the list of management groups can be updated automabcally. Automabcally update management group assignments from AD DS If you select this opton, the agent will query AD DS for the list of management groups to which it has been assigned. If any are found, they are added to the ist. Managementgroups thathave been found in AD DS cannot be removed by using this property sheet. Managemen t Groups: Primar y Management Ser.. Port •e Assignmen t Agent Action

 

MOM rebranded

Microsoft Monitoring Agent Properties Operations Manager Properties An agent can report to multipla management groupe f you use Operations Manager integration with Active Directory Domain Services (AD DS). the list of management groups can be updated automatically r Automatically update management group assignments from AD DS f you select this option. the agent will query AD DS for the list of management groups to which t has been assigned f any are found. they are added to the list Management groups that have been found in AD DS cannot be removed by using this property sheet Management Groups: Prim Man Ser Port

 

At this point we plan to upgrade all agents making sure customers are able to report to their own OMS workspace without interfering with our central SCOM and OMS installations.

SCOM 2016 is also shipped with the MMA agent and is likely the same but with a different version.

 

Let me know if you have something to add and I will update my post accordingly.

 

 

Bombshell:

If you extract the .MSI from MMASetup******.exe you end up with a MSI which installs the “old” MOM agent

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit

Posts pagination

1 … 28 29 30 31 32 … 37

Popular blog posts

  • Azure Application registrations, Enterprise Apps, and managed identities
  • Access to Blob storage using Managed Identity in Logic Apps - by Nadeem Ahamed
  • Creating Azure AD Application using Powershell
  • Track changes to Azure resources
  • First look at the vSphere 6.5 REST API

Categories

Automation Azure Azure Active Directory Azure Bicep Azure DevOps Azure Functions Azure Lighthouse Azure Logic Apps Azure Monitor Azure Policy Community Conferences CSP Monitoring DevOps GitHub Guest blogs Infrastructure As Code Kubernetes Microsoft CSP MPAuthoring OMS Operations Manager Podcast Powershell Uncategorised Windows Admin Center Windows Server

Follow Martin Ehrnst

  • X
  • LinkedIn

RSS feed RSS - Posts

RSS feed RSS - Comments

Microsoft Azure MVP

Martin Ehrnst Microsoft Azure MVP
Adatum.no use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Cookie Policy
Theme by Colorlib Powered by WordPress