virtual network service endpoint - azure-virtual-network

I have a virtual network in my resource group with the default subnet Microsoft Storage Service endpoints are already assigned to the default subnet of the virtual network but, now I want to add another multiple service endpoint with default subnet using PowerShell
The code below is what I'm using to add the service endpoint Microsoft.ServiceBus to the same virtual network.
#Get vnet
$virtualnetwork = Get-AzureRmVirtualNetwork -Name $VN -ResourceGroupName $RG
#Configure service endpoint
Add-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -
VirtualNetwork $virtualnetwork -ServiceEndpoint $EP
#Set configuration
$virtualnetwork | Set-AzureRmVirtualNetwork
The issue is that every time I run the above script, it updates the current service endpoint rather than adding a new one. Any idea

I tried to reproduce the same in my environment and added the service endpoint successfully like below.
I have created microsoft.storage service endpoint with default subnet like Below.
I tried to add another service endpointMicrosoft.ServiceBus to the same virtual network with default subnet using below powershell script
$subscription = "ID"
$subnets = #('default')
$vnetName = "your vnetname"
$vnetRgName = "Rgname"
$newEndpoint = "Microsoft.ServiceBus"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
$delegation=$virtualNetwork.Delegations
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint -Delegation $delegation | Set-AzVirtualNetwork
}
Output:
To check in portal, Microsoft.serviceBus is added successfully with default subnet along with Microsoft.storage.

Related

Azure Monitoring Database performance

I need to compile the following information: "a scheduled report that shows the DB environment state. From free space to performance, failed jobs and anything else that can cause a DB not to function correctly."
I keep getting referred to the same learn.microsoft links but for some reason i just get progressively more confused.
Can someone please help me with a step by step instruction on how to achieve the above mentioned?
All our DBs are on Azure VMs.
I tried Chat GPT for the disk sizes and it gave me a Power Shell code. <
# Connect to your Azure account
Connect-AzAccount
# Get a list of all virtual machines in your subscription
$vms = Get-AzVM
# Loop through the list of virtual machines
foreach ($vm in $vms) {
# Get the details of each virtual machine
$vmName = $vm.Name
$vmSize = $vm.HardwareProfile.VmSize
# Get a list of all disks attached to the virtual machine
$disks = Get-AzDisk | Where-Object { $_.ManagedBy -eq $vm.Id }
# Loop through the list of disks
foreach ($disk in $disks) {
# Get the details of each disk
$diskName = $disk.Name
$diskSize = $disk.DiskSizeGB
$diskType = $disk.StorageAccountType
# Print the virtual machine, disk, and disk size information
Write-Output "VM Name: $vmName"
Write-Output "VM Size: $vmSize"
Write-Output "Disk Name: $diskName"
Write-Output "Disk Size: $diskSize GB"
Write-Output "Disk Type: $diskType"
Write-Output ""
}
}
\>
I could not get free space information or Database information this way.
Your script is working but you are retrieving information about the VMs, not about the SQL Server that is stored within the VMs.
You need to login into the SQL Server inside the VM and run the query that you want:
# Load the Azure RM module
Import-Module AzureRM
# Login to Azure
Login-AzureRmAccount
# Get a list of all Azure VMs
$vms = Get-AzureRmVM
# Loop through each VM
foreach ($vm in $vms) {
# Get the VM's IP address
$ipAddress = (Get-AzureRmPublicIpAddress -ResourceGroupName $vm.ResourceGroupName -Name ($vm.Name + '-ip')).IpAddress
# Connect to SQL Server on the VM
$connectionString = "Server=$ipAddress;Database=master;User ID=<username>;Password=<password>"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
# Execute the SELECT ##VERSION query
$command = $connection.CreateCommand()
$command.CommandText = "SELECT ##VERSION"
$reader = $command.ExecuteReader()
# Display the result
while ($reader.Read()) {
Write-Output $reader.GetValue(0)
}
# Close the connection
$connection.Close()
}
Note that you will need to replace <username> and <password> with the actual SQL Server login credentials for each VM.
Replace the "SELECT ##VERSION" with the query that investigates:
DB environment state
free space
performance
failed jobs
anything else...

Failed to setup Custom Domain for APIM using PowerShell script

I am trying to setup custom domain for my APIM instance using below script
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$Hostname,
[String]
$ApimServiceName,
[string]
$KeyVaultId
)
$ProxyHostnameConf = New-AzApiManagementCustomHostnameConfiguration -Hostname $Hostname -HostnameType "Proxy" -KeyVaultId $KeyVaultId -DefaultSslBinding
$apim = Get-AzApiManagement -ResourceGroupName $ResourceGroupName -Name $ApimServiceName
$apim.ProxyCustomHostnameConfiguration = $ProxyHostnameConf
Set-AzApiManagement -InputObject $apim
But the script is failing with below error
Line |
15 | Set-AzApiManagement -InputObject $apim
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 'SubnetResourceId' does not match expected pattern
| '^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$'.
I am getting this error both in my local machine as well as from the devops Microsoft hosted agent
I was able to fix this using azure cli command mentioned in the below ink
Azure CLI - Bash script to set up API Management custom domain
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$HostName,
[String]
$KeyVaultId,
[String]
$ApimServiceName
)
$config ='[{\"hostName\":\"'+$HostName+'\",\"type\":\"Proxy\",\"keyVaultId\":\"'+$KeyVaultId+'\",\"defaultSslBinding\":true,\"negotiateClientCertificate\":false}]'
Write-Host $config
az apim update --resource-group $ResourceGroupName --name $ApimServiceName --set hostnameConfigurations=$config

Azure: Error while using Azure virtual network, It says subnet is not valid in virtual network

$rg1="firstyear-rg-01"
$loc="eastasia"
New-AzResourceGroup -name $rg1 -location $loc
$ec1 = New-AzVirtualNetworkSubnetConfig -Name "ec-lab-sn-01" -AddressPrefix "10.0.0.0/27"
$cs1 = New-AzVirtualNetworkSubnetConfig -Name "cs-lab-sn-01" -AddressPrefix "10.0.1.0/27"
$it1 = New-AzVirtualNetworkSubnetConfig -Name "it-lab-sn-01" -AddressPrefix "10.0.2.0/27"
$mc1 = New-AzVirtualNetworkSubnetConfig -Name "mech-lab-sn-01" -AddressPrefix "10.0.3.0/27"
$vn1 = New-AzVirtualNetwork -Name "firstyear-vn-01" -ResourceGroupName $rg1 -Location $loc -AddressPrefix "10.0.0.0/25" -Subnet $ec1,$cs1,$it1,$mc1
The above is the exact code I tried, but it gives error:
New-AzVirtualNetwork: Subnet 'cs-lab-sn-01' is not valid in virtual
network 'firstyear-vn-01'. StatusCode: 400 ReasonPhrase: Bad Request
ErrorCode: NetcfgInvalidSubnet ErrorMessage: Subnet 'cs-lab-sn-01' is
not valid in virtual network 'firstyear-vn-01'. OperationID :
c5bd59de-a637-45ec-99a7-358372184e98
What am I doing wrong?
If you are using a virtual network with an address range 10.0.0.0/25, the subnet AddressPrefix should be included in that virtual network. You can assign subnets to address prefixed like 10.0.0.0/27, 10.0.0.32/27, 10.0.0.64/27, 10.0.0.96/27 according to the IP Calculator.
I ran into this issue when setting up a subnet in Azure using Terraform.
When I run terraform apply, I get the error below:
module.subnet_private_1.azurerm_subnet.subnet: Creating...
╷
│ Error: creating Subnet: (Name "my-private-1-dev-subnet" / Virtual Network Name "my-dev-vnet" / Resource Group "MyDevRG"): network.SubnetsClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="NetcfgInvalidSubnet" Message="Subnet 'my-private-1-dev-subnet' is not valid in virtual network 'my-dev-vnet'." Details=[]
│
│ with module.subnet_private_1.azurerm_subnet.subnet,
│ on ../../../modules/azure/subnet/main.tf line 1, in resource "azurerm_subnet" "subnet":
│ 1: resource "azurerm_subnet" "subnet" {
Here's how I fixed it:
The issue was that I was assignining subnet_address_prefixes that were already assinged to a subnet to the new subnet.
I had already assinged ["10.1.1.0/24"] to an already existing subnet, and I made a mistake in my module to assign it again to the new subnet that I was creating.
All I had to do was to use a different subnet_address_prefixes, which is ["10.1.2.0/24"] and everything worked fine.
In your case, this is because your chosen IP Ranges of the subnets are not part of the Virtual Network IP Range.
Generally such error can occur either because of a subnet with the same name already exist, your chosen ip subnet range is not part of the virtual network ip range or your chosen subnet ip ranges are overlapping.
When you are not sure about the boundaries of your IP Ranges, you can use an IP Range calculator.
As you can see here, your virtual network ranges from 10.0.0.2 to 10.0.0.126. Therefor none of your subnets is in that range as you used:
"10.0.0.0/27","10.0.1.0/27","10.0.2.0/27","10.0.3.0/27"
Depending on the size you need, you can go for a configuration as suggested by #nancy Xiong.
Virtual network : 10.0.0.0/25
subnets: 10.0.0.0/27, 10.0.0.32/27, 10.0.0.64/27, 10.0.0.96/27

Setup Alert when SQL Agent Down using Task Scheduler

I am looking something to setup alert notification when SQL agent is down, sometimes when windows patch apply or server get rebooted SQL Agent is not restarting even though we have set up SQL Agent properties Auto Restart SQL Server if it stops unexpectedly
Auto Restart SQL Server Agent if it stops unexpectedly.
I have also tried to setup services on Component service on server to at Recovery tab, First Failure Restart the service and also restarted service rebooted but didn't work.
Is it any way I can get the alert so I can restart service manually when it's Agent is down it it will trigger to restart the job when Agent it's down.
$AgentStatus = (Get-Service -ComputerName <CompName> -Name <SqlServerAgentName> | Where-Object {$_.Status -eq "Stopped"} | Measure-Object).Count
If($AgentStatus -eq 1){
Start-Service -Name SqlServerAgentName
$SMPTPort = <Specify port number>
$From = "email1#domain.com"
$To = "email2#domain.com"
$Subject = "The SQL Server Agent Service in $env:ComputerName has been restarted."
$Body = "The SQL Server Agent Service <SqlServerAgentName> was in a Stopped state and has been restarted."
$SMTPServer = "SMTP SERVER"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SMPTPort)
$SMTPClient.EnableSsl = $false
$SMTPClient.Send($From, $To, $Subject, $Body)}
You can try creating a batch file below which checks for service status. This sends an SMTP mail (using powershell) along with restarting service again.
for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
powershell -ExecutionPolicy ByPass -Command Send-MailMessage -SmtpServer SMTPSERVER -To someone#domain.com -From noreply#domain.com -Subject Testing -Body Service_Not_Running
net start "MyServiceName"
)
)
Once you have the script ready, create a task scheduler to call the batch file. Run the scheduler every 1 hr or so.

Call WCF Service from bat file

is it possible to call a Methode of a WCF Service in a bat file. We want to test if the WCF Service works correct after the Server was restartet.
There are no commands within the BAT file universe that will allow you to contact a WCF service directly, however you could use a BAT file to run an existing console program that can connect and interact with a WCF service. So the answer is both yes and no; not directly, but through a separate program yes.
If you need some simple, clickable way of accessing a WCF service, I'd go with a Powershell or VB script (assuming you're in a windows environment).
Maybe you will be able to use PowerShell? It would be easier then. Create script with content:
$url = 'http://yoursite.url/example.svc'
$action = "`"http://some.namespace/method`""
$SOAPRequest = [xml]#'heregoesxmlmessage'#
write-host "Sending SOAP Request To Server: $url"
$soapWebRequest = [System.Net.WebRequest]::Create($url)
$soapWebRequest.Headers.Add("SOAPAction", $action)
$soapWebRequest.ContentType = "text/xml;charset=`"utf-8`""
$soapWebRequest.Accept = "text/xml"
$soapWebRequest.Method = "POST"
write-host "Initiating Send."
$requestStream = $soapWebRequest.GetRequestStream()
$SOAPRequest.Save($requestStream)
$requestStream.Close()
write-host "Send Complete, Waiting For Response."
$resp = $soapWebRequest.GetResponse()
$responseStream = $resp.GetResponseStream()
$soapReader = [System.IO.StreamReader]($responseStream)
$ReturnXml = [Xml] $soapReader.ReadToEnd()
$responseStream.Close()
write-host "Response Received."
$ReturnXml.OuterXml | out-file ".\test.xml"
write-host $ReturnXml.OuterXml
As mentioned in the other answers Powershell is probably the best way to go using the New-WebServiceProxy cmdlet.
http://technet.microsoft.com/library/hh849841.aspx
Example from the link above:
PS C:\> $URI = "http://www.webservicex.net/uszip.asmx?WSDL"
PS C:\>$zip = New-WebServiceProxy -Uri $URI -Namespace WebServiceProxy -Class USZip
PS C:\> $zip.getinfobyzip(20500).table
CITY : Washington
STATE : DC
ZIP : 20500
AREA_CODE : 202
TIME_ZONE : E