Tag Archives: Azure resource manager

Step-by-Step Guide: Azure Key Vault

People use safes, security boxes to protect their valuable things. In digital world “Data” is the most valuable thing. Passwords, Connection Strings, Secrets, Data encryption/decryption keys protects access to different data sets. Whoever have access to those will also have access to data behind it (of cause they need to know how to use those ๐Ÿ˜Š). So how we can protect those valuable info? People use different methods. Some use third party software installed on PC to do it. If its large environment some use web application so multiple people have access to it. different vendors use different methods to protect these types of valuable data. Microsoft Azure Key vault is a service which we can use to protect Passwords, Connection Strings, Secrets, Data encryption/decryption keys uses by cloud applications and services. Keys stored in vaults is protected by hardware security modules (HSMs). It is also possible to import or generate keys using HSMs. Any keys process that way will be done according to FIPS 140-2 Level 2 guidelines. You can find about FIPS 140-2 Level 2 using https://www.microsoft.com/en-us/trustcenter/Compliance/FIPS

Benefits of using Key Vault

Keys saved in vault will be served via URLs. Developers, engineers do not need worry about securing keys. Application or service do not see the keys as vault service process behalf of them.  

Customers do not have to disclosure their keys to vendors or service providers. They can manage their own keys and allow to access those keys via urls in vendor or service provider applications. Vendor or service providers will not see the keys. 

By design Microsoft can’t extract or see customer keys. So, its further protected in vendor level too. 

HSMs are FIPS 140-2 Level 2 validated. So, any industry required to comply with these standards are protected by default. 

Key usage details are logged. So, you know what’s happening with your keys.  

An Azure Administrator is allowed to do following using Azure Key Vault,

Create or import a key or secret

Revoke or delete a key or secret

Authorize users or applications to access the key vault, which allow them to manage or use its own keys and secrets

Configure key usage 

Record key usage

More info about Azure Key vault can find under https://docs.microsoft.com/en-us/azure/key-vault/key-vault-overview 

Let’s go ahead and see how we can setup and use Azure Key Vault service. 

Create Azure Key Vault Instance  
 
1) Log in to Azure Portal as global admin.
2) Click on Cloud Shell icon in top right-hand corner. (You also can setup this using portal, Azure CLI or locally installed Azure PowerShell. In this demo I am using Azure PowerShell directly from portal)  
 
kv1
 
3) Then select PowerShell for the command type. 
4) Then type Get-AzureRmResourceGroup to list down resource groups. So, we can select the resource group to associate the new key vault. 
 
kv2
 
5) If you wish to create key vault under new resource group, you can do it using 
 
New-AzureRmResourceGroup -Name RGName -Location WestUS
 
In above command RGName specify the resource group name and WestUS define the region. You can find the available locations using Get-AzureRmLocation
 
6) Now it’s time to create the vault. We can create it using, 
 
New-AzureRmKeyVault -VaultName 'Rebel-KVault1' -ResourceGroupName 'therebeladmin' -Location 'North Central US'
 
In above VaultName defines the Key Vault name. ResourceGroupName defines the resource group it is associated with. Location defines the location of resource. 
 
kv3
 
7) We can view properties of existing key vault using,
 
Get-AzureRmKeyVault "Rebel-KVault1"
 
In above Rebel-KVault1 is the key vault name. 
 
kv4
 
Vault URI shows the URL which can use to access the key vault by applications and services. 
 
8) Next step is to create Access Policy for the key vault. Using access policy we can define who have control over key vault, what they can do inside key vault and also what a application or service can do with it. 
 
Set-AzureRmKeyVaultAccessPolicy -VaultName 'Rebel-KVault1' -UserPrincipalName 'user1@rebeladmlive.onmicrosoft.com' -PermissionsToKeys create,delete,list -PermissionsToSecrets set,list,delete -PassThru
 
In above command, user1@rebeladmlive.onmicrosoft.com can create,delete,list keys in Rebel-KVault1. He also can set,list,delete secrets under same vault. 
 
kv5
 
We also can set permissions for application to retrieve secrets or keys. 
 
Set-AzureRmKeyVaultAccessPolicy -VaultName 'Rebel-KVault1' -ServicePrincipalName 'http://crm.rebeladmin.com' -PermissionsToSecrets Get
 
In above, service running on http://crm.rebeladmin.com will have permissions to retrieve secrets from the vault. 
 
Key Management
 
Now we have a vault up and running. Next step is to see how to manage valued data using it. In this demo I am going to do this using Azure Portal. Same tasks still can be done using Azure CLI or Azure PowerShell. 
 
1) To access Key vault feature in portal, go to Azure Portal > All Services > Key vaults
 
kv6
 
2) Then click on the relevant key vault from the list. In my demo it is Rebel-KVault1 which we create on previous section. 
 
kv7
 
3) Then it will load new window. Let’s go ahead and add a secret. To do that click on the Secrets option. 
 
kv8
 
4) Then click on Generate/Import
 
kv9
 
5) Then in the form fill the relevant info. Value defines the secret. After put relevant info click on create
 
kv10
 
6) If you need to delete a secret, click on the relevant secret from the list.
 
kv11
 
7) Then click on Delete
 
kv12
 
8) We also can generate/import certificates for use. In order to do so click on Certificates from the list.
 
kv13
 
9) Then click on Generate/Import 
 
kv14
 
10) From the form, using Generate option we can create self-signed certificate. 
 
kv15
 
11) Using Import option, we can import certificates in .PFX format. In the form, Upload Certificate File is the path for the .PFX file. You can use browse option to define the path. We can provide the PFX password under Password field. Once form is done, click on Create
 
kv16
 
kv17
 
 
Hope now you have understanding about Azure key vault and how to use it. This marks the end of this blog post. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Azure Virtual Machine Scale Sets โ€“ Part 01 โ€“ What is it and How to set it up?

There are many different solutions available to load balance applications. It can be based on separate hardware appliances, virtual appliances or system inbuilt method such as NLB (Network Load Balancer). However, there are few common challenges on these environments. 

If its third-party solution, additional cost involves for licenses, configuration and maintenance 

Applications or services not always use all of the allocated resources. It may depend on demand and time. Since its fixed number of instance, infrastructure resource will be wasted in non-peak time. if its cloud service, it going to waste money!

When the number of server instances increase, it makes it harder to manage systems. Too many manual tasks!

Azure virtual machine scale sets answers all above challenges. It can automatically increase and decreases number of vm instances running based on demand or schedule. No extra virtual appliances or licenses involves. It also allows to centrally manage, configure large number of instances. Following points are recognized as key benefits of Azure virtual machine scale sets.

It supports Azure load balancer (Layer-4) and Azure Application Gateway (Layer-7) traffic distribution.

It allows to maintain same VM configuration across the instance including VM size, Network, Disk, OS image, Application installs. 

Using Azure Availability Zones, if required we can configure to distribute VM instances in scale set to different datacenters. It adds additional availability. 

It can automatically increase and decrease number of vm instances running based on application demand. It saves money!

It can grow up to 1000 vm instances, if its own custom images, it supports up to 300 vm instances. 

It supports Azure Managed Disks and Premium Storage. 

Let’s see how we can setup Azure virtual machine scale set. In my demo I am going to use Azure PowerShell. 

1) Log in to Azure Portal as Global Administrator
 
2) Open Cloud shell (right hand corner)
 
ss1
 
3) Make sure you are using PowerShell Option
 
ss2
 
4) In my demo scale set configuration as following
 
New-AzureRmVmss `
  -ResourceGroupName "rebelResourceGroup" `
  -Location "canadacentral" `
  -VMScaleSetName "rebelScaleSet" `
  -VirtualNetworkName "rebelVnet" `
  -SubnetName "rebelSubnet" `
  -PublicIpAddressName "rebelPublicIPAddress" `
  -LoadBalancerName "rebelLoadBalancer" `
  -BackendPort "80" `
  -VmSize "Standard_DS3_v2" `
  -ImageName "Win2012Datacenter" `
  -InstanceCount "4" `
  -UpgradePolicy "Automatic"
 
In above,
 

Parameter

Description

New-AzureRmVmss

This is the command use to create Azure Virtual Machine Scale Set

-ResourceGroupName

This define the resource group name and it is a new one.

-Location

This defines the resource region. In my demo its Canada Central

-VMScaleSetName

This defines the name for the Scale Set

-VirtualNetworkName

This defines the virtual network name

-SubnetName

This defines the subnet name. if you do not define subnet prefix, it will use default 192.168.1.0/24

-PublicIpAddressName

This defines the name for public IP address. If not define allocation method using -AllocationMethod , it will use dynamic by default.

-LoadBalancerName

This defines the load balancer name

-BackendPort

This creates relevant rules in loadbalancer and load balance the traffic. in my demo I am using TCP port 80.

-VmSize

This defines the VM size. if this is not defined, by default it uses Standard_DS2_v2

-ImageName

This defines the VM image details. If no valuves used it will use default value which is Windows Server 2016 Datacenter

-InstanceCount

This defines the initial number of instance running on the scale set

-UpgradePolicy

This defines upgrade policy for VM instances in scale set

Once this is run it will ask to define login details for instances. After completes, it will create the scale set.

ss3

This also can do using Portal. In order to use GUI, 

1) Log in to Azure Portal as Global Administrator

2) Go to All Services | Virtual Machine Scale Set

ss4

3) In new page, click on Add

ss5

4) Then it will open up the form, once fill in relevant info click on create 

ss6

5) We also can review the existing scale set properties using Virtual machine scale sets page. On page click on scale set name to view the properties. If we click on Instances, we can see the number of instances running

ss7

6) Scaling shows the number of instances used. If need it can also adjust in here. 

ss8

7) Size defines the size of the VM, again if need values can change in same page. 

ss9

8) Also, if we go to Azure Portal | Load Balancers, we can review settings for load balancer used in scale set.

ss10

9) In my demo I used TCP port 80 to load balance. Those info can find under Load Balancing rules

ss11

10) Relevant public ip info for scale set can be find under inbound NAT rules

ss12

 

This marks the end of this blog post. In next post we will look in to further configuration of scale set. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

How to re-enable Network Interface in Azure VM?

In Hyper-V or VMware virtualization environment, Enable/Disable NIC in a VM is not a big deal. Even if you do not have NIC or valid IP configure, administrators still can connect to VM as it does have “Console” access. Few weeks ago, I received an email from one of my regular blog readers. He accidently disabled NIC in azure vm and he lost RDP access to it. since there is no console access like other on-premises virtualization solution, of cause he was panicking. In this blog post I am going to share what you can do to re-enable your Azure VM NIC in such scenario. 

In my demo setup, I have an active azure VM running with 10.5.2.33 private IP address. 

ip1

I logged in to VM as administrator and disable the NIC.

Now I need to regain the RDP access to server. in order to do that, log in to Azure Portal as Global Administrator and click on Cloud Shell button in right hand top corner. 

ip2

When window load up makes sure you are using PowerShell option. 

ip3

Now we need to find out the NIC details of the VM that we having issues with. We can do this using,

Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" 

In this command, -ResourceGroupName represent the resource group that VM belongs to. In my demo setup I only have one VM under that resource group.  but if you have more VMs it can be hard to find the relevant info. In that case I recommend to use portal itself to view this info.

In here, note down the network interface name, IP address and allocation method you using. 

ip4

Now, we need to assign a new IP address to the same nic from same subnet. It can be done using,

$Nic = Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" -Name "rebeladmin-vm1123"

$Nic.IpConfigurations[0].PrivateIpAddress = "10.5.2.34"

$Nic.IpConfigurations[0].PrivateIpAllocationMethod = "Static"

$Nic.Tag = @{Name = "Name"; Value = "Value"}

Set-AzureRmNetworkInterface -NetworkInterface $Nic

In above commands, rebeladmin-vm1123 represent the network interface name. 10.5.2.34 is the new ip address for the network interface. PrivateIpAllocationMethod define the ip allocation method. Set-AzureRmNetworkInterface cmdlet sets the network interface configuration. 

ip5

Great!! Now I got my RDP access back with new IP address.

ip6

But it is not the original IP it had, now we can change it back with,

$Nic2 = Get-AzureRmNetworkInterface -ResourceGroupName "REBELADMIN-DEMO" -Name "rebeladmin-vm1123"

$Nic2.IpConfigurations[0].PrivateIpAddress = "10.5.2.33"

$Nic2.IpConfigurations[0].PrivateIpAllocationMethod = "Static"

$Nic2.Tag = @{Name = "Name"; Value = "Value"}

Set-AzureRmNetworkInterface -NetworkInterface $Nic2

ip7

Once it is applied, I can access server via RDP and now it has same private IP address it had.

ip8

If you using dynamic IP allocation method, you need to make it static, then change the ip and go back to dynamic mode. 

This marks the end of this blog post. If you have any questions feel free to contact me on rebeladm@live.com also follow me on twitter @rebeladm to get updates about new blog posts.

Step-By-Step guide to create Azure VM using Azure CLI 2.0

In my previous blog post I have explain what is Azure CLI and how we can integrate it with windows system. If you didn’t read it yet please look in to it before we continue on this post. You can find it on http://www.rebeladmin.com/2017/08/step-step-guide-start-azure-cli-2-0/

In this blog post I am going to demonstrate how we can create Azure VM using Azure CLI. 

1) Log in to Azure CLI using az login (This is explained on my first blog. If you using cloud shell this is not necessary. All you need to do is launch it on the portal)

clivm1

2) Next step on process is to create resource group. before we create we need to know the available locations. So, we can create resource group under relevant geographical location. To list down the locations, run az account list-locations

clivm2

In my demo I am going to create resource group called “rebeladminrg01” under west us. The command for that task will be az group create --name rebeladminrg01 --location westus. In above –name specify the resource group name and –location specifies the geographical location. 

clivm3

3) Next step is to create a virtual network under my new resource group. for that I am going to use 

az network vnet create --name rebeladminVNet --resource-group rebeladminrg01 --location westus --address-prefix 10.10.0.0/16

In above command –name specify the virtual network name. in sample, it is rebeladminVNet. --resource-group defines the resource group it belongs to. In above –location specify the geographical location it belongs to. --address-prefix specify the address space associated with the virtual network.

clivm4

4) Now we have virtual network, next step is to create subnet 10.10.20.0/24 under the virtual network rebeladminVNet. In order to do that I am going to use,

az network vnet subnet create --address-prefix 10.10.20.0/24 --name rebeladminsub1 --resource-group rebeladminrg01 --vnet-name rebeladminVNet

in above, --address-prefix specify the address space for the subnet. –name specify the name of the subnet. --resource-group specify the resource group new subnet belongs to. --vnet-name specify the virtual network it is belongs to. 

clivm5

5) let’s also associate a new public IP address with virtual network, so we can use it to connect from external to new vm that we about to create. 

az network public-ip create --name rebeladminpubip1 --resource-group rebeladminrg01 --location westus --allocation-method dynamic

In above –name specify the name of the public IP instance. --resource-group defines the resource group name it belongs to. –location specifies the georgical location resource belongs to. --allocation-method specifies the public IP allocation method. It can be static IP or dynamic Ip assignment. In this demo, I am going to use dynamic method. 

clivm6

6) Next step on the process to create NIC so we can attach it to VM. 

az network nic create --resource-group rebeladminrg01 --name rebeladminNic1 --vnet-name rebeladminVNet --subnet rebeladminsub1 --public-ip-address rebeladminpubip1

in above sample, --resource-group defines the resource group name it belongs to. --vnet-name specify the virtual network it is belongs to. –subnet specify the subnet it associated with. --public-ip-address specify the public ip address this NIC will associate with. 

clivm7

Now we have components needed for the vm (except storage, I will cover storage on different post. In here I will be using Azure managed disks). We can review the details about the resource we created using az resource list -g rebeladminrg01 this will list down the resource under resources group rebeladminrg01

clivm8

Some data such as subnet info will not display by using above command. Those can view using list command combine with resources group and parent resources. as an example, to view subnet info under the virtual network we can use,

az network vnet subnet list --vnet-name rebeladminVNet -g rebeladminrg01

in above --vnet-name specify the virtual network name and -g specify the resource group name. 

clivm9

7) Now it’s all ready, lets create first windows VM using the resource we created on previous steps. 

az vm create --resource-group rebeladminrg01 --location westus --nics rebeladminNic1 --name REBLEVM101 --image win2016datacenter --admin-username rebeladmin --admin-password Pa$$w0rd123456

in above, --resource-group specify the resources group VM belong to. –nics specify the network interface associated with the VM. –name is the VM name. –image specify the virtual machine image going to use with VM. You can get list of entire image list using az vm image list --output table –all

in sample --admin-username defines the admin user name for the new vm and --admin-password defines the VM password. 

clivm10

this creates the VM successfully. 

clivm11

In this demo, I explain how to create VM using azure cli. Hope this was useful and in next post on Azure CLI I will cover about storage. If you have any questions, feel free to contact me on rebeladm@live.com 

Step-by-Step Guide to Start with Azure CLI 2.0

There are many ways to create, manage, remove resources from Azure subscription. For the users who prefer GUI has Azure Classic portal and Azure Resource Manager. For PowerShell lovers Azure has Azure PowerShell module. Apart from that there are other methods such as terraform (I already wrote articles about it, if you want to know more about it, search for “terraform” in the blog) which simplifies Azure resource management. Azure CLI is also a command-line tool introduced by Microsoft which can use to manage azure resources. This is allowing to use from multiple platform such as Linux, Mac OS and Windows. This blog post is to explain how we can configure windows system to use Azure CLI. 

There are two ways which we can use to connect to Azure CLI. 

Using Azure Portal

Azure also allow to use web based version of Azure CLI with name of “Cloud Shell”. This is easily can open through the browser. In order to access it,

1) Log in to Azure Portal

2) Click on Cloud Shell icon on top right-hand side

cli1

3) When you do this for first time it will ask to create Azure file share. You can select relevant subscription and click on “Create Storage

cli2

4) Once it is created the storage, it will load up the shell access through the browser. 

cli3

Using Windows Computer

We also can use Azure CLI from the local computer. as I said this is not only supported to use with windows systems. it is supported to use with Linux and Mac OS. In this demo, I am going to demonstrate how to configure it with windows system. 

Azure CLI uses python so out configuration will be based on python installation. 

1) Log in to computer as an administrator

2) Go to https://www.python.org/downloads/ and download python

cli4

3) Once file is downloaded, run it as administrator to install. During the installation, make sure to select option “Add Python 3.6 to PATH” option. Then it will allow to use python commands without navigating to installation location. 

cli5

4) Once installation completed, open windows command-line and type python –version. this will confirm the python installation. (it is recommended to open command line as administrator, otherwise it will say PATH records are not added as we ran the installation as Administrator) 

cli6

5) Next step is to install Azure CLI libraries. In order to do that run pip install –user azure-cli

cli7

6) Once it is completed, move to C:\Users\[Admin User]\AppData\Roaming\Python\Python36\Scripts and run command az . This will verify the Azure CLI integration. If it needs to run from anywhere add it to the PATH. 

cli8

7) Now let’s try to log in to Azure using Azure CLI. In order to do that we can use az login -u azureusername -p password. the problem on this method is that password need to type in as clear text. Instead of that we can use browser based more secure login. To do that type az login in command-line. 

The it gives a link and code to use for authentication. 

cli9

8) Once it is open in browser it asks for the verification code. Once its enter click on Continue

cli10

In next page, it verifies the Azure login and then confirm the connection.

cli11

When we go back to Azure CLI, we can see its successfully logged in and showing the subscription data. 

cli12

This confirms the successful connection to Azure using Azure CLI. This is the end of this post and in next post let’s see how we can add, manage, remove azure resources via Azure CLI. Hoep this was helpful and if you have any questions feel free to contact me on rebeladm@live.com

Azure resource setup simplified with terraform

This week I was testing Terraform , a simple tool which can use to automate Azure resource deployment.

It will be easier to explain terraform with a real-world example. I am developing a web application and as my resource provider I am using Azure. my first requirement is to setup a development environment. For that I need at least one web server, one database server and connectivity between these two servers. to setup the environment, I log in to the portal and then setup resource group, storage account and virtual network. After that I start to build servers. after I complete it, I setup web server application and database server. so even its looks like straight forward, its takes time. later on, in the development process I also required a test platform where I can try my application with different operating systems. Also, I like to test application by adding more components such as load balancers, web servers to the environment. These testing environments are temporally. So, each and every time I need to setup environment with all the different components and once testing process completes, needs to destroy it. when I need to sell it as a solution to people, I face another challenge as not everyone wants to run it on Azure. Even if it’s another service provider or on-premises environment, application should test in similar environment prior to sell as a solution. Each provider has their own way of setting up things.

On this given scenario I faced few challenges,

To setup required resources for application takes time as each component need to configure in certain way. 

To setup integration between components, I need to log in to different systems and adjust the settings. A single mistake can cause hours of disruptions to the project. 

Due to the complexity of setting up environments, I may end up keep running test environments longer which probably increase my development cost. 

How Terraform can help?

Using Terraform I can deploy the whole environment by executing a single script file. This script is basically a set of instructions explaining how to setup each and every component. If I need to setup a new server in azure from scratch there is a procedure for it. we need to setup relevant resource groups, network components, storage accounts before we start to build the server. terraform itself understand these dependencies and build the environment according to that. This also helps to standardize the resource setup process.

Terraform also can use to configure application settings as part of the environment setup. That means we do not need to log in to systems to make initial software configurations. This will prevent the human errors.

Once we setup an environment using terraform we can change it, destroy it using a single command. As an example, let’s assume we setup a test environment with two web servers (using terraform). I have a new requirement to add new web server to the same environment. To do that all I need to do is modify the same script and add new entry for new webserver. once I execute it, it will automatically detect the current environment and only add the missing components. When destroy, it is again a single command and it will remove each component in the proper order. As example, it will understand that before remove resource group, it need to remove all other components under it.

As setup and destroy process of resources is easy with terraform, we do not need to keep running non-critical resources. As an example, if I need to give a POC or show a demo to a customer, all I need to do is to execute the pre-created terraform script when needed and destroy it afterwards.

Terraform support different service providers. It is not only for cloud based solutions. It also supports on-premises solutions. As an example, terraform can use with Azure Pack and Azure stack to do the same thing in on-premises Hyper-V environment. It also supports to SaaS application configurations. The supported providers list can be found in here https://www.terraform.io/docs/providers/index.html

Terraform mainly have three functions.

Plan – Before execute the configuration, it should go for the planning stage. In here terraform will build the execution plan based on the configuration provided by the engineer. It will explain what will be created when configuration is executed.

Apply – In this phase it will apply execute the execution plan created on the “planning” stage. It will also report back once its completed the resource setup. If there were errors, it will also explain it in details.

Destroy – This is basically to undo the execution plan. By calling this, we can destroy all the resource created by a particular terraform configuration file.

I think it’s enough with the theory, let’s see why it’s so cool.

In my demo, I am going to show how to setup terraform and how to use it to create resource in azure. 

Setup Terraform

In my demo, I am going to use windows 10 as the system. Terraform also supported on Linux, Mac and solaris systems.

1) Go to this link and download the file relevant to windows architecture. 

2) Then create a folder and move the downloaded terraform.exe file. 

3) Next step is to setup the Binary path for the terraform so system knows when we use the terraform commands. To do that, run the PowerShell console as Administrator and then type

$env:Path += ";C:\terraform"

In here C:\terraform is the folder where I saved the terraform.exe

terra1

4) As next step, we can confirm terraform setup by running terraform in the PowerShell console. 

terra2
 
This confirms the Terraform setup and next step to configure Azure side to support terraform. 
 
Retrieve Required info from Azure

Terraform uses Azure ARM API to connect and manage azure resources. To connect to Azure, terraform need to provide following Azure ARM environment variables using configuration file.

ARM_SUBSCRIPTION_ID

ARM_CLIENT_ID

ARM_CLIENT_SECRET

ARM_TENANT_ID

To get ARM_CLIENT_ID, ARM_CLIENT_SECRET and ARM_TENANT_ID we need to create a Service Principal in Azure.

To do the we can use Azure Cloud Shell.  

1) Log in to Azure Portal ( https://portal.azure.com ) as a Global Administrator

2) Click on Cloud Shell Button. 

terra3

3) Then it will open the shell in the same window. If it’s your first time using this feature, it will ask to create a storage account. 

terra4

4) Next step is to fine the Subscription Id. To do that type following and press enter. 

az account list

Then it will provide an output like following. In there “id” represent the Subscription ID we required. 

terra5

5) Next step is to create the Service Principal. In order to do that use,

az ad sp create-for-rbac –role="Contributor" –scopes="/subscriptions/xxxxxxxxxxxx"

in above command xxxxxxxxxxxx should replace with the Subscription ID we found in the previous step. 

Then it gives an output similar to following

terra6

In above image 

appId is equal to Client ID.

Password is equal to Client Secret

Tenant is equal to Tenant ID

Now we have all the information we need in order to connect to Azure trough terraform. 

Create first configuration

Next step is to create first terraform configuration file. The file is using the extension of .tf. You can use your favorite text editor to create the file. I am using Visual Studio code and it can be download from https://code.visualstudio.com/

The file no need to save on the same folder where your terraform.exe file. However, you need to navigate to that folder before execute the terraform commands. In my demo, it is C:\terraform

My first configuration is following

 

# Configure the Microsoft Azure Provider

provider "azurerm" {

  subscription_id = "xxxxxxx"

  client_id       = " xxxxxxx "

  client_secret   = " xxxxxxx "

  tenant_id       = " xxxxxxx "

}

resource "azurerm_resource_group" "myterrapro1" {

  name     = "myterrapro1"

  location = "West US"

}

resource "azurerm_virtual_network" "myterrapro1network" {

  name                = "myterrapro1vn"

  address_space       = ["10.11.12.0/24"]

  location            = "West US"

  resource_group_name = "${azurerm_resource_group.myterrapro1.name}"

}

In above code,

provider "azurerm"

define the service provider as Azure ARM.

 subscription_id = "xxxxxxx"

                client_id       = " xxxxxxx "

                client_secret   = " xxxxxxx "

                tenant_id       = " xxxxxxx "

the above values should replace by the values we found through the Azure.

resource "azurerm_resource_group" "myterrapro1" {

  name     = "myterrapro1"

  location = "West US"

}

The above saying to create new azure resource group called myterrapro1 in West US region.

resource "azurerm_virtual_network" "myterrapro1network" {

  name                = "myterrapro1vn"

  address_space       = ["10.11.12.0/24"]

  location            = "West US"

  resource_group_name = "${azurerm_resource_group.myterrapro1.name}"

in the next section, it is creating an Azure Virtual Network called myterrapro1vn. It got address space allocated as 10.11.12.0/24. This will create under resource group called myterrapro1. This virtual network also will be created under West US region.

Once script is ready, save it with .tf extension.

Then launch PowerShell as Administrator. Then change the folder path to where script file is saved. In my demo, its C:\terraform. After that type following,

terraform plan

This is step where terraform build the execution plan.

terra7

This output shows what will happen when apply the execution plan.

To apply the plan type following and press enter.

terraform apply

once process is started, it will also show the progress of setting up resources.

terra8

according to above image we can see its successfully created the resources. we can confirm it using the Azure portal.

terra9

terra10

Now we know how to create resource. Let’s see how to destroy the resources we created.

In order to do that you do not need to change anything in the script. All you need to do is to issue the command,

terraform destroy

once we run the command it will ask to confirm. Type yes and press enter to proceed with the destroy process.

terra11

As we can see it remove all the resource in the configuration file. Once it done we can also log in to azure portal and confirm.

Isn’t this cool?

In this blog post I explained what is terraform and how we can use it to simplify resource setup in azure. in next blog post I will share more examples to show its capabilities.

Hope this was useful and if you have any questions feel free to contact me on rebeladm@live.com