Big Bank Weekend Project


 

 

 

Converting Azure PowerShell scripts to Linux Scripts.

In one of my recent customer engagements, I was demonstrating the capabilities of Azure HPC and Azure Batch. During the meeting the customer mentioned that as much as they liked the Windows PowerShell environment, they use Linux for undertaking most of their HPC compute requirements and would like to see the same running in the Linux environments.

What it means is it’s time to get the Azure Cross-Platform Command-line interface (Cli) a whirl and with the big weekend break coming up, it was time for a mini-project.

Project objective: ‘Convert and successfully execute Windows PowerShell script in the Linux environment’

Engagement Constraints:

-          Be as native as possible – meaning shell scripts only and utilising no-browser on Linux or on Windows. 

-          No Desktop installation on Linux variants. I personally don’t believe in installing Desktops on Linux servers as it sorts of defeats the purpose.

Migration Script

First let’s take a moment to review the source PowerShell script that needs to be migrated.

At a very high level, the script creates six Linux ‘Ubuntu 2015 LTS’ ‘Medium’ instances inside a Virtual network and under a specific Subnet.

The complete script, is repeated in here

#CreateLinuxVirtualMachines

azure config mode asm

# The Subscription name that we want to create our environment in

$SubscriptionNameId = "<your-subscription-id-guid>"

# Storage account name. This should already be created

$StorageAccountname = "<you-storage-account-name>"

# AffinityGroup name. This should already exist before the script is executed

$AffinityGroup = "linuxdistros"

# Network name. Should already be created

$VnetName = "linuxdistronetwork"

# Subnetname. Should exists before the script is executed.

$SubnetName = "Subnet-1"

# Availability Set

$AvailabilitySetName = "linuxdistro"

# Cloud Service name. This service will be created

$CloudServiceName = "<your-cloud-service-name-here>"

# Instance size

$InstanceSize = "Medium"

# Linux Admin Username

$password = "<your password here>"

# Linux Admin Password

$username = "linuxuser"

# Name Prefix of the VM machine name. Numeric counter number is appended to this to create the final VM name

$LinuxImageNamePrefix = "linuxdistro-0"

# Load the certificate keys for us to login to

$LoadSettings = Import-AzurePublishSettingsFile "NinadKNew.publishsettings"

# Important to specify the CurrentStorageAccountName, especially otherwise you might get Storage not accessible error when creating Linux machines.

Set-AzureSubscription -SubscriptionId $SubscriptionNameId -CurrentStorageAccountName $StorageAccountname -ErrorAction Stop

Select-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

 

# Get the image from Azure repository that we want to create. Its the Ubuntu 14_04_LTS variant. We can speed up the creation script by caching the name.

# the name obtianed is 'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB'

$UbuntuImage = Get-AzureVMImage | where {($_.ImageName -match 'Ubuntu-14_04') -and ($_.ImageName -match '2015') -and ($_.ImageName -match 'LTS') -and ($_.Label -eq 'Ubuntu Server 14.04.2.LTS')} | Select ImageName

Write-Host $UbuntuImage[0].ImageName

 

# If the service does not exist, we'll create one.

$GetCloudService = Get-AzureService -ServiceName $CloudServiceName -Verbose -ErrorAction Continue

if (!$GetCloudService )

{

    # service does not exist.   

    $CreateCloudService = New-AzureService -ServiceName $CloudServiceName -AffinityGroup $AffinityGroup -Label "Created from Windows power shell" -Description '13 April 2014'

    Write-Host ("Return value from creating the cloud service = {0}" -f $CreateCloudService.OperationStatus.ToString())

}

$Counter = 1

# Loop to create the Linux machines.

do

{

    # Prepend the VM name

    $LinuxImagename = $LinuxImageNamePrefix + $Counter.ToString()

    # Configure VM by specifying VMName, Instance Size, ImageName, AvailabilitySet and specify AzureSubnet

    $VMNew = New-AzureVMConfig -Name $LinuxImagename -InstanceSize $InstanceSize -ImageName $UbuntuImage[0].ImageName -AvailabilitySetName $AvailabilitySetName | Set-AzureSubnet $SubnetName

    # Add the username and password to the VM creation configuration

    $VMNew | Add-AzureProvisioningConfig -Linux -LinuxUser $username -Password $password

    # Create and start the VM. Remember, it won't be fully provisioned when the call returns.   

    $Result = $VMNew | New-AzureVM -ServiceName $CloudServiceName -VNetName $VnetName

    Write-Host ("Created VM Image {0}, return value = {1}" -f $LinuxImagename, $Result.OperationStatus )

    $Counter++

}

while ($Counter -le 6)

Figure 1: Migration Source Script

 

Note:

Script assumes that following entities already exists within the Azure subscription environment –

§  Valid Azure account: The subscription id of the valid subscription under the account is contained in the variable $SubscriptionNameId 

§   Affinity group: Name of the affinity group is contained in the cmdlet variable $AffinityGroup

§   Network: Azure network should be pre-created with a subnet. The VNet name is contained in the variable $VnetName  and subnet name is contained in the variable $SubnetName

§   Storage account: Valid storage account to host and create Azure VMs should already exist. The name of the storage account is contained in the variable - $StorageAccountname

If the cloud service does not exists, script will create one ($CloudServiceName) and the virtual machines will be created inside the affinity group ($AvailabilitySetName).

·         To connect to my Azure subscription, I use Import-AzurePublishSettingsFile cmdlet. You will need to execute Get-AzurePublishSettingsFile cmdlet first to download the file.

·         The script uses Get-AzureVMImage cmdlet and then filters it to get the name of the VM image that we want to create.  Instead of retrieving the image name, one could instead use the complete name directly instead – ‘'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB

·         Script uses New-AzureVMConfig  and AzureProvisioningConfig cmdlets to configure the Linux VMs and finally create a Linux VM using cmdlet New-AzureVM

·         The script to clean the environment is available here

Create Linux Host and establish connection

Now we need to create a Linux host that will be used as a host for running our scripts. We use a simple script to create the VM.

Once the VM has been created and provisioned, we access the provisioned VM by finding out the public port the VM is running and using DNS name to connect. We can find out the public port by using cmdlet Get-AzureEndpoint as shown in the following example.

$VMEndpoints = Get-AzureVM -ServiceName $CloudServiceName -Name $LinuxImagename | Get-AzureEndpoint

if ($VMEndpoints)

{

    foreach($item in $VMEndpoints)

    {

        if ($VMEndpoints.Name.Equals('SSH'))

        {

            Write-host ("{0}.cloudapp.net:{1}" -f $CloudServiceName, $item.Port)

        }

    }

}

Figure 2: Get-AzureEndPoint Script

 

Note:

Complete script of the above example is copied here.

Outside the virtual network, public DNS name of the VM is made up of <your-cloud-service-name> + ‘cloudapp.net’

The output of the above script shows the DNS name and the public port to connect to the Linux machine.

Now we need an SSH client to connect to the Linux VM. I’ll use PuTTY for our example. You can download PuTTY client from https://aka.ms/putty.  Enter the DNS address and port number and click Open as shown in the screen snapshot below

image3.jpg

Figure 3: PuTTY Login screen

When you connect for the first time, you’ll see some security warnings, similar to the ones that get displayed when using a RDP connection. Click continue.

Enter username and password credentials on the PuTTY connection window. These are the same credentials that you used when you created the VM. It is important to note that you’d be logging in as pseudo root user.

If the login is successful, you would be in the Linux world. Welcome.

login as: linuxuser

linuxuser@<Removed>.cloudapp.net's password:

Welcome to Ubuntu 14.04.2 LTS (GNU/Linux 3.16.0-31-generic x86_64)

* Documentation:  https://help.ubuntu.com/

  System information as of Mon Apr 13 21:31:13 UTC 2015

  System load:  0.0               Processes:           235

  Usage of /:   2.7% of 28.80GB   Users logged in:     0

  Memory usage: 3%                IP address for eth0: 100.78.2.22

  Swap usage:   0%

  Graph this data and manage this system at:

    https://landscape.canonical.com/

  Get cloud support with Ubuntu Advantage Cloud Guest:

    http://www.ubuntu.com/business/services/cloud

0 packages can be updated.

0 updates are security updates.

Last login: Mon Apr 13 21:31:14 2015 from <Removed>

linuxuser@ubuntuhost:~

Figure 4: Linux Login Screen

Install Azure Cross-Platform Cli on Linux Machine

All the commands that you would now execute would be at ‘root’ level privileges. To execute commands at elevated privileges, on the command prompt, prefix each command with ‘sudo’ keyword. ‘sudo’ stands for ‘super user do’. To execute a command, you specify the command after this keyword.

First we need to install the Azure cross-platform Command Line Interface (Cli). The instructions for the same can are available from here.

First execute two commands to download the latest updates and upgrade the machine.

linuxuser@ubuntuhost:~$ sudo apt-get update

linuxuser@ubuntuhost:~$ sudo apt-get upgrade

Figure 5: Linux VM Update and Upgrade

Click [Y] for confirmation to upgrade

Next install the Azure cross-platform Cli environment by executing following three commands

linuxuser@ubuntuhost:~$ sudo apt-get install nodejs-legacy

linuxuser@ubuntuhost:~$ sudo apt-get install npm

linuxuser@ubuntuhost:~$ sudo npm install -g azure-cli

Figure 6: Install azure-cli

First command installs the compatible node.js environment. Second command installs the azure client library for node. This library provides a Node.js package that makes it easy to consume and manage Azure services. Last command installs the azure cross-platform Cli using npm.

Now let’s test the installation. Entering ‘azure’ on the command line should display us the cli banner – as shown.

linuxuser@ubuntuhost:~$ azure

info:             _    _____   _ ___ ___

info:            /_\  |_  / | | | _ \ __|

info:      _ ___/ _ \__/ /| |_| |   / _|___ _ _

info:    (___  /_/ \_\/___|\___/|_|_\___| _____)

info:       (_______ _ _)         _ ______ _)_ _

info:              (______________ _ )   (___ _ _)

info:

info:    Microsoft Azure: Microsoft's Cloud Platform

info:

info:    Tool version 0.8.17

help:

help:    Display help for a given command

help:      help [options] [command]

help:

help:    Log in to an Azure subscription using Active Directory. Currently, the user can login only via Microsoft organizational account

help:      login [options]

help:

help:    Log out from Azure subscription using Active Directory. Currently, the user can log out only via Microsoft organizational account

help:      logout [options] [username]

help:

help:    Open the portal in a browser

help:      portal [options]

help:

help:    Commands:

help:      account        Commands to manage your account information and publish settings

help:      config         Commands to manage your local settings

help:      hdinsight      Commands to manage your HDInsight accounts

help:      mobile         Commands to manage your Mobile Services

help:      network        Commands to manage your Networks

help:      sb             Commands to manage your Service Bus configuration

help:      service        Commands to manage your Cloud Services

help:      site           Commands to manage your Web Sites

help:      sql            Commands to manage your SQL Server accounts

help:      storage        Commands to manage your Storage objects

help:      vm             Commands to manage your Virtual Machines

help:

help:    Options:

help:      -h, --help     output usage information

help:      -v, --version  output the application version

linuxuser@ubuntuhost:~$

Figure 7: Test Azure Cli Installation

Connecting to Azure Account from Linux Machine

There are two ways to connect to the Azure account from the cli environment.

·         Account based authentication: using ‘azure login’ commands

·         Certificate based authentication: using ‘azure account download’ commands

linuxuser@ubuntuhost:~$ azure login

info:    Executing command login

warn:    Please note that currently you can login only via Microsoft organizational account or service principal. For instructions on how to set them up, please read https://aka.ms/Dhf67j.

Username: <Details Removed>@microsoft.com

Password: ************

-info:    Added subscription <Details Removed>

info:    Setting subscription <Details Removed> as default

info:    Added subscription <Details Removed> Subscription

info:    Added subscription <Details Removed>

+

info:    login command OK

linuxuser@ubuntuhost:~$ azure logout -u <Details Removed>@microsoft.com

info:    Executing command logout

info:    You have logged out.

info:    logout command OK

linuxuser@ubuntuhost:~$ azure account download

info:    Executing command account download

info:    Launching browser to http://go.microsoft.com/fwlink/?LinkId=254432

help:    Save the downloaded file, then execute the command

help:      account import <file>

info:    account download command OK

linuxuser@ubuntuhost:~$

Figure 8: Login to Azure from Linux Machine

Note: A good comparison between the two approaches of authentication is provided here

Now one challenge that I encountered with running the azure cmdlets on the Linux environment was that although the second command reported success, as there is no browser installed on the machine, the second command does not work. The Linux machine VM does not have Desktop installed, no browser installed and therefore the certificate file cannot be downloaded.

Cunning Plan – Azure File share.

We would download the certificate file on a Windows client machine, and upload it on a file share and download it onto this Linux VM.

We would use Azure Files service to achieve this aim as it provides the ideal – SMB – environment to achieve this.

In order to achieve that we need to carry out following steps

1.      Create an Azure File share

2.      Upload the file to Azure File share

The script to carry out Steps 1 and 2 is copied here. The script creates the Azure File share by utilising New-AzureStorageShare and New-AzureStorageDirectory  cmdlets.

Note:

Azure File is currently in preview and you’ll need to request access from the azure preview page. Azure Files allows Virtual Machines (VMs) in an Azure Data Centre to mount a shared file system using the SMB protocol.

Copying and storing the Azure certificate file in an online storage poses security risk. It is recommended that the share and the uploaded file be closed as soon as the file has been downloaded on to the Linux box.

3.      Mount the shared folder in the Linux machine

4.      Download the file onto Linux machine

linuxuser@ubuntuhost:~$ mkdir Share

linuxuser@ubuntuhost:~$ pwd

/home/linuxuser

linuxuser@ubuntuhost:~$ sudo mount.cifs //<your-file-storage-name>.file.core.windows.net/linuxshare/share /home/linuxuser/Share -o vers=2.1,username=<your-file-storage-name>,password=<your-password-key-ending-with ==>,dir_mode=0777,file_mode=0777

linuxuser@ubuntuhost:~$ cp ./Share/NinadKNew.publishsettings ./Script

linuxuser@ubuntuhost:~$ ls -l ./Script

total 12

-rwxrwxr-x 1 linuxuser linuxuser   76 Apr 14 11:16 createvm.sh

-rwxrwxr-x 1 linuxuser linuxuser 7503 Apr 14 19:32 NinadKNew.publishsettings

linuxuser@ubuntuhost:~$

Figure 9: Linux mount file share and download file commands

In the Linux shell, we first create a folder ‘Share’, next we mount the Azure File shared folder on the ‘Share’ folder using mount.cifs command. After the mount has been successful, we copy the file from the Share to the local scripts folder.

Note: if cifs is not installed on the server, it can be installed using the following command

linuxuser@ubuntuhost:~$ sudo apt-get install cifs-utils

You can un mount the Share using the following ‘umount’ command

sudo umount /home/linuxuser/Share

Create Equivalent UNIX Script

Now we are ready to create our cli script.  First let’s create a folder where the script file will reside and create the skeleton shell file using the famous text editor – ‘VI’.

linuxuser@ubuntuhost:~$ pwd

/home/linuxuser

linuxuser@ubuntuhost:~$ mkdir Script

linuxuser@ubuntuhost:~$ cd Script

linuxuser@ubuntuhost:~/Script$ pwd

/home/linuxuser/Script

linuxuser@ubuntuhost:~/Script$ echo $SHELL

/bin/bash

linuxuser@ubuntuhost:~/Script$ vi createvm.sh

Figure 10: Start Creating UNIX equivalent script -1

Inside the VI editor, insert following line [VI Command àEsc i]

#!/bin/bash

echo 'This script will create Linux VMs in Azure subscription'

Figure 11: UNIX script inside VI

The first line in the script informs the system that it’s a script file and that the shell to be used for this is /bin/bash. This value is contained in the environment variable $SHELL.

Save the script file [VI command àEsc:wq] and change its mode to indicate it’s an executable. Finally execute the file from the command line.

linuxuser@ubuntuhost:~/Script$ vi createvm.sh

linuxuser@ubuntuhost:~/Script$ chmod +x createvm.sh

linuxuser@ubuntuhost:~/Script$ ls -l

total 4

-rwxrwxr-x 1 linuxuser linuxuser 76 Apr 14 11:16 createvm.sh

linuxuser@ubuntuhost:~/Script$ ./createvm.sh

This script will create Linux VMs in Azure subscription

linuxuser@ubuntuhost:~/Script$

Figure 12: Create and Test Linux Script

The Linux script is divided into two parts.

The first parts uses the standard UNIX stream find tools to get the azure image name. The second script creates the six Linux VMs just as the original Windows script did.

In the first script, Azure account based authentication is used as that is the only valid option. In the second script, Azure certificate based authentication is used.

#!/bin/bash

 echo 'This script will output the name of the Linux image file'

#Login using account subscription and not with certificate login

 azure login -u '<REMOVED>@microsoft.com' -p '<REMOVED>'

IMAGENAME =$(azure vm image list | grep 'Ubuntu-14_04_2' | awk '{print $2}')

 echo $IMAGENAME

 azure logout -u '<REMOVED>@microsoft.com'

Figure 13: UNIX Script 1

Script first logins to the Azure account using cmdlet azure login . After a successful login, we get the list of all the Azure images and pipe the result to UNIX grep and awk command. Script display’s the captured image name on the console window and then finally logout (azure logout) from the Azure account.

 

The output from the first script -

b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB’ is the image name of the Ubuntu virtual machine and it’s used in the second script to create all the virtual machines.

 

#!/bin/bash

echo 'This script will create Linux VMS in Azure subscription'

IMAGENAME='b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB'

SF="/home/linuxuser/Share/NinadKNew.publishsettings"

SUBSID='<your-subscription-id>'

STORAGEACCNAME="<your-storage-account-name>"

AVAILABILITYSET="linuxdistroset"

AFFINITYGROUP="linuxdistros"

CLOUDSERVICENAME="<your-cloud-service-name>"

VNETNAME="linuxdistronetwork"

SUBNETNAME="Subnet-1"

INSTANCESIZE="Medium"

PASSWORD="<your-password>"

USERNAME="linuxuser"

# Load the certificate file to login to azure account

azure account import $SF

# select the appropriate subscription

azure account set $SUBSID

# Let’s select the appropriate storage

azure storage account set $STORAGEACCNAME

FILENAMEPREFIX='linuxdistro-0'

COUNTER=1

while [ $COUNTER -lt 7 ]

do

 TEMPFILENAME=$FILENAMEPREFIX$COUNTER

 # echo $TEMPFILENAME

 # echo current value of counter is $COUNTER

if [ $COUNTER -eq 1 ]

then

        echo Creating first VM

        azure vm create -n $TEMPFILENAME -z $INSTANCESIZE -A $AVAILABILITYSET -w $VNETNAME -a $AFFINITYGROUP -b $SUBNETNAME $CLOUDSERVICENAME $IMAGENAME $USERNAME $PASSWORD

else

        echo Creating next VM

        azure vm create -n $TEMPFILENAME -z $INSTANCESIZE -A $AVAILABILITYSET -w $VNETNAME -b $SUBNETNAME -c $CLOUDSERVICENAME $IMAGENAME $USERNAME $PASSWORD

fi

 COUNTER=$(($COUNTER+1))

done

Figure 14: UNIX Script 2

We use the downloaded certificate file and consume the cmdlet azure account import to login to the Azure subscription. Next we set the appropriate subscription (azure account set) and azure storage (azure storage account)

The above Bash script creates Ubuntu instances using cmdlet azure vm create. Script uses normal Bash keywords and constructs to iterate through and create the require number of VM instance. Whilst creating the first instance we pass extra parameter ($AFFINITYGROUP) because the cloud service is not yet created. 

Conclusion

 

Microsoft Azure cross-platform cli makes it a real breeze to use the Linux shell environment to execute Azure cmdlets. It does not have all the intellisense and debugging support that Windows PowerShell ISE provides but in the hands of a familiar UNIX person, that should not be a deterrence.

Proof: - and yes I am aware that I am moving away from my goal of staying away from any GUI – but just to confirm the results, we will use the Azure management portal and see that our Linux instances are up and running.

image2.jpg

Figure 15: Virtual instance running under service account

image3.jpg

Figure 16: Virtual instances running under network configuration

Note: Please make sure you stop and clean your installation otherwise any they will incur cost to your subscription. The script to clean the environment is provided here.

 

Scripts

Clean-Up Script

# CleanLinuxVirtualMachines

# The Subscription name that we want to create our environment in

$SubscriptionNameId = "<Account subscription id>"

# Cloud Service name. This service will be created

$CloudServiceName = "<cloud-service-name>"

# Name Prefix of the VM machine name. Numeric counter number is appended to this to create the final

$LinuxImageNamePrefix = "linuxdistro-0"

# Load the keys for us to login to

Import-AzurePublishSettingsFile "NinadKNew.publishsettings"

Set-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

Select-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

$Counter = 1

$AllVmsStopped = 1

do

{

    # Prepend the VM name

    $LinuxImagename = $LinuxImageNamePrefix + $Counter.ToString()

    Write-Host ("VM Image name = {0}" -f $LinuxImagename)

    $VMPresent = Get-AzureVM -ServiceName $CloudServiceName -Name $LinuxImageName

    if ($VMPresent)

    {

        if ($VMPresent.Status -eq "StoppedVM" -or $VMPresent.Status -eq "StoppedDeallocated" )

        {

            Write-Host ("{0} VM is either stopped or StoppedDeallocated" -f $LinuxImagename )

        }

        else

        {

            Write-Host ("[Stopping] VM {0}" -f $VMPresent.Name)

            $StopVM = Stop-AzureVM -Name $VMPresent.Name -ServiceName $VMPresent.ServiceName -Force

            if ($StopVM.OperationStatus.Equals('Succeeded'))

            {

                Write-Host ("[Removing] virtual machine {0}" -f $VMPresent.Name)

                Remove-AzureVM -Name $VMPresent.Name -ServiceName $VMPresent.ServiceName

            }

            else

            {

                Write-Host ("Not able to stop virtual machine {0}, cloud service will not be removed" -f $VMPresent.Name)

                $AllVmsStopped = 0  

            }

        }

    }

    else

    {

        Write-Warning ("No Vm found " -f $LinuxImageName)

    }

    $Counter++

}

while ($Counter -le 6)

 

#Remove the cloud service now

# only if we were albe to stop all running ones

if ($AllVmsStopped -eq 1)

{

    # is it present

    $CloudServicesPresent = Get-AzureService -ServiceName $CloudServiceName -ErrorAction Continue

    if ($CloudServicesPresent)

    {

        $ResultRemoveCloudService = Remove-AzureService -ServiceName $CloudServiceName -Force

    }

    else

    {

        Write-Warning ("No {0} cloud service found" -f $CloudServiceName)

    }

}

else

{

    Write-Host ("Not able to stop virtual machine, cloud service will not be removed")

}

Figure 17: Clean-up Script

Create Linux Host VM

 

#CreateHostLinuxVirtualMachine

# The Subscription name that we want to create our environment in

$SubscriptionNameId = "<your subscriber id here>"

# Storage account name. This should already be created

$StorageAccountname = "portalvhds0mll57sg9hvjd"

# Cloud Service name. This service should exist.

$CloudServiceName = "<insert-name-of-your-cloud-service-here>"

# Instance size

$InstanceSize = "Medium"

# Linux Admin Username

$password = "<insert your password here>"

# Linux Admin Password

$username = "<insert your username here>"

# Linux image name

$LinuxImagename = "ubuntuhost"

# Load the keys for us to login to

$LoadSettings = Import-AzurePublishSettingsFile "NinadKNew.publishsettings"

# Important to specify the CurrentStorageAccountName, especially otherwise you might get Storage not accessible error when creating linux machines.

Set-AzureSubscription -SubscriptionId $SubscriptionNameId -CurrentStorageAccountName $StorageAccountname -ErrorAction Stop

Select-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

# Get the image from Azure repository that we want to create. Its the Ubuntu 14_04_LTS variant. We can speed up the creation script by caching the name.

# the name obtained is

$UbuntuImage = 'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB'

# Configure VM by specifying VMName, Instance Size, ImageName, AvailabilitySet and specify AzureSubnet

$VMNew = New-AzureVMConfig -Name $LinuxImagename -InstanceSize $InstanceSize -ImageName $UbuntuImage

# Add the username and password to the VM creation configuration

$VMNew | Add-AzureProvisioningConfig -Linux -LinuxUser $username -Password $password

# Create and start the VM. Remember, it won't be fully provisioned when the call returns.   

$Result = $VMNew | New-AzureVM -ServiceName $CloudServiceName

Write-Host ("Created VM Image {0}, return value = {1}" -f $LinuxImagename, $Result.OperationStatus )

    

Figure 18: Create Linux Host Script

Get Public Endpoints of a VM

# GetPublicEndPointOfaVM

# The Subscription name that we want to create our environment in

$SubscriptionNameId = "< insert your subscription id here>"

# Cloud Service name. This service should exist.

$CloudServiceName = "< insert cloud-service-name here >"

# Linux image name

$LinuxImagename = "< insert image name here >"

$LoadSettings = Import-AzurePublishSettingsFile "NinadKNew.publishsettings"

Set-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

Select-AzureSubscription -SubscriptionId $SubscriptionNameId -ErrorAction Stop

$VMEndpoints = Get-AzureVM -ServiceName $CloudServiceName -Name $LinuxImagename | Get-AzureEndpoint

if ($VMEndpoints)

{

    foreach($item in $VMEndpoints)

    {

        if ($VMEndpoints.Name.Equals('SSH'))

        {

            Write-host ("{0}.cloudapp.net:{1}" -f $CloudServiceName, $item.Port)

        }

    }

}

 

Figure 19: Get Public Endpoints of a VM Script

Creating Azure File Share and uploading file

# creating Azure file share and uploading the certificate file to it.

# CreateAzureFileStorageScript

$SubscriptionName = "<Insert-your-Subscription-name-here>" # just go for one subscription

$LoadSettings = Import-AzurePublishSettingsFile "NinadKNew.publishsettings"

Set-AzureSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop

# Wow this Select-AzureSubscription is more important than anything else.

Select-AzureSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop

$StorageAccountname = "<insert-your-file-storage-name>"

$AffinityGroup = "linuxdistros"

if (!$GetStorageAccount)

{

    # Storage account does not exists, let’s create one

    $GetStorageAccount = New-AzureStorageAccount -StorageAccountName $StorageAccountname -Label "PS Created" -AffinityGroup $AffinityGroup

    Write-host ("Storage account {0} created status = {1}" -f $StorageAccountname, $GetStorageAccount.OperationStatus)

}

#lets get the storage context now

$AzureSampleShare = "linuxshare"

$ShareDirectoryName = "share"

$StorageContext =New-AzureStorageContext -StorageAccountName $StorageAccountname -StorageAccountKey (Get-AzureStorageKey -StorageAccountName $StorageAccountname).Primary -Protocol Https

if ($StorageContext)

{

     $ExistingStorageShare = Get-AzureStorageShare -Name $AzureSampleShare -Context $StorageContext -ErrorAction Continue

     if (!$ExistingStorageShare)

     {

        $ExistingStorageShare = New-AzureStorageShare -Name $AzureSampleShare -Context $StorageContext

        Start-Sleep -s 30

        Write-Host ("New Azure Storage Share created, name = {0}" -f $AzureSampleShare)

        # create a share directory name

        $NewAzureStorageDirectory = New-AzureStorageDirectory -Share $ExistingStorageShare -Path $ShareDirectoryName

     }

     # upload our file

     Set-AzureStorageFileContent -Share $ExistingStorageShare -Source C:\Azure\Linux\NinadKNew.publishsettings -Path $ShareDirectoryName

     # check that the file has been uploaded.

     Get-AzureStorageFile -Share $ExistingStorageShare -Path $ShareDirectoryName

}

Figure 20: Creating Azure File Share and uploading file Script

References

1.       Install and configure Azure Cross-Platform Command-Line Interface

2.       Running a remote desktop on Windows Azure Linux VM

3.       How to use SSH with Linux on Azure

4.       Shared folder on Linux via Azure Files

5.       Best Practices for Managing Azure Subscriptions in Windows Azure PowerShell Cmdlets


Comments (0)

Skip to main content