Azure PowerShell - Getting Started (Presentation)

Presentation #01

About me

I am
Kiran Patnayakuni

Working as a
Cloud Ops Engineering Specialist

I blog at
https://kpatnayakuni.com

I am a moderator and ICYMI editor @ PowerShell.org

Follow me on
Session link
kpatnayakuni.com/azps

Session recordings
kpatnayakuni.com/azpspl

My special thanks to
Heartin J. Kanikathottu
and                    
Azure Cloud FB Group

Abstract

Azure PowerShell is used to automate, manage and administrate the Microsoft Azure Services. It is a PowerShell module used with the command line interface with vast support of Azure services and huge collection of cmdlets.

This session includes…

Azure Cloud Shell

Azure PowerShell Module

Azure PowerShell CmdLets (Demo)


Target Audience

  • Microsoft Azure & PowerShell Users

Prerequisite

  • Microsoft Azure Basics
  • PowerShell Basics
  • Azure Subscription

Environment Setup

  • Install Chocolatey Package Manager
  • Install PowerShell 7
  • Install Windows Terminal
  • Install Az Module
  • Install Visual Studio Code
  • Install PowerShell Extension for VSCode
  • Install Azure Tools Extension for VSCode
  • Install NodeJS

Azure Cloud Shell

Introduction

Azure Cloud Shell is an interactive, authenticated and browser based shell hosted in cloud to manage the Azure resources, and it supports both Bash & PowerShell.

Key Features

  • It is most useful for all common tasks like operation, development, deployment and automation
  • Browser-based authentic shell experience
  • Blend of both Bash & PowerShell
  • It’s a linux container
  • It is fully configured and authenticated
  • It uses Microsoft Azure File Share for persistent storage
  • Ships with Azure PS Drive
  • In-built code editor (Monaco)
  • Accessible from anywhere (virtually)
  • Cloud Shell is updated and maintained by Microsoft

Pricing

  • There is no upfront cost
  • Pay only for storage

Access to Cloud Shell

Cloud Shell Basics (Demo)

shell.azure.com 

  • Setup your environment
  • Environment Walk-through
  • Azure PS Drive
  • PowerShell CmdLets
  • Get-AzContext
  • PSCloudShellUtility Module
  • Code Editor

Azure PowerShell Module

AzureRM -> Az

  • AzureRM Module(Before December' 2018)
    • Support through December' 2020
    • No new features, only bug fixes
    • Latest Version: 6.13.1
  • Az Module
    • Latest and greatest features
    • Enable-AzureRmAlias
    • Latest Version: 4.5.0

Installation (Demo)

Online Installation

## Open PowerShell
# To Check the latest version of Azure PowerShell
Find-Module -Name Az

# To install the Azure PowerShell 
Install-Module -Name Az
        # or
Find-Module -Name Az | Install-Module

# To update the Azure PowerShell
Install-Module -Name Az -Force
        # or 
Update-Module -Name Az

Offline Installation

Save-Module -Name Az -Path '\\server\share\PowerShell\modules' -Force

Connect to Azure Subscription (Demo)

Sign in interactively

# Import Module
Import-Module -Name Az
 
# Interactive Sign in
Connect-AzAccount
# Follow the screen and authenticate in the web browser
 
# Authentication valid only for current session
Connect-AzAccount -Scope Process

Sign in with a service principal



Azure PowerShell CmdLets (Demo)

Exploring various cmdlets

# List all the Azure PowerShell Module
Get-Module -Name Az.* -ListAvailable
 
# List the cmdlets in a specific module
Get-Command -Module Az.Resources
 
# Filter the cmdlets by verb or/and noun
Get-Command -Verb Get -Module Az.Resources
Get-Command -Verb Get -Noun *VM -Module Az.Compute 
Get-Command -Name *LoadBalancer* -Module Az.Network
<# Available Verbs in Az Module
Add, Clear, Disable, Edit, Enable, Export, Get, Import, Invoke, Join, List, Login, Logout, Move, New, 
Reactivate, Remove, Repair, Reset, Resolve, Restart, Restore, Resume, Save, Select, Set, Start, Stop, 
Submit, Suspend, Swap, Sync, Test, Update, Use, Validate, Wait, Disconnect, Register, Send, Unregister, 
Approve, Backup, Close, Complete, Confirm, Connect, Convert, ConvertTo, Deny, Enter, Grant, Initialize, 
Install, Lock, Publish, Rename, Resize, Revoke, Switch, Undo, Uninstall, Unpublish
#>
 
# Get help
Get-Help -Name New-AzVirtualNetwork # -Detailed, -Full, -Examples and -Online
 
# Get object members
$VM = Get-AzVm -ResourceGroup test-rg -Name TestVM
$VM | Get-Member

Fetching the required information

## Login to Azure
# Login-AzAccount

# Get the current subscription
Get-AzContext

# Get all the subscriptions in the current context
Get-AzContext -ListAvailable

# List all the subscriptions
Get-AzSubscription | Select-Object -Property Name, State

# To Switch between the subscriptions 
# Get-AzSubscription -SubscriptionId '<subscription name>' | Set-AzContext
Get-AzSubscription -SubscriptionName '<subscription name>' | Select-AzSubscription # Set-AzContext
Get-AzContext -Name '<context name>' | Select-AzContext
Set-AzContext -SubscriptionName '<subscription name>'


## Fetching the required information from Azure
# Get all the resources in the current context
Get-AzResource
Get-AzResource -Name '<resource name>'
Get-AzResource -ResourceId '<resource id>'
Get-AzResource -ResourceType '<resource type>' # Microsoft.Compute/virtualMachines, Microsoft.Storage/storageAccounts, Microsoft.Network/publicIPAddresses
Get-AzResource -Tag '<tag ht>' # -TagName, -Tag Value

# Get all the resource groups in the current context
Get-AzResourceGroup

# Get virtual machines
Get-AzVM
Get-AzVM -ResourceGroupName test-rg 
Get-AzVM -Location westus
Get-AzVM -ResourceGroupName test-rg -Name TestVM

# Get storage accounts
Get-AzStorageAccount -Name '<sa name>'
Get-AzStorageAccount

# Get virtual networks
Get-AzVirtualNetwork -Name '<vnet name>'
Get-AzVirtualNetwork -ResourceGroupName '<rg name>' -Name '<vnet name>'
Get-AzVirtualNetwork 

# Get network security group
Get-AzNetworkSecurityGroup -ResourceGroupName '<rg name>' -Name '<vnet name>'
Get-AzNetworkSecurityGroup

# Get network interface 
Get-AzNetworkInterface -ResourceId '<resource id>'
Get-AzNetworkInterface -ResourceGroupName '<rg name>' -Name '<nic name>'
Get-AzNetworkInterface

# Get azure locations
Get-AzLocation | ForEach-Object Location # DisplayName

# Get virtual machine sizes
Get-AzVMSize -Location southindia

## Finding the right OS image
# Get image publishers
Get-AzVMImagePublisher -Location westus     # MicrosoftWindowsServer, Canonical

# Get image offerings from the specified publisher
Get-AzVMImageOffer -Location southindia -PublisherName Canonical    # UbuntuServer, Ubuntu_Core # WindowsServer

# Get the image sku
Get-AzVMImageSku -Location southindia -PublisherName Canonical -Offer UbuntuServer  # 18.04-LTS, 18.10

# List security rules of a network security group
$NSG = Get-AzNetworkSecurityGroup -ResourceGroupName security-rg -Name nsg1
$NSG.SecurityRules
# or
Get-AzNetworkSecurityGroup -ResourceGroupName security-rg -Name nsg1 | Get-AzNetworkSecurityRuleConfig
# or
Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $NSG

# Fetch public ip address of a VM
$VM = Get-AzVM -ResourceGroupName test-rg -Name TestVM
$VM 
<#
ResourceGroupName  : test-rg
Id                 : /subscriptions/1b7eaa76-c64f-4a0f-b56f-10b25b056be3/resourceGroups/test-rg/providers/Microsoft.Compute/virtualMachines/SimpleVM
VmId               : 51c723bb-93d0-404e-be83-c32123f9d07d
Name               : SimpleVM
Type               : Microsoft.Compute/virtualMachines
Location           : eastus
Tags               : {}
DiagnosticsProfile : {BootDiagnostics}
HardwareProfile    : {VmSize}
NetworkProfile     : {NetworkInterfaces}
OSProfile          : {ComputerName, AdminUsername, LinuxConfiguration, Secrets, AllowExtensionOperations, RequireGuestProvisionSignal}
ProvisioningState  : Succeeded
StorageProfile     : {ImageReference, OsDisk, DataDisks}
#>
$NICId = $VM.NetworkProfile.NetworkInterfaces.id
$NIC = Get-AzNetworkInterface -ResourceId $NICId
# Private IP Address
$NIC.IpConfigurations.PrivateIpAddress

$PIPId = $NIC.IpConfigurations.PublicIpAddress.id
$PIP = Get-AzResource -ResourceId $PIPId
# Public IP Address
$PIP.Properties.ipAddress

## Working with the objects and formating the output
Get-AzResource | Select-Object -Property ResourceName, ResourceType, ResourceGroupName
Get-AzResource | Where-Object { $_.ResourceType -eq 'Microsoft.Compute/virtualMachines/extensions' }
Get-AzResource | Select-Object -Property ResourceName, ResourceGroupName | Sort-Object -Property ResourceGroupName

$Tag = @{crit = 4}
Get-AzResource | Where-Object { $null -eq $_.Tags } | ForEach-Object { New-AzTag -ResourceId $_.ResourceId -Tag $Tag }

# Format the output
Get-AzResource | Format-Table
Get-AzResource | Format-Table -Property ResourceName, ResourceGroupName
Get-AzResource | Select-Object -Property ResourceName, ResourceGroupName | Format-List

Creating & Configuring the Azure resources

### Create and configure the Azure resources

# Declare local variables
$ResourceGroupName = 'demo-rg'
$Location = 'westus'


## Create a new resource group
$DemoRG = New-AzResourceGroup -Name $ResourceGroupName -Location $Location 


## Create a new storage account
$SAName = "sa" + -join ((0x30..0x39) + ( 0x61..0x7A) | Get-Random -Count 8 | ForEach-Object { [char]$_ })   # Generate a random sa account name
$DemoSA = New-AzStorageAccount -ResourceGroupName $ResourceGroupName -Location $Location -Name $SAName -SkuName Standard_LRS


## Create a new network security group with RDP and Web allow security rules
$NSGName = 'demo-nsg'
$RDPRule = New-AzNetworkSecurityRuleConfig -Name allow-3389 -Priority 1000 -Protocol Tcp -Direction Inbound -Access Allow -SourcePortRange * -DestinationPortRange 3389 -SourceAddressPrefix * -DestinationAddressPrefix * 
$WebRule = New-AzNetworkSecurityRuleConfig -Name allow-80 -Priority 1010 -Protocol Tcp -Direction Inbound -Access Allow -SourcePortRange * -DestinationPortRange 80 -SourceAddressPrefix * -DestinationAddressPrefix * 
$DemoNSG = New-AzNetworkSecurityGroup -ResourceGroupName $ResourceGroupName -Location $Location -Name $NSGName -SecurityRules $RDPRule, $WebRule

# Remove a security rule from the existing NSG
Remove-AzNetworkSecurityRuleConfig -Name allow-80 -NetworkSecurityGroup $DemoNSG
$DemoNSG | Set-AzNetworkSecurityGroup

# Add a new a security rule from the existing NSG
Add-AzNetworkSecurityRuleConfig -Name allow-8080 -Priority 1010 -Protocol Tcp -Direction Inbound -Access Allow -SourcePortRange * -DestinationPortRange 8080 -SourceAddressPrefix * -DestinationAddressPrefix * -NetworkSecurityGroup $DemoNSG
$DemoNSG | Set-AzNetworkSecurityGroup


## Create a new virtual network
$VNetName = 'demo-vnet'
$VNetAddressPrefix = '192.168.0.0/16'
$SubnetName = 'subnet'
$SubnetAddressPrefix = '192.168.1.0/24'
$Subnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix -NetworkSecurityGroupId $DemoNSG.Id
$DemoVNet = New-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -Location $Location -Name $VNetName -AddressPrefix $VNetAddressPrefix -Subnet $Subnet

# Change address prefix of a subnet in the vnet
$SubnetAddressPrefix = '192.168.0.0/24'
$DemoVNet.Subnets.Where({ $_.Name -eq $SubnetName }).AddressPrefix = $SubnetAddressPrefix
$DemoVNet | Set-AzVirtualNetwork

# Add a new subnet to an existing vnet
$SubnetName2 = 'subnet2'
$SubnetAddressPrefix2 = '192.168.1.0/24'
Add-AzVirtualNetworkSubnetConfig -Name $SubnetName2 -AddressPrefix $SubnetAddressPrefix2 -NetworkSecurityGroupId $DemoNSG.Id -VirtualNetwork $DemoVNet
$DemoVNet | Set-AzVirtualNetwork


## Create a pubblic ip address
$PIPName = 'demo-pip'
$DemoPIP = New-AzPublicIpAddress -ResourceGroupName $ResourceGroupName -Location $Location -Name $PIPName -AllocationMethod Dynamic


## Create a new network interface card
$NICName = 'demo-nic'
$DemoNIC = New-AzNetworkInterface -ResourceGroupName $ResourceGroupName -Location $Location -Name $NICName -SubnetId $DemoVNet.Subnets[0].Id -PublicIpAddressId $DemoPIP.Id 

Deploy a complete virtual machine using Azure PowerShell

#### This is in continuation to create-configure-the-azure-resources.ps1
## In the previous script, we have already created ResourceGroup, NSG, VNet, StorageAccount, NIC with public ip

# Declare local variables
$RGName = 'demo-rg'
$Location = 'westus'
$VMName = 'demo-vm'
$ComputerName = 'demo-vm'
$VMSize = 'Standard_D2_v2'
$PublisherName = 'MicrosoftWindowsServer' 
$Offer = 'WindowsServer' 
$Sku = '2019-Datacenter' 
$AdminCredential = Get-Credential -UserName sysadmin

# Create VM configuration
$VMConfig = New-AzVMConfig -VMName $VMName -VMSize $VMSize

# Operating System configuration
$VMConfig | Set-AzVMOperatingSystem -Windows -ComputerName $ComputerName -Credential $AdminCredential

# VM Source Image Referance
$VMConfig | Set-AzVMOSDisk -CreateOption FromImage
$VMConfig | Set-AzVMSourceImage -PublisherName $PublisherName -Offer $Offer -Skus $Sku -Version latest

# Add NIC
$VMConfig | Add-AzVMNetworkInterface -Id $DemoNIC.Id -Primary

# Add Data Disk
$VMConfig | Add-AzVMDataDisk -DiskSizeInGB 1023 -Lun 0 -CreateOption Empty

# Enable Boot Diagnostics
$VMConfig | Set-AzVMBootDiagnostic -ResourceGroupName $RGName -Enable -StorageAccountName $DemoSA.Name

# Create Virtual Machine
New-AzVM -ResourceGroupName $RGName -Location $Location -VM $VMConfig

Thank you


About Cloud Shell https://azure.microsoft.com/en-in/features/cloud-shell/ 
Overview of Azure Cloud Shell https://docs.microsoft.com/en-in/azure/cloud-shell/overview 
Azure Cloud Shell https://github.com/Azure/CloudShell 
Features & tools for Azure Cloud Shell https://docs.microsoft.com/en-in/azure/cloud-shell/features 
Tools inside Cloud Shell https://docs.microsoft.com/en-us/azure/cloud-shell/features#tools 
Monaco Editor https://microsoft.github.io/monaco-editor/ 
Simple Hierarchy in PowerShell (SHiPS) https://github.com/PowerShell/SHiPS 
AzurePSDrive https://github.com/PowerShell/AzurePSDrive 
PowerShell https://github.com/PowerShell/PowerShell 
Windows Terminal https://github.com/microsoft/terminal 
Azure PowerShell https://github.com/Azure/azure-powershell 
https://www.powershellgallery.com/packages/Az/ 
Azure PowerShell MSI https://github.com/Azure/azure-powershell/releases/latest 
Azure PowerShell documentation https://docs.microsoft.com/en-in/powershell/azure 
Migrate Azure PowerShell from AzureRM to Az https://docs.microsoft.com/en-in/powershell/azure/migrate-from-azurerm-to-az 
Install Azure PowerShell https://docs.microsoft.com/en-in/powershell/azure/install-az-ps 
PowerShell Module Browser https://docs.microsoft.com/en-in/powershell/module/?view=azps-4.5.0 
Sign in with Azure PowerShell https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps 
Create an Azure service principal with Azure PowerShell https://docs.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps 
Azure PowerShell context objects https://docs.microsoft.com/en-in/powershell/azure/context-persistence 
Azure PowerShell - Microsoft Learn https://docs.microsoft.com/en-us/learn/modules/automate-azure-tasks-with-powershell 

Last modified: 30 October 2020

Share it on     |   |   |   | 
comments powered by Disqus