One C# statement to authenticate. One statement to create a virtual machine. One statement to modify an existing virtual network, etc. No more guessing about what is required vs. optional vs. non-modifiable.
So that’s what the Azure team had to say when they released what the .NET ‘Fluent’ API back in 2016, with the promise of simplifying the Azure management libraries down to being able to create VMs, modify settings and perform all sorts of clever things with single lines of C# code. Sounds promising, but is it any good?
In short, yes, it really is. Let’s take a look at what you can do with it and why, as a developer, you should care.
Where does it fit in with other management options?
Since 2016 the Fluent API has made its way into the mainstream Azure management library for .NET, so there are now (as of writing) 4 main options for managing your infrastructure:
- Azure PowerShell
- Azure CLI
- Azure Management API (inc. the .NET Management library)
If you want to understand more about the other options, head over the Azure for beginners blog series where I cover Azure PowerShell & the CLI in detail. The great thing about the final option, however, is that its designed to be object-orientated, which makes it perfect for programmers who want / need to take a role in managing Azure infrastructure. It’s also built on top of .NET Core, which makes it open-source, which we like.
Why call it Fluent exactly?
Well, this stems from the programming pattern known as ‘Fluent Interfaces’, and is essentially the idea of building APIs that make the code written for them as simple and readable as possible, and as a nice by-product, easier to maintain. Let me show you what I mean…
In an interaction with a traditional ‘un-fluent’ API through object-orientated code, you might see something like this:
Each method call is happening on a new line, one after another. However, what if the API we’re calling passes us back a reference to the object as a result of us calling a method? Well, that would mean we could chain all of this together into a single line of code, like so:
Beautiful, I know. Almost brings a tear to your eye. There’s a lot more to it than that, but that’s the general idea behind ‘fluent’ APIs.
Okay, so are you going to show me how it works or just ramble on?
Say no more.
Setting up a Service Principal
Before we can crack on and start fluent-ing, we need to make sure our program has sufficient access to our Azure subscription to do some stuff, which means we need to set it up in Azure Active Directory as a ‘Service Principal’. Think of this as setting up the program as a user and defining their access rights to administer the subscription (more details in the documentation here).
Let’s use trusty PowerShell to do this. If you’ve checked out the Azure for beginners blog posts you’ll know we can do this using Azure’s Cloud Shell in the browser, or if you have the AzureRM modules installed locally, then that’s fine too. Start with logging in (if you aren’t using the Cloud Shell) and selecting the right subscription:
Log in at the prompt, then:
Now we’re logged in, we can register a new Azure AD app like so (feel free to change the naming):
$NewAADApp = New-AzureRmADApplication -DisplayName "FluentAPIApp" -HomePage "http://www.FluentAPIApp.com" -IdentifierUris "http://FluentAPIApp"
Let’s add the app as a Service Principal for our subscription:
New-AzureRmADServicePrincipal -ApplicationId $NewAADApp.ApplicationId
You should get the following output if successful:
Finally let’s give our new Service Principal the appropriate permissions it will need (I’m setting it to Contributor so it can create new resources as well as view/edit existing ones, but it’s up to you what level of access you want to provide):
New-AzureRmRoleAssignment -ServicePrincipalName $NewAADApp.ApplicationId.Guid -RoleDefinitionName Contributor
As you can see, for the ‘Scope’, my app has been granted Contributor access to my subscription. Keep the PowerShell window open as you’ll need to grab some values from it in a sec.
To use the Azure Management API, we must first authenticate – and we have to do this every time we use it for obvious reasons. We can either do this in the code itself or by using an authentication file, and I’m going to go with the latter so we keep the code squeaky clean. Open up your favourite code / text editor and paste in the following:
Now replace the missing fields with their appropriate values (most of which you can get from your open PowerShell window):
- Subscription: your Subscription ID
- Client: the Application ID
- Key: you will need to navigate to the portal for this. From the left-hand menu, go into Azure Active Directory, then App Registrations, then click your new app. Now click Settings, then Keys, then type a description for a new key, like ‘API App Key’. When you hit Save, you’ll see a new secure string will be generated. Copy it and paste it into your authorisation text document
- Tenant: you can get this using
Get-AzureRmSubscriptionand looking under the subscription you’re using
Save this somewhere safe as a .txt file and call it something like “Azure-authentication.txt”.
Create our app
Time to make the app that we’ll use to do, well, stuff. Azure-y stuff. Sticking with the open-source mantra, let’s do this with .NET Core and my favourite IDE, Visual Studio Code.
Seriously, VS Code is worth checking out. Free and open-source, and IntelliSense makes working with Azure just like using predictive text on your phone, except it actually works. Download it here if you haven’t already.
To begin, fire up PowerShell, the Command Line or Bash and
cd to the location you want to create your app in. Then
mkdir FolderName to create a folder for it (obviously replace FolderName with whatever you want to call your app), and
cd FolderName into it.
Now we can quickly create a .NET Core Console App by typing in
dotnew new console and the template will be created for us. Nice.
Open it up with Visual Studio Code by typing
code .. That is also nice. (You can of course do all of this with full-fat Visual Studio and starting off with a .NET Core Console App template in the New Project menu if you so wish).
Once VS Code opens, locate the project.assets.json file along the left-hand side in the Explorer window and double-click. Now add the below into the “dependencies”:
dotnet restore in the command line (in the project directory) to make sure this is applied, or alternatively if you prefer using Nuget Package Manager, just search for Microsoft.Azure.Management.Fluent and install that, and it will fill in all the dependencies for you.
Finally, open up Program.cs and add the following using statements:
You may get prompted to install the C# extension by Visual Studio Code if it’s your first time editing a cs file in it. Make sure you click install and let it do it’s magic, it’ll make the rest of the exercise much easier.
Okay, we’ve prepared our app. Now let’s get started with the API.
Now we need to add the following statement in the
Main() method of our code to get the authentication file we’ve just made and create an authenticated Azure object with it. (Note: I’ve moved the .txt file I created into the project’s directory, so either do the same or replace the below with a relative path to your .txt file):
var azure = Azure.Authenticate("Azure-authentication.txt").WithDefaultSubscription();
With these changes, your program.cs should be looking a little bit like this:
Create a VM
Once we’ve got our authenticated object, we can now do lot’s of cool stuff with it very quickly and easily. Let’s create a VM by inserting the following code just before the closing parenthesis of the
Run the code and you should hopefully see a new VM being created with our specifications. Pretty cool. What’s even cooler is if you start entering the first line of this code by yourself in Visual Studio, IntelliSense will then guide you through a wizard-like experience through suggestions of what required and optional parameters you need to define next, in the right order, for the type of resource you’re creating.
Create some storage and methodise
Okay, now let’s add storage account creation to the mix by inserting the following few lines just at the end of the
var storageAccount = azure.StorageAccounts.Define("StorageCreatedWithFluent")
Give it another run and you’ll find that it’ll fail, and that’s because we’re trying to create a VM’s public IP using the same DNS record we used for a previous VM, and this happens before we even get to creating storage.
How should we fix this? Well as with any good code, why don’t we split the code up into some re-usable methods? We can then also add user input to assign a VM name parameter, so we can decide upon creation what we want to name our new resources (and then use this to add a unique name to the DNS). Here’s the final result:
If we give that a run now, as long as you’re entering in valid unique names (note: I’ve added
ToLower() to the StorageName parameter as storage account names can only be lower case), you should see some successful outputs:
And if we check in the portal, we can see that the resources we’ve requested have appeared:
I’ll say it again: pretty cool.
Yeah, it is cool, but what else can you do?
Since its release in 2016 the team have added support for a number of different resources. Here’s some inspiration from the Azure samples on GitHub to get you started:
|Virtual Machines – parallel execution|
|Virtual Machine Scale Sets|
That’s all folks…
I hope you like the sound of the .NET Azure Management Fluent SDK and that you try out some of its functionalities. I’ve gotta say, it’s definitely my preferred way of managing Azure resources and it’s extremely easy to make pretty powerful workflows as you get to grips with it. Let me know in the comments if you want to hear more about it or if you’ve got some code of your own to share, and as always, happy to help in any way I can if you’re struggling or having issues you need support with.
Until next time – happy fluenting!