I'm trying to create start/stop schedule for my virtual machine. Simple schedule:
Start # 10am, Stop # 5pm, don't run on the weekend
Trying to create this automatic schedule is turning into a nightmare!
I don't have time to learn PowerShell.
I looked into doing this thru the Automation portal. I have imported a script through the repository.
"Name of Script: Scheduled Virtual Machine Shutdown/Startup by Automys"
and as it is shown in Azure portal:
"assert-autoshutdownshedule."
I now need to edit this script.
Where/how do I input my credentials/parameters? What needs to be changed?
Create Run as Automation account in azure portal
then import the below script to your Runbook.
if(-not (#('Saturday', 'Sunday') -contains (Get-Date).DayOfWeek)) #skip execution if the day of week is Saturday or Sunday
{
$cred = Get-AutomationPSCredential -Name "Your Automation Account"
Login-AzureRmAccount -Credential $cred
Get-AzureRmSubscription
Select-AzureRmSubscription -SubscriptionName "Your Subscription Name"
Start-AzureRmVM -Name "VM001" -ResourceGroupName "Your Resource group" -ErrorAction Continue -Force
}
All the best :)
Let me know if this work
Related
We keep randomly getting the error "Resource group '{resource-group-name}' could not be found" when running our runbooks, where {resource-group-name} is the name of one of our resource groups. These runbooks are either running in that resource group, or have selected the subscription where that resource group resides. The RunAs account also has Contributor permissions on the resource group(s). This is happening in runbooks that we run daily. Sometimes we get the error and sometimes we don't. There doesn't appear to be a reason for this happening. It's almost like the Azure runbook worker is losing context. We are not using a hybrid runbook worker. We've tried a number of things, including ensuring that our RunAs connection is logged in to Azure.
I suggest you to try below way of connection:
Disable-AzContextAutosave –Scope Process
$connection = Get-AutomationConnection -Name AzureRunAsConnection
$logonAttempt = 0
while(!($connectionResult) -And ($logonAttempt -le 10))
{
$LogonAttempt++
# Logging in to Azure...
$connectionResult = Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID -ApplicationID $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint
Start-Sleep -Seconds 30
}
$AzureContext = Select-AzSubscription -SubscriptionId $connection.SubscriptionID
Get-AzVM -ResourceGroupName "xxxxxxxxxxxxxxx" -AzureRmContext $AzureContext
As shown below, I got the same error code ResourceGroupNotFound when I have provided a dummy non-existing resource group name so I suggest you to double check the resource group name part i.e., may be some extra whitespace is getting added to your actual resource group name or something of that sort might be the reason for your issue.
Want to update Smart detection setting alerts provided under Azure application insights using powershell cmdlets.
I want to update Smart detection setting alerts provided under Azure application insights using powershell cmdlets, following is a scenario which i want to accomplish.
Scenario: I want to update Failure Anomalies alert and register my emailid under additional email recipients and want to disable the default mail to subscription owner configuration.
Is there any way above mentioned scenario can be accomplished using powershell cmdlets?
Update:
Here is a solution and assume your have azure powershell az module installed(it's ok if you're using powershell azureRM module, but you need to just change the cmdlet respectively):
#the -Name parameter is the Failure Anomalies alert name you see in azure portal, like "Failure Anomalies - your_app_insights_name"
$alets_all = Get-AzAlertRule -ResourceGroupName "xxx" -Name "xxx"
$a = $alets_all[0]
$AppIns = "xxx" #the application insights name
$ResourceGroup = "xxxx"
$SubscriptionId ="xxxx"
$Location =$a.Location
$MetricName =$a.Condition.DataSource.MetricName
$action=New-AzAlertRuleEmail -CustomEmail "abc#gmail.com; xyz#microsoft.com"
$action.SendToServiceOwners=$false
Add-AzMetricAlertRule -Name "Failure Anomalies - $AppIns" -ResourceGroupName $ResourceGroup -TargetResourceId "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/microsoft.insights/components/$AppIns" -Operator GreaterThan -Threshold 0 -WindowSize 01:00:00 -Location $Location -TimeAggregationOperator Total -Action $action -MetricName $MetricName
it works well at my side, and test result as below:
I'm building my Azure Logic Apps worklow which is supposed to check some conditions and run following Powershell:
Stop-AzureWebsiteJob -Name MyWebsite -JobName MyWebJob
Start-AzureWebsiteJob -Name MyWebsite -JobName MyWebJob -JobType Continuous
The question is: what's the easiest way to invoke such script in Azure Logic Apps? It seems like there's no built in block/connector for Powershell so I'd like to know what are the possibilites. Or perhaps it might be easier to run az CLI command with similar operation
Finally I ended up with a solution which takes advantage of Azure Automation. From Azure Portal we can create new Resource typing in Automation:
Once the resource is created we can add new Runbook under runbooks tab:
Runbook can run Powershell Workflow and get authorized using AzureRunAsConnection option (details here). My sample Powershell which is supposed to restart WebJob an specific App Service looks like below:
Workflow RestartMyWebJob
{
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$AzureContext = Select-AzureRmSubscription -SubscriptionId $Conn.SubscriptionID
$Apiversion = "2015-08-01"
$ResourceGroupName = 'My-Resource-Group-Name'
$ResourceName = 'My-Resource-Group-Name/My-AppService--WebJob-Name'
Invoke-AzureRmResourceAction -ResourceGroupName $ResourceGroupName -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName $ResourceName -Action stop -ApiVersion $Apiversion -Force
Invoke-AzureRmResourceAction -ResourceGroupName $ResourceGroupName -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName $ResourceName -Action start -ApiVersion $Apiversion -Force
}
Having this Workflow setup we can run it from Azure Logic Apps by adding new block to our logic.
Currently, azure logic seems not support to run powershell and cli script, here is a voice in azure feedback, you could vote it.
Workaround:
If you want to start and stop the webjob, you can call the Kudu WebJobs API in the logic app.
You can follow the steps below.
1.Run the powershell command locally to generate the Authorization token of your web app.
$creds = Invoke-AzureRmResourceAction -ResourceGroupName joywebapp -ResourceType Microsoft.Web/sites/config -ResourceName joywebapp2/publishingcredentials -Action list -ApiVersion 2015-08-01 -Force
$username = $creds.Properties.PublishingUserName
$password = $creds.Properties.PublishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
The $base64AuthInfo is what we need, it should be like JGpveXdlYmFwcDI6NnJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzRktSdXlUcU5acUUzdFhNb05j.
The token will never be changed except you reset the publish profile, so you just need to do this step once.
2.In the logic app, specific the Method, URI, Headers(The header should be like
Authorization: Basic JGpveXdlYmFwcDI6NnJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzRktSdXlUcU5acUUzdFhNb05j, note use space to separate the Basic and token), for example , I start a triggered webjob in my web app.
Triggered result:
So you just need to follow the steps above, for your issue, refer to the APIS:
Start a continuous job
Stop a continuous job
Create an Azure Function with an http trigger with Powershell as the function language (or any other supported language). Then you call the Function easily in the Logic app by calling an Http endpoint.
actually nowdays Azure provide this option, without creating runbooks and automation accounts. It is still in preview mode, but seems to be working !
You can also have your PowerShell code run in an Azure Container Instance supporting PowerShell and create an new Container Group from the Logic App workflow.
I have created an Azure Data Factory pipeline and deployed it. No issues. When I am in the Azure portal Data Factory blade, I click on the Monitor & Manage button and it takes me to a new tab in MS Edge with the following error:
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
Does anyone know what I need to do to be able to monitor my Azure Data Factory pipeline activity?
Thank you.
Not sure about the 404 error, maybe just an authentication issue. Or permissions in your Azure directory.
To monitor a pipeline or ADF in general I would suggest using PowerShell. There are loads of cmdlets to do things beyond the Azure Portal UI, including set a time slice status.
For example, to check what's currently 'In Progress' in your factory do something like this...
Import-Module Azure
#Params...
$AzureUser = "" # <<< enter username
$AzurePass = "" #<<< enter password
$AzureSubscription = "" # <<< enter subscription name
$ResourceGroup = "" # <<< enter resource group name
#Create credential
$SecurePassword = ConvertTo-SecureString $AzurePass -AsPlainText -Force
$PSCredential = New-Object System.Management.Automation.PSCredential ($AzureUser, $SecurePassword)
#Create Azure Connection
Login-AzureRmAccount -Credential $PSCredential | Out-Null
#Set context for subscription
$SubId = Get-AzureSubscription `
-SubscriptionName $AzureSubscription | SELECT SubscriptionId
Set-AzureRmContext -SubscriptionId $SubId.SubscriptionId | Out-Null
#Get ADF details
$ADFName = Get-AzureRmDataFactory `
-ResourceGroupName $ResourceGroup | SELECT DataFactoryName
Get-AzureRmDataFactoryActivityWindow `
-DataFactoryName $ADFName.DataFactoryName `
-ResourceGroupName $ResourceGroup `
| ? {$_.WindowState -eq "InProgress"}
Here's a link to the other cmdlets.
https://learn.microsoft.com/en-us/powershell/resourcemanager/azurerm.datafactories/v2.5.0/azurerm.datafactories
Hope this helps.
Thank you Paul, I want to start getting more familiar with Azure Powershell cmdlets.
I was able to access the portal Monitor & Manage by opening the portal in Chrome. Seems strange that MS Azure doesn't work in MS Edge but it does work in Chrome.
Thank you for you response.
Jon
I need to stop all my vm's in azure portal when my balance is 0$ How can i do it? maybe some script?
Unfortunately you can't do that with script for now... The balance (or billing) is not exposed via the Azure REST API (or Azure PowerShell).
For shutdown, we use a RUNBOOK with the follow code inside.
We run this everyday at 8PM. (You could trigger this from another alert http://www.matthewjbailey.com/create-azure-billing-alert-email/)
workflow ShutDown-AllVMs {
param (
[parameter(Mandatory=$true)]
[String] $VMCredentialName = "ourcred#xyz.com"
)
$Credential = Get-AutomationPSCredential -Name $VMCredentialName
if ($Credential -eq $null) {
throw "Could not retrieve '$VMCredentialName' credential asset. Check that you created this asset in the Automation service."
}
Add-AzureAccount -Credential $Credential
Select-AzureSubscription BizSpark
InlineScript {
Get-azurevm | ? { $_.Status -ne "StoppedDeallocated"} | Stop-AzureVM -Force
}
}
For alerts
Setup the alert
http://www.matthewjbailey.com/create-azure-billing-alert-email/
Monitor the alert
http://blogs.technet.com/b/keithmayer/archive/2014/11/08/scripts-to-tools-automate-monitoring-alert-rules-in-microsoft-azure-with-powershell-and-the-azure-service-management-rest-api.aspx
I have not tried all this together, so you may have a 2+2=5 issue :) but have a read of the blogs and you may find that you get 4 :)