DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
yaswanthteja
yaswanthteja

Posted on

Create and save scripts in Azure PowerShell #2

Complex or repetitive tasks often take a great deal of administrative time. Organizations prefer to automate these tasks to reduce costs and avoid errors.

This is important in the Customer Relationship Management (CRM) company example. There, you're testing your software on multiple Linux Virtual Machines (VMs) that you need to continuously delete and recreate. You want to use a PowerShell script to automate the creation of the VMs versus creating them manually each time.

Beyond the core operation of creating a VM, you have a few additional requirements for your script:

You will create multiple VMs, so you want to put the creation inside a loop
You need to create VMs in three different resource groups, so the name of the resource group should be passed to the script as a parameter
In this section, you will see how to write and execute an Azure PowerShell script that meets these requirements.

What is a PowerShell script?

A PowerShell script is a text file containing commands and control constructs. The commands are invocations of cmdlets. The control constructs are programming features like loops, variables, parameters, comments, etc., supplied by PowerShell.

PowerShell script files have a .ps1 file extension. You can create and save these files with any text editor.

If you’re writing PowerShell scripts under Windows, you can use the Windows PowerShell Integrated Scripting Environment (ISE). This editor provides features such as syntax coloring and a list of available cmdlets.

The following screenshot shows the Windows PowerShell Integrated Scripting Environment (ISE) with a sample script to connect to Azure and create a virtual machine in Azure.

Image description
Once you've written the script, execute it from the PowerShell command line by passing the name of the file preceded by a dot and a backslash:

.\myScript.ps1
Enter fullscreen mode Exit fullscreen mode

PowerShell techniques
PowerShell has many features found in typical programming languages. You can define variables, use branches and loops, capture command-line parameters, write functions, add comments, and so on. We will need three features for our script: variables, loops, and parameters.

Variables
As you saw in the last unit, PowerShell supports variables. Use $ to declare a variable and = to assign a value. For example:

$loc = "East US"
$iterations = 3
Enter fullscreen mode Exit fullscreen mode

Variables can hold objects. For example, the following definition sets the adminCredential variable to the object returned by the Get-Credential cmdlet.

$adminCredential = Get-Credential
Enter fullscreen mode Exit fullscreen mode

To obtain the value stored in a variable, use the $ prefix and its name, as in the following:

$loc = "East US"
New-AzResourceGroup -Name "MyResourceGroup" -Location $loc
Enter fullscreen mode Exit fullscreen mode

Loops
PowerShell has several loops: For, Do...While, For...Each, and so on. The For loop is the best match for our needs, because we will execute a cmdlet a fixed number of times.

The core syntax is shown below; the example runs for two iterations and prints the value of i each time. The comparison operators are written -lt for "less than", -le for "less than or equal", -eq for "equal", -ne for "not equal", etc.

For ($i = 1; $i -lt 3; $i++)
{
    $i
}
Enter fullscreen mode Exit fullscreen mode

Parameters
When you execute a script, you can pass arguments on the command line. You can provide names for each parameter to help the script extract the values. For example:

.\setupEnvironment.ps1 -size 5 -location "East US"
Enter fullscreen mode Exit fullscreen mode

Inside the script, you'll capture the values into variables. In this example, the parameters are matched by name:

param([string]$location, [int]$size)
Enter fullscreen mode Exit fullscreen mode

You can omit the names from the command line. For example:

.\setupEnvironment.ps1 5 "East US"
Enter fullscreen mode Exit fullscreen mode

Inside the script, you'll rely on position for matching when the parameters are unnamed:

param([int]$size, [string]$location)
Enter fullscreen mode Exit fullscreen mode

We could take these parameters as input and use a loop to create a set of VMs from the given parameters. We'll try that next.

The combination of PowerShell and Azure PowerShell gives you all the tools you need to automate Azure. In our CRM example, we'll be able to create multiple Linux VMs using a parameter to keep the script generic and a loop to avoid repeated code. This means that we can execute a formerly complex operation in a single step.

Create and save scripts in Azure PowerShell

you'll continue with the example of a company that makes Linux admin tools. Recall that you plan to use Linux VMs to let potential customers test your software. You have a resource group ready, and now it's time to create the VMs.

Your company has paid for a booth at a large Linux trade show. You plan a demo area containing three terminals each connected to a separate Linux VM. At the end of each day, you want to delete the VMs and recreate them, so they start fresh every morning. Creating the VMs manually after work when you're tired would be error prone. You want to write a PowerShell script to automate the VM creation process

Write a script to create virtual machines

Follow these steps in Cloud Shell on the right to write the script:

1.Switch to your home folder in Cloud Shell.

cd $HOME\clouddrive
Enter fullscreen mode Exit fullscreen mode

2.Create a new text file, named ConferenceDailyReset.ps1.

touch "./ConferenceDailyReset.ps1"
Enter fullscreen mode Exit fullscreen mode

3.Open the integrated editor, and select the ConferenceDailyReset.ps1 file.

code "./ConferenceDailyReset.ps1"
Enter fullscreen mode Exit fullscreen mode

The integrated Cloud Shell also supports vim, nano, and emacs if you'd prefer to use one of those editors.

  1. Start by capturing the input parameter in a variable. Add the following line to your script.
param([string]$resourceGroup)
Enter fullscreen mode Exit fullscreen mode

Normally, you'd have to authenticate with Azure using your credentials using Connect-AzAccount, and you could do so in the script. However, in Cloud Shell environment you will already be authenticated, so this is unnecessary.

5.Prompt for a username and password for the VM's admin account and capture the result in a variable:

$adminCredential = Get-Credential -Message "Enter a username and password for the VM administrator."
Enter fullscreen mode Exit fullscreen mode
  1. Create a loop that executes three times:
For ($i = 1; $i -le 3; $i++) 
{

}
Enter fullscreen mode Exit fullscreen mode
  1. In the loop body, create a name for each VM and store it in a variable, and output it to the console:
$vmName = "ConferenceDemo" + $i
Write-Host "Creating VM: " $vmName
Enter fullscreen mode Exit fullscreen mode
  1. Next, create a VM using the $vmName variable:
New-AzVm -ResourceGroupName $resourceGroup -Name $vmName -Credential $adminCredential -Image UbuntuLTS
Enter fullscreen mode Exit fullscreen mode
  1. Save the file. You can use the "..." menu at the top right corner of the editor. There are also common accelerator keys for Save, like Ctrl-S.

The completed script should look like the following code:

param([string]$resourceGroup)

$adminCredential = Get-Credential -Message "Enter a username and password for the VM administrator."

For ($i = 1; $i -le 3; $i++)
{
    $vmName = "ConferenceDemo" + $i
    Write-Host "Creating VM: " $vmName
    New-AzVm -ResourceGroupName $resourceGroup -Name $vmName -Credential $adminCredential -Image UbuntuLTS
}
Enter fullscreen mode Exit fullscreen mode

Run the script

1.Save the file, and close the editor using the "..." context menu on the top right of the editor.

2.Run the script.

./ConferenceDailyReset.ps1 [sandbox resource group name]
Enter fullscreen mode Exit fullscreen mode

The script will take several minutes to complete. When it's finished, verify it ran successfully by looking at the resources you now have in your resource group:

Get-AzResource -ResourceType Microsoft.Compute/virtualMachines
Enter fullscreen mode Exit fullscreen mode

You should see three VMs, each with a unique name.

You wrote a script that automated the creation of three VMs in the resource group indicated by a script parameter. The script is
short and simple, but automates a process that would take a long time to complete manually with the Azure portal.

Clean up

When you're working in your own subscription, it's a good idea at the end of a project to identify whether you still need the resources you created. Resources that you leave running can cost you money. You can delete resources individually or delete the resource group to delete the entire set of resources.

When you are running in your own subscription, you can use the following PowerShell cmdlet to delete the resource group (and all related resources).

Remove-AzResourceGroup -Name MyResourceGroupName
Enter fullscreen mode Exit fullscreen mode

When you are asked to confirm the delete, answer Yes, or you can add the -Force parameter to skip the prompt. The command may take several minutes to complete.

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›