Is it possible to create Azure alerts for multiple subscriptions at once? - azure-powershell

I am trying to create Alerts for different services on Azure but i need to create it for all subscriptions at once using PowerShell.
I have tried with GUI but failed.

Depending on the number of subscriptions on the account it might take awhile, but you can pull an array of subscriptions from the account and perform the same actions on each of them in a loop. If you only want to run through certain subscriptions I would probably create a list in a csv file and then replace az account list | ConvertFrom-Json with the csv file.
$subs = az account list | ConvertFrom-Json
foreach($sub in $subs) {
az account set --subscription $sub.id
"Current Account:"
az account show
# create alert 1
# create alert 2
# ....
}

Related

How to update existing routing rule in Azure Frontdoor using PowerShell?

I need to update the backend pool (Maintenance) used by an existing routing rule in Azure Frontdoor to a different existing backend pool (Maintenance2). Here is the UI screen from where it can be done. Can someone advise on how to do this via PowerShell. I have tried via the cmdlets (https://learn.microsoft.com/en-us/powershell/module/az.frontdoor/set-azfrontdoor?view=azps-9.0.1 ) but unable to get the correct set of commands.
I have tried via the cmdlets (https://learn.microsoft.com/en-us/powershell/module/az.frontdoor/set-azfrontdoor?view=azps-9.0.1 ) but unable to get the correct set of commands.
In order to update the backend pool (Poo1) used by an existing routing rule in Azure Front Door to a different existing backend pool (Pool2).
Created a Front Door environment with backend Pools [Pool1/Pool2] which they are pointing to routing rules
Pool1 -> Rule1 and Pool2 -> Rules2
Click on Rule1
WorkAround:
Login into Powershell
tag to the current subscription where Front Door was created. using below command
az account set --subscription "******-****-****-****-*********"
Verify the Backend Pool on Front Door using this command
az network front-door backend-pool list --front-door-name "FrontDoorName" --resource-group "ResoruceGroupName"
Update Backend Pool for Rule1 from pool1 to pool2
using below command
az network front-door routing-rule update --front-door-name "Front Door Name" --name "Rule Name" --resource-group "Resource Group Name" --backend-pool "New Backend Pool"
example:
az network front-door routing-rule update --front-door-name "testfrontdoor" --name "Rule1" --resource-group "rg-testdemo" --backend-pool "pool2"
Output:
Resulted output on Front Door Rule1
Now Rule1 is points to Backend Pool "Pool2" instead of original one "Pool1".
Thank you Swarna. The solution provided is in CLI and the question was for powershell.
I was able to figure out how to do this in PowerShell. It requires the use of 3 Azure PS cmdlets- Get-AzFrontDoor, New-AzFrontDoorRoutingRuleObject and Set-AzFrontDoor. The way it works in the background is that when an update is performed on the Routing Rule, the routing rule is deleted and recreated with the changes. In-order to do this via PS, we have to get the existing frontdoor properties, routing rule properties and put the changes in New-AzFrontDoorRoutingRuleObject. Lastly use Set-AzFrontDoor to apply the changes to frontdoor.
$subscription='Sub1'
Select-AzSubscription $Sub1
$frontdoorName='Frontdoor1'
$resourcegroupname='fdrrg'
$MaintenanceBackPool='Maintenance2'
$PrimaryBackPool='Maintenance1'
$RoutingRuleName='Route1'
#get the current frontdoor property object
$frontdoorobj=Get-AzFrontDoor -ResourceGroupName $resourcegroupname -Name $frontdoorName
#get the Routing Rules and filter the one which needs to be modified
$RoutingRuleUpdate=$frontdoorobj.RoutingRules
$RoutingRuleUpdate2=$RoutingRuleUpdate|Where-Object {$_.Name -contains $RoutingRuleName}
#get the list of all frontendendpointIds as an array (this is required to account for more than 1 frontends/domains associated with the routing rule)
#Perform string manipulation to get the frontend/domain name from the ID
[String[]] $frontdoorHostnames=$RoutingRuleUpdate2.FrontendEndpointIds | ForEach-Object {"$PSItem" -replace '.*/'}
#get the position of the Routing Rule (to be modified) in the Routing Rules collection
$i=[array]::indexof($RoutingRuleUpdate.Name,$RoutingRuleName)
#Update the Routing Rule object with the changes needed- in this case a different backendpool
$updatedRouteObj=New-AzFrontDoorRoutingRuleObject -Name $RoutingRuleUpdate[$i].Name  -FrontDoorName $frontDoorName -ResourceGroupName $resourcegroupname -FrontendEndpointName $frontdoorHostnames -BackendPoolName $MaintenanceBackPool
$RoutingRuleUpdate[$i]=$updatedRouteObj
#Finally update the frontdoor object with the change in Routing Rule
Set-AzFrontDoor -InputObject $frontdoorobj -RoutingRule $RoutingRuleUpdate
Write-Output "Successfully Updated RoutingRule:$RoutingRuleName to backendpool:$MaintenanceBackPool"**

Get-AzureADUser - ALL - PowerShell Slow Get all users and users who made changes to account

I am working with Azure AD and need to get all users and export it into csv file and finally put it into SQL.
At this moment we have about 10,000 users. The problem is the PowerShell command [Get-AzureADUser – ALL] it’s SUPER SLOW!! It takes about 58 minutes to complete the task. Today we noticed that some users made changes to their account. I need to update the whole list to find the changes made.
My questions is:
1) Is there a faster way I can get ALL users?
2) How can I only find users who made changes to their account?
Powershell script:
$aadUsers = Get-AzureADUser -All $true | Select DisplayName, ObjectId, userType,GivenName
According to my research, if we want to get the users' changes, we have two ways to do that
Track changes to users with Users audit logs.
We can use Azure AD Powershell command Get-AzureADAuditDirectoryLogs to get Users audit logs. For more details, please refer to https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureadauditdirectorylogs?view=azureadps-2.0-preview
Install-module AzureADPreview
Connect-AzureAD
Get-AzureADAuditDirectoryLogs -All $true -Filter "Category eq 'UserManagement' and result eq 'success'"
Track changes to users with Microsoft Graph delta query
The API is as below
Get https://graph.microsoft.com/v1.0/users/delta
For example
GET https://graph.microsoft.com/v1.0/users/delta?$select=displayName,givenName,surname
If your response is too big, it will return #odata.nextLink in the response. Then you can directly use the link to get the next page response. At the last page response, it will return #odata.deltaLink in the response. You can save it and directly use the link to get the changes in next time. For more details, please refer to https://learn.microsoft.com/en-us/graph/delta-query-users
Get-msoluser -all | select DisplayName, ObjectId, userType, FirstName
Get-msoluser -all | select *
Get-msoluser -all | Where {$_.city -eq 'chicago'}
This module seems quite a bit faster.

Credentials Error when integrating Google Drive with

I am using Google Big Query, I want to integrate Google Big Query to Google Drive. In Big query I am giving the Google spread sheet url to upload my data It is updating well, but when I write the query in google Add-on(OWOX BI Big Query Reports):
Select * from [datasetName.TableName]
I am getting an error:
Query failed: tableUnavailable: No suitable credentials found to access Google Drive. Contact the table owner for assistance.
I just faced the same issue in a some code I was writing - it might not directly help you here since it looks like you are not responsible for the code, but it might help someone else, or you can ask the person who does write the code you're using to read this :-)
So I had to do a couple of things:
Enable the Drive API for my Google Cloud Platform project in addition to BigQuery.
Make sure that your BigQuery client is created with both the BigQuery scope AND the Drive scope.
Make sure that the Google Sheets you want BigQuery to access are shared with the "...#appspot.gserviceaccount.com" account that your Google Cloud Platform identifies itself as.
After that I was able to successfully query the Google Sheets backed tables from BigQuery in my own project.
What was previously said is right:
Make sure that your dataset in BigQuery is also shared with the Service Account you will use to authenticate.
Make sure your Federated Google Sheet is also shared with the service account.
The Drive Api should as well be active
When using the OAuthClient you need to inject both scopes for the Drive and for the BigQuery
If you are writing Python:
credentials = GoogleCredentials.get_application_default() (can't inject scopes #I didn't find a way :D at least
Build your request from scratch:
scopes = (
'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/cloud-platform')
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'/client_secret.json', scopes)
http = credentials.authorize(Http())
bigquery_service = build('bigquery', 'v2', http=http)
query_request = bigquery_service.jobs()
query_data = {
'query': (
'SELECT * FROM [test.federated_sheet]')
}
query_response = query_request.query(
projectId='hello_world_project',
body=query_data).execute()
print('Query Results:')
for row in query_response['rows']:
print('\t'.join(field['v'] for field in row['f']))
This likely has the same root cause as:
BigQuery Credential Problems when Accessing Google Sheets Federated Table
Accessing federated tables in Drive requires additional OAuth scopes and your tool may only be requesting the bigquery scope. Try contacting your vendor to update their application?
If you're using pd.read_gbq() as I was, then this would be the best place to get your answer: https://github.com/pydata/pandas-gbq/issues/161#issuecomment-433993166
import pandas_gbq
import pydata_google_auth
import pydata_google_auth.cache
# Instead of get_user_credentials(), you could do default(), but that may not
# be able to get the right scopes if running on GCE or using credentials from
# the gcloud command-line tool.
credentials = pydata_google_auth.get_user_credentials(
scopes=[
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/cloud-platform',
],
# Use reauth to get new credentials if you haven't used the drive scope
# before. You only have to do this once.
credentials_cache=pydata_google_auth.cache.REAUTH,
# Set auth_local_webserver to True to have a slightly more convienient
# authorization flow. Note, this doesn't work if you're running from a
# notebook on a remote sever, such as with Google Colab.
auth_local_webserver=True,
)
sql = """SELECT state_name
FROM `my_dataset.us_states_from_google_sheets`
WHERE post_abbr LIKE 'W%'
"""
df = pandas_gbq.read_gbq(
sql,
project_id='YOUR-PROJECT-ID',
credentials=credentials,
dialect='standard',
)
print(df)

Open ticket via email POP3 in Trac

I'm searching for a way to let people open Trac ticket by email.
The only solution I've found so far is email2trac | https://oss.trac.surfsara.nl/email2trac/wiki The problem with this solution is that I don't want to install & setup a mailserver. I would like a less invasive solution.
I was thinking about a cron script that download messages from a POP3 account and open/update tickets by parsing the content.
Is this possible ?
I was thinking about a cron script that download messages from a POP3
account and open/update tickets by parsing the content. Is this
possible ?
I think it would be possible yes. Certainly once you had the data from a POP3 account, you could iterate over it and create/update tickets as appropriate with the Trac API.
For the data retrieval step, you could create a new plugin, with a Component which implements the IAdminCommandProvider interface. How you actually retrieve and parse the data is an implementation detail for you to decide, but you could probably use the email/poplib modules and follow some of the parsing structure from email2trac.
For some untested boilerplate to get you started...
from trac.admin import IAdminCommandProvider
from trac.core import Component, implements
from trac.ticket import Ticket
def EmailToTicket(Component):
implements(IAdminCommandProvider)
def get_admin_commands(self):
yield ('emailtoticket retrieve',
'Retrieve emails from a mail server.'
None, self._do_retrieve_email)
def _do_retrieve_email(self):
# TODO - log into the mail server, then parse data.
# It would be nice to have a tuple of dictionaries,
# with keys like id, summary, description etc
# iterate over the data and create/update tickets
for email in emails:
if 'id' in email: # assuming email is a dictionary
self._update_ticket(email)
else:
self._create_ticket(email)
def _update_ticket(self, data):
ticket = Ticket(self.env, data[id])
for field, value in data.iteritems():
ticket[field] = value
ticket.save_changes(author, comment, when)
def _create_ticket(self, data):
ticket = Ticket(self.env)
for field, value in data.iteritems():
ticket[field] = value
ticket.insert()
You could then have Cron tab execute this command via TracAdmin (the frequency is up to you - the below example runs every minute)
* * * * * trac-admin /path/to/projenv emailtoticket retrieve
The find out more about plugin development, you should read this Trac wiki page.

Multi Login ZF2 with multi session

I have an application with 3 different logins (3 different dashboard). Not to write duplicate code I created an adapter and a plugin to login.
Now how can I manage 3 different sessions. If I run in to login Login 1 must also be signed on dashboard 2 dashboard 3, but only on dashboard 1.
How can I handle this? multi session for multi login.
This has nothing to do with authentication (or login: know what the identity of the user is) but authorization (or access: has the user the right to access this page).
You should not manage authorization with different logins, different sessions and so on. Just use a single identity for a user and use authorization for access. Take an example with ACL or RBAC, both inside Zend\Permission.
With these permission systems, you can say: this user X is allowed to access dashboard 1 and 3. The user Y is allowed to access 1 and 2. The user Z is only allowed to visit dashboard 1.
You should use Zend\Permissions\Acl. Check section "Multiple Inheritance among Roles".
http://framework.zend.com/manual/2.0/en/modules/zend.permissions.acl.intro.html
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
$acl = new Acl();
$acl->addRole(new Role('guest'))
->addRole(new Role('member'))
->addRole(new Role('admin'));
$parents = array('guest', 'member', 'admin');
$acl->addRole(new Role('someUser'), $parents);
$acl->addResource(new Resource('someResource'));
$acl->deny('guest', 'someResource');
$acl->allow('member', 'someResource');
echo $acl->isAllowed('someUser', 'someResource') ? 'allowed' : 'denied';
But in case you don't want to use ACL. then why don't you add into your login table a permission column an integer(1,2,3...up to 7 I think) on login add this integer to a session and on each dashboard you check for permission number if not allowed access then you redirect to login or home page.