Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Wednesday, 14 October 2020

Azure PowerShell : Script to create Azure App Service

This PowerShell script is to create an Azure App Service with .NETCORE Web Application:
#Provide following variables:

$subscriptionname = ""
$Environment = ""
$webappName=""              #Provide Web App Name
$location="westus"                         #Provide Location
$resourceGroupName = ""     #Provide Resource Group
$AppServicePlan = ""   #Provide Service Plan
$BusinessOwner = ""
$Owner =""

$SubsId = Get-AzSubscription -SubscriptionName $subscriptionname

Select-AzSubscription -SubscriptionId $SubsId.Id

#Creating WebApp
New-AzWebApp -ResourceGroupName $resourceGroupName -Name $webappName `
-Location $location -AppServicePlan $AppServicePlan

Set-AzWebApp -ResourceGroupName $resourceGroupName `
-Name $webappName -AlwaysOn $true


#Setting .NET CORE
$dotnetResourceName = $webappName + "/metadata"

$PropertiesObject = @{
    "CURRENT_STACK" =  "dotnetcore"
}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName $resourceGroupName `
-ResourceType Microsoft.Web/sites/config -ResourceName $dotnetResourceName -Force



#Creating App Insight
New-AzApplicationInsights -ResourceGroupName $resourceGroupName `
-Name $webappName -Location $location

# Collecting create app insight info
$appInsightsKey = Get-AzApplicationInsights -Name $webappName `
-ResourceGroupName $resourceGroupName


$errorpage = "https://"+ $webappName + 
".scm.azurewebsites.net/detectors?type=tools&name=eventviewer"

$appconnectionstring = "InstrumentationKey=" + $appInsightsKey.InstrumentationKey `
+";IngestionEndpoint=https://"+ $location + "-0.in.applicationinsights.azure.com/"


$app = Get-AzWebApp -ResourceGroupName $resourceGroupName -Name $webappName -ErrorAction Stop
$newAppSettings = @{} # case-insensitive hash map
# preserve non Application Insights application settings.
$app.SiteConfig.AppSettings | %{$newAppSettings[$_.Name] = $_.Value} 
$newAppSettings["ANCM_ADDITIONAL_ERROR_PAGE_LINK"] = $errorpage;
 # set the Application Insights instrumentation key
$newAppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] = $appInsightsKey.InstrumentationKey;
 # set the Application Insights connection string
$newAppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"] = $appconnectionstring;
 # enable the ApplicationInsightsAgent
$newAppSettings["ApplicationInsightsAgent_EXTENSION_VERSION"] = "~2";
$newAppSettings["XDT_MicrosoftApplicationInsights_Mode"] = "default";

$app = Set-AzWebApp -AppSettings $newAppSettings `
-ResourceGroupName $app.ResourceGroup -Name $app.Name -ErrorAction Stop

$Tags = @{App="Apps";BusinessOwner=$BusinessOwner;Owner=$Owner;Environment =$Environment};

Set-AzResource -ResourceGroupName $resourceGroupName `
-Name $webappName -ResourceType Microsoft.Web/sites -Tag $Tags -Force
    
  

Wednesday, 15 July 2020

MS Azure : Run Login-AzureRmAccount to Login Silently in Azure Automation Runbooks

How to Run Login-AzureRmAccount to Login Silently when working with PowerShell script in azure Automation Runbooks to get data from Azure Subscription

Issue: This blogpost is to fix the below error message:
Get-AzureRmResourceGroup : Run Login-AzureRmAccount to login.
At line:35 char:19
+ $ResourceGroups = Get-AzureRmResourceGroup
+                   ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:)PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.Resources

When executing any AzureRM [i.e. Azure Resource Manager] PowerShell command first requires Azure authentication at Azure subscription level.
So if executing AzureRM command without Login-AzureRMAccount, we will get an error message as above.

Solution:
Use Azure AD Service Principal to resolve this issue. So what is Service Principal?
Service principal means running an application as a user and giving full access to it so now it can perform any action against azure subscription level. As Azure subscription is always present in the Azure Active Directory tenant; must add the information of application in Azure AD tenant and this is nothing but the service principal.
So how do we create a Service principal? Well you don’t have to create because it is already exists when we have an Azure ARM automation account created.
Open Assets -> Connections -> AzureRunAsConection
This shows type as Azure service principal and there are many Ids present.

Application Id is the one by which your Automation account is identified as Service principal in Azure AD. Tenant id is nothing but Azure AD id under which your subscription exists. Subscription Id is the actual Azure subscription Id.

Let’s verify this exist in your Azure AD as well. For the same, on Azure portal open
Azure Active Directory -> App Registrations
You will see an Application Id same as what we have observed under automation account connection.

This means AzureRunAsConection of automation account is acting as Service principal. Hence it can be used for authentication against the subscription and also to perform operations against our azure subscription. With this let’s write some PowerShell code to perform authentication using service principal.

Authenticating using Service principal

Code for authenticating Azure Automation account runbook using Automation connection as Service principal is shown below:
Add above code segment in any runbook you wish to in Azure Automation account and you will never receive error of “Run Login-AzureRMAccount to login”.
Thats it!! :-)
$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName      
    "Logging in to Azure..."
    $account = Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}
Write-Output $account

Friday, 1 May 2020

MS Azure : PowerShell script to Map Azure Storage Fileshare as a Drive Letter

PowerShell script to map fileshare named folder "DatabaseFiles" from Azure fileshare named "filesdbprod01":

# Input Variables : Provide input to following Variables

$filesharename="filesdbprod01"
$accesskey = "asnjanskdaodnajksndjknaskdnand&^&T^ASDASasaksjdkasjsdajsod"
$root = "DatabaseFiles"
$drive = "X"


# Script Variables
$fullFSName= $filesharename + ".file.core.windows.net"
$FSroot = "\\" + $fullFSName + "\" +$root
$user = "Azure\" + $filesharename

$connectTestResult = Test-NetConnection -ComputerName $fullFSName -Port 445

if ($connectTestResult.TcpTestSucceeded) {
# Save the password so the drive will persist on reboot
cmd.exe /C "cmdkey /add:$fullFSName /user: $user /pass: $accesskey "
# Mount the drive
New-PSDrive -Name $drive -PSProvider FileSystem -Root $FSroot -Persist
} else {
Write-Error -Message "Unable to reach the Azure storage account via port 445.
Check to make sure your organization or ISP is not blocking port 445,
or use Azure P2S VPN, Azure S2S VPN, orExpress Route to tunnel 
SMB traffic over a different port."
} 



Monday, 20 January 2020

PowerShell to Send Mail in HTML format using SMTP

PowerShell Script to Send mail in html format using smtp Server:

PS Script to Send mail with attachment(optional):
Information required:
1. Create ".html page" like in script using "content.html"
2. Make a note of file path, if needs to be attached with an email.
3. smtp server details.
4. Save the below script somewhere with ".ps1" extension, That's it!!

############################################

###########Define Variables########

$fromaddress = "donotreply@labtest.com"
$toaddress = "A@labtest.com"
$bccaddress = "A@labtest.com"
$CCaddress = "A@labtest.com"
$Subject = "ACtion Required"
$body = get-content C:\dba_path\content.html
$attachment = "C:\dba_path\test.txt"
$smtpserver = "smtp.lab.com"

####################################

$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)

###############################################