Thursday, 22 December 2016

Prepare/Generalize an Ubuntu Virtual Machine for Azure


Prerequisites

Install an Ubuntu Linux operating system to a virtual hard disk.

Ubuntu installation notes:
  • The VHDX format is not supported in Azure, only fixed VHD. You can convert the disk to VHD format using Hyper-V Manager or the convert-vhd cmdlet.
  • When installing the Linux system, it is recommended that you use standard partitions rather than LVM (often the default for many installations). This will avoid LVM name conflicts with cloned VMs, particularly if an OS disk ever needs to be attached to another VM for troubleshooting. LVM or RAID may be used on data disks if preferred.
  • Do not configure a swap partition on the OS disk. The Linux agent can be configured to create a swap file on the temporary resource disk. More information about this can be found in the steps below.
  • All of the VHDs must have sizes that are multiples of 1 MB.
STEPS:
1.       In the center pane of Hyper-V Manager, select the virtual machine.
2.      Click Connect to open the window for the virtual machine.
3.      Replace the current repositories in the image to use Ubuntu's Azure repos. The steps vary slightly depending on the Ubuntu version.
  
 Before editing /etc/apt/sources.list, it is recommended to make a backup:

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak


  #sudo sed -i "s/[a-z][a-z].archive.ubuntu.com/azure.archive.ubuntu.com/g" /etc/apt  /sources.list

         sudo apt-get update


4.      Update the operating system to the latest kernel by running the following commands:

# sudo apt-get update


# sudo apt-get install linux-image-virtual


 (recommended) sudo apt-get dist-upgrade



       Once all the above necessary packages were install, make sure to reboot your Linux box

 # sudo reboot

5.      Modify the kernel boot line for Grub to include additional kernel parameters for Azure. To do this open "/etc/default/grub" in a text editor, find the variable called GRUB_CMDLINE_LINUX_DEFAULT (or add it if needed) and edit it to include the following parameters:

                  GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0,115200n8                                 earlyprintk=ttyS0,115200 rootdelay=300"


Save and close this file, and then run 'sudo update-grub'. This will ensure all console messages are sent to the first serial port, which can assist Azure technical support with debugging issues.

#sudo update-grub

6.      Ensure that the SSH server is installed and configured to start at boot time. This is usually the default. 

7.      Install the Azure Linux Agent:

        # sudo apt-get update
        # sudo apt-get install walinuxagent


Note: Installing the walinuxagent package will remove the NetworkManager and NetworkManager-gnome packages, if they are installed.

8.      The Azure Linux Agent can automatically configure swap space using the local resource disk that is attached to the VM after provisioning on Azure. Note that the local resource disk is a temporary-disk, and might be emptied when the VM is deprovisioned.

After installing the Azure Linux Agent (see previous step), modify the following parameters in /etc/waagent.conf appropriately:

          #vi /etc/waagent.conf


      ResourceDisk.Format=y
      ResourceDisk.Filesystem=ext4
      ResourceDisk.MountPoint=/mnt/resource
      ResourceDisk.EnableSwap=y
      ResourceDisk.SwapSizeMB=2048    


## NOTE: set this to whatever values you need it to be.

9.      Run the following commands to deprovision the virtual machine and prepare it for provisioning on Azure:

sudo waagent -force -deprovision
export HISTSIZE=0
logout / exit



10. Click Action -> Shut Down in Hyper-V Manager. Your Linux VHD is now ready to be uploaded to Azure.

You're now ready to use your Ubuntu Linux virtual hard disk to create new virtual machines in Azure.

Wednesday, 21 December 2016

Connect to Office 365 using PowerShell

Connect to Office 365 using PowerShell


Step 1: Install required software

These steps are required once on your computer, not every time you connect. However, you'll likely need to install newer versions of the software periodically.

1.      Install the 64-bit version of the Microsoft Online Services Sign-in Assistant: Microsoft Online Services Sign-in Assistant for IT Professionals RTW.

2.      Install the 64-bit version of the Windows Azure Active Directory Module for Windows PowerShell: Windows Azure Active Directory Module for Windows PowerShell (64-bit version).

Step 2: Open the Windows Azure Active Directory Module


1.      Find and open the Windows Azure Active Directory Module for Windows PowerShell by using one of the following methods based on your version of Windows:
o    Start menu   On the Start menu, enter Azure in the Search programs and files box.
o    No Start menu   Search for Azure using any of these methods:
o    On the Start screen, click an empty area, and type Azure.
o    On the desktop or the Start screen, press the Windows key+Q. In the Search charm, type Azure.
o    On the desktop or the Start screen, move your cursor to the upper-right corner, or swipe left from the right edge of the screen to show the charms. Select the Search charm, and enter Azure.

2.      In the results, select Windows Azure Active Directory Module for Windows PowerShell.

Or you can start -à Powershell ISE

Step 3: Connect to your Office 365 subscription


1.      In the Windows Azure Active Directory Module for Windows PowerShell, run the following command.

2.  $Cred = Get-Credential

In the Windows PowerShell Credential Request dialog box, type your Office 365 work or school account user name and password, and then click OK.

3.      Run the following command.

4.  Connect-MsolService -Credential $Cred

5.  Import-Module MSOnline

6.  Set-ExecutionPolicy RemoteSigned -Force

7.  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
-Credential $Cred -Authentication Basic -AllowRedirection


8.  Import-PSSession $Session -AllowClobber

Moving Azure Resources from one Subscription to Another in Same Tenant


Moving Azure Resources from one Subscription to Another in Same Tenant


Login-AzureRmAccount

Get-AzureRmSubscription

$subsId=Select-AzureRmSubscription -SubscriptionId "your Subscription ID xxxxx"

Get-AzureRMResource -ResourceName "Source Resource_Name" -ResourceGroupName "Source_Resource_Group"

Move-AzureRMResource -DestinationResourceGroupName "Resource_Move" -DestinationSubscriptionId "Destination Subscription ID xxxxx"



Note: This works only if both the subscriptions are under in same Tenant ID.

Powershell Script to view / check the status of VMs in a Subscription



Powershell Script to view / check the status of VMs in a Subscription



Login-AzureRmAccount

$RGs = Get-AzureRMResourceGroup

foreach($RG in $RGs)
{
    $VMs = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName
    foreach($VM in $VMs)
    {
        $VMDetail = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName -Name $VM.Name -Status
        foreach ($VMStatus in $VMDetail.Statuses)
        {
            #if($VMStatus.Code.CompareTo("PowerState/deallocated") -eq 0)
            if($VMStatus.Code -like "PowerState/*")
            {
                $VMStatusDetail = $VMStatus.DisplayStatus
            }
        }
        write-output $VM.Name $VMStatusDetail
    }
}



Automation PS Workflow to Start or Stop VMs Simultaneously

#PowerShell Script to Create Automation Account and Import RunBook!

Run Book which will start or stop VMs Simultaneously 


#Select-AzureRmProfile -Path 'C:\Users\gulab\Desktop\Text\Azure Scripts\Login\hotmail.txt'

Login-AzureRmAccount

$ResourceGroup = "Automation-SorStVMs"
$AutomationAcct = "cloudsupport"
$runbookName = "startORstop"
$scheduleName1 = "Start"
$scheduleName2 = "Stop"

New-AzureRmResourceGroup -Name $ResourceGroup -Location 'southeastasia'

New-AzureRmAutomationAccount -Name $AutomationAcct -ResourceGroupName $ResourceGroup -Location 'southeastasia'

New-AzureRmAutomationRunbook -Name startORstop -Type PowerShellWorkflow `
-Description "Start or Stop all VMs in a Subscription Parallely" `
-ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAcct


#Import-AzureRmAutomationRunbook -AutomationAccountName $AutomationAcct `
#-ResourceGroupName $ResourceGroup -Path 'C:\Users\gulab\Desktop\Text\Azure Scripts\startORstop.ps1' `
#-Type PowerShellWorkflow -Description "Parallel Start or Stop All VMs"


#Once you are done creating empty RunBook, copy the below attached .ps workflow script into empty RunBook and save the runbook.


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


workflow startORstop
{
   Param
    (

        [Parameter(Mandatory=$true)]
        [String]
        $ResourceGroupName = '*',

        [Parameter(Mandatory=$true)]
        [Boolean]
        $Shutdown
    )
    $connectionName = "AzureRunAsConnection"
    try
    {
    
        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

        "Logging in to Azure..."
        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
        }
    }

    If ($ResourceGroupName -eq '*')
    {
        $vms = Get-AzureRmVM
        Foreach -Parallel ( $vm in $vms ) 
        {
                        
            if ( $Shutdown ) 
            {
                Write-Output "Stopping $($vm.Name)";              
                Stop-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force;
            }

            else 
            {
                Write-Output "Starting $($vm.Name)";                
                Start-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName;
            }
        }

    }
    
    Else
    {
        $vms = Get-AzureRmVM -ResourceGroupName $ResourceGroupName;   

        Foreach -Parallel ( $vm in $vms ) 
        {                        
            if ( $Shutdown ) 
            {
                Write-Output "Stopping $($vm.Name)";              
                Stop-AzureRmVm -Name $vm.Name -ResourceGroupName $ResourceGroupName -Force;
            }

            else 
            {
                Write-Output "Starting $($vm.Name)";                
                Start-AzureRmVm -Name $vm.Name -ResourceGroupName $ResourceGroupName;
            }
        }
    }

}

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




Publish-AzureRmAutomationRunbook -ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAcct -Name "startORstop"


New-AzurermAutomationSchedule –AutomationAccountName $AutomationAcct `
–Name $scheduleName1 –StartTime "11/26/2016 08:45:00 AM" -TimeZone "UTC+05:30" `
–DayInterval 1 -ResourceGroupName $ResourceGroup -Description "Parallel Start all VMs"


New-AzurermAutomationSchedule –AutomationAccountName $AutomationAcct `
–Name $scheduleName2 –StartTime "11/26/2016 07:00:00 PM" -TimeZone "UTC+05:30" `
–DayInterval 1 -ResourceGroupName $ResourceGroup -Description "Parallel Stop all VMs"
To link a schedule to a runbook with the Azure Portal to Start VMs
1.      In the Azure portal, from your automation account, click the Runbooks tile to open the Runbooks blade.
2.      Click on the name of the runbook to schedule.
3.      Click on Schedule Tile
4.      If the runbook is not currently linked to a schedule, then you will be given the option to create a new schedule or link to an existing schedule (Start).
5.      Click on Add a Schedule à Schedule (Link a schedule to your runbook) à Select the Existing Schedule (Start)
6.      The runbook has parameters, you can select the option à Click Configure Parameters and Run Settings à RESOURCEGROUPNAME “Leave it” Blank à Shutdown (Select False), and OK & OK to Link your schedule with your runbook.



To link a schedule to a runbook with the Azure Portal to Stop VMs
7.      In the Azure portal, from your automation account, click the Runbooks tile to open the Runbooks blade.
8.      Click on the name of the runbook to schedule.
9.      Click on Schedule Tile
10.  If the runbook is not currently linked to a schedule, then you will be given the option to create a new schedule or link to an existing schedule (Stop).
11.  Click on Add a Schedule à Schedule (Link a schedule to your runbook) à Select the Existing Schedule (Stop)
12.  The runbook has parameters, you can select the option à Click Configure Parameters and Run Settings à RESOURCEGROUPNAME “Leave it” Blank à Shutdown (Select True), and OK & OK to Link your schedule with your runbook.




Monday, 19 December 2016

List out AzureRM Operating Systems available

#Below command lists the Image Publishers available in the Specified location
Get-AzureRmVMImagePublisher -Location 'Southindia'

#Below command lists the Offer(offer means Windows flavour category) available with the Publishername
Get-AzureRmVMImageOffer -Location 'Southindia' -PublisherName 'MicrosoftWindowsServer'

#Below command lists the available SKU's under windows server
Get-AzureRmVMImagesku -Location 'Southindia' -PublisherName 'MicrosoftWindowsServer' -Offer 'windowsserver'

#Below command lists the version of the sku
Get-AzureRMVMImage -location 'Southindia' -publisherName "MicrosoftWindowsServer" -sku "2012-R2-Datacenter" -Offer 'windowsserver'

#Below Command lists the detials of the particual sku.
Get-AzureRMVMImage -location 'Southindia' -publisherName "MicrosoftWindowsServer" -sku "2012-R2-Datacenter" -Offer 'windowsserver' -Version '4.0.20161214'

Get SSL Certificate Expiry Notification on Mail.

 There are multiple ways to get SSL Certification expiry details/alert. We all know if our SSL certificate get expire, how critical situatio...