Skip to content
This repository was archived by the owner on Jan 5, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions FunctionalTests/ExportedTemplate/DeploymentHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Requires the following Azure NuGet packages and related dependencies:
// package id="Microsoft.Azure.Management.Authorization" version="2.0.0"
// package id="Microsoft.Azure.Management.ResourceManager" version="1.4.0-preview"
// package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.8-preview"

using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure.Authentication;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace PortalGenerated
{
/// <summary>
/// This is a helper class for deploying an Azure Resource Manager template
/// More info about template deployments can be found here https://go.microsoft.com/fwLink/?LinkID=733371
/// </summary>
class DeploymentHelper
{
string subscriptionId = "your-subscription-id";
string clientId = "your-service-principal-clientId";
string clientSecret = "your-service-principal-client-secret";
string resourceGroupName = "resource-group-name";
string deploymentName = "deployment-name";
string resourceGroupLocation = "resource-group-location"; // must be specified for creating a new resource group
string pathToTemplateFile = "path-to-template.json-on-disk";
string pathToParameterFile = "path-to-parameters.json-on-disk";
string tenantId = "tenant-id";

public async void Run()
{
// Try to obtain the service credentials
var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret);

// Read the template and parameter file contents
JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

// Create the resource manager client
var resourceManagementClient = new ResourceManagementClient(serviceCreds);
resourceManagementClient.SubscriptionId = subscriptionId;

// Create or check that resource group exists
EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

// Start a deployment
DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
}

/// <summary>
/// Reads a JSON file from the specified path
/// </summary>
/// <param name="pathToJson">The full path to the JSON file</param>
/// <returns>The JSON file contents</returns>
private JObject GetJsonFileContents(string pathToJson)
{
JObject templatefileContent = new JObject();
using (StreamReader file = File.OpenText(pathToJson))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
templatefileContent = (JObject)JToken.ReadFrom(reader);
return templatefileContent;
}
}
}

/// <summary>
/// Ensures that a resource group with the specified name exists. If it does not, will attempt to create one.
/// </summary>
/// <param name="resourceManagementClient">The resource manager client.</param>
/// <param name="resourceGroupName">The name of the resource group.</param>
/// <param name="resourceGroupLocation">The resource group location. Required when creating a new resource group.</param>
private static void EnsureResourceGroupExists(ResourceManagementClient resourceManagementClient, string resourceGroupName, string resourceGroupLocation)
{
if (resourceManagementClient.ResourceGroups.CheckExistence(resourceGroupName) != true)
{
Console.WriteLine(string.Format("Creating resource group '{0}' in location '{1}'", resourceGroupName, resourceGroupLocation));
var resourceGroup = new ResourceGroup();
resourceGroup.Location = resourceGroupLocation;
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, resourceGroup);
}
else
{
Console.WriteLine(string.Format("Using existing resource group '{0}'", resourceGroupName));
}
}

/// <summary>
/// Starts a template deployment.
/// </summary>
/// <param name="resourceManagementClient">The resource manager client.</param>
/// <param name="resourceGroupName">The name of the resource group.</param>
/// <param name="deploymentName">The name of the deployment.</param>
/// <param name="templateFileContents">The template file contents.</param>
/// <param name="parameterFileContents">The parameter file contents.</param>
private static void DeployTemplate(ResourceManagementClient resourceManagementClient, string resourceGroupName, string deploymentName, JObject templateFileContents, JObject parameterFileContents)
{
Console.WriteLine(string.Format("Starting template deployment '{0}' in resource group '{1}'", deploymentName, resourceGroupName));
var deployment = new Deployment();

deployment.Properties = new DeploymentProperties
{
Mode = DeploymentMode.Incremental,
Template = templateFileContents,
Parameters = parameterFileContents["parameters"].ToObject<JObject>()
};

var deploymentResult = resourceManagementClient.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment);
Console.WriteLine(string.Format("Deployment status: {0}", deploymentResult.Properties.ProvisioningState));
}
}
}
107 changes: 107 additions & 0 deletions FunctionalTests/ExportedTemplate/deploy.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<#
.SYNOPSIS
Deploys a template to Azure

.DESCRIPTION
Deploys an Azure Resource Manager template

.PARAMETER subscriptionId
The subscription id where the template will be deployed.

.PARAMETER resourceGroupName
The resource group where the template will be deployed. Can be the name of an existing or a new resource group.

.PARAMETER resourceGroupLocation
Optional, a resource group location. If specified, will try to create a new resource group in this location. If not specified, assumes resource group is existing.

.PARAMETER deploymentName
The deployment name.

.PARAMETER templateFilePath
Optional, path to the template file. Defaults to template.json.

.PARAMETER parametersFilePath
Optional, path to the parameters file. Defaults to parameters.json. If file is not found, will prompt for parameter values based on template.
#>

param(
[Parameter(Mandatory=$True)]
[string]
$subscriptionId,

[Parameter(Mandatory=$True)]
[string]
$resourceGroupName,

[string]
$resourceGroupLocation,

[Parameter(Mandatory=$True)]
[string]
$deploymentName,

[string]
$templateFilePath = "template.json",

[string]
$parametersFilePath = "parameters.json"
)

<#
.SYNOPSIS
Registers RPs
#>
Function RegisterRP {
Param(
[string]$ResourceProviderNamespace
)

Write-Host "Registering resource provider '$ResourceProviderNamespace'";
Register-AzureRmResourceProvider -ProviderNamespace $ResourceProviderNamespace;
}

#******************************************************************************
# Script body
# Execution begins here
#******************************************************************************
$ErrorActionPreference = "Stop"

# sign in
Write-Host "Logging in...";
Login-AzureRmAccount;

# select subscription
Write-Host "Selecting subscription '$subscriptionId'";
Select-AzureRmSubscription -SubscriptionID $subscriptionId;

# Register RPs
$resourceProviders = @("microsoft.cognitiveservices","microsoft.storage","microsoft.web","microsoft.insights","microsoft.botservice");
if($resourceProviders.length) {
Write-Host "Registering resource providers"
foreach($resourceProvider in $resourceProviders) {
RegisterRP($resourceProvider);
}
}

#Create or check for existing resource group
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if(!$resourceGroup)
{
Write-Host "Resource group '$resourceGroupName' does not exist. To create a new resource group, please enter a location.";
if(!$resourceGroupLocation) {
$resourceGroupLocation = Read-Host "resourceGroupLocation";
}
Write-Host "Creating resource group '$resourceGroupName' in location '$resourceGroupLocation'";
New-AzureRmResourceGroup -Name $resourceGroupName -Location $resourceGroupLocation
}
else{
Write-Host "Using existing resource group '$resourceGroupName'";
}

# Start the deployment
Write-Host "Starting deployment...";
if(Test-Path $parametersFilePath) {
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -Name $deploymentName -TemplateFile $templateFilePath -TemplateParameterFile $parametersFilePath;
} else {
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -Name $deploymentName -TemplateFile $templateFilePath;
}
122 changes: 122 additions & 0 deletions FunctionalTests/ExportedTemplate/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

# -e: immediately exit if any command has a non-zero exit status
# -o: prevents errors in a pipeline from being masked
# IFS new value is less likely to cause confusing bugs when looping arrays or arguments (e.g. $@)

usage() { echo "Usage: $0 -i <subscriptionId> -g <resourceGroupName> -n <deploymentName> -l <resourceGroupLocation>" 1>&2; exit 1; }

declare subscriptionId=""
declare resourceGroupName=""
declare deploymentName=""
declare resourceGroupLocation=""

# Initialize parameters specified from command line
while getopts ":i:g:n:l:" arg; do
case "${arg}" in
i)
subscriptionId=${OPTARG}
;;
g)
resourceGroupName=${OPTARG}
;;
n)
deploymentName=${OPTARG}
;;
l)
resourceGroupLocation=${OPTARG}
;;
esac
done
shift $((OPTIND-1))

#Prompt for parameters is some required parameters are missing
if [[ -z "$subscriptionId" ]]; then
echo "Your subscription ID can be looked up with the CLI using: az account show --out json "
echo "Enter your subscription ID:"
read subscriptionId
[[ "${subscriptionId:?}" ]]
fi

if [[ -z "$resourceGroupName" ]]; then
echo "This script will look for an existing resource group, otherwise a new one will be created "
echo "You can create new resource groups with the CLI using: az group create "
echo "Enter a resource group name"
read resourceGroupName
[[ "${resourceGroupName:?}" ]]
fi

if [[ -z "$deploymentName" ]]; then
echo "Enter a name for this deployment:"
read deploymentName
fi

if [[ -z "$resourceGroupLocation" ]]; then
echo "If creating a *new* resource group, you need to set a location "
echo "You can lookup locations with the CLI using: az account list-locations "

echo "Enter resource group location:"
read resourceGroupLocation
fi

#templateFile Path - template file to be used
templateFilePath="template.json"

if [ ! -f "$templateFilePath" ]; then
echo "$templateFilePath not found"
exit 1
fi

#parameter file path
parametersFilePath="parameters.json"

if [ ! -f "$parametersFilePath" ]; then
echo "$parametersFilePath not found"
exit 1
fi

if [ -z "$subscriptionId" ] || [ -z "$resourceGroupName" ] || [ -z "$deploymentName" ]; then
echo "Either one of subscriptionId, resourceGroupName, deploymentName is empty"
usage
fi

#login to azure using your credentials
az account show 1> /dev/null

if [ $? != 0 ];
then
az login
fi

#set the default subscription id
az account set --subscription $subscriptionId

set +e

#Check for existing RG
az group show --name $resourceGroupName 1> /dev/null

if [ $? != 0 ]; then
echo "Resource group with name" $resourceGroupName "could not be found. Creating new resource group.."
set -e
(
set -x
az group create --name $resourceGroupName --location $resourceGroupLocation 1> /dev/null
)
else
echo "Using existing resource group..."
fi

#Start deployment
echo "Starting deployment..."
(
set -x
az group deployment create --name "$deploymentName" --resource-group "$resourceGroupName" --template-file "$templateFilePath" --parameters "@${parametersFilePath}"
)

if [ $? == 0 ];
then
echo "Template has been successfully deployed"
fi
Loading