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.
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
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
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
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
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
}
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"
Inside the script, you'll capture the values into variables. In this example, the parameters are matched by name:
param([string]$location, [int]$size)
You can omit the names from the command line. For example:
.\setupEnvironment.ps1 5 "East US"
Inside the script, you'll rely on position for matching when the parameters are unnamed:
param([int]$size, [string]$location)
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
2.Create a new text file, named ConferenceDailyReset.ps1.
touch "./ConferenceDailyReset.ps1"
3.Open the integrated editor, and select the ConferenceDailyReset.ps1 file.
code "./ConferenceDailyReset.ps1"
The integrated Cloud Shell also supports vim, nano, and emacs if you'd prefer to use one of those editors.
- Start by capturing the input parameter in a variable. Add the following line to your script.
param([string]$resourceGroup)
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."
- Create a loop that executes three times:
For ($i = 1; $i -le 3; $i++)
{
}
- 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
- Next, create a VM using the $vmName variable:
New-AzVm -ResourceGroupName $resourceGroup -Name $vmName -Credential $adminCredential -Image UbuntuLTS
- 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
}
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]
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
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
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)