Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State of the branch after implementation is complete. #15866

Merged
Show file tree
Hide file tree
Changes from 5 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
105 changes: 84 additions & 21 deletions eng/common/TestResources/New-TestResources.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
[CmdletBinding(DefaultParameterSetName = 'Default', SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param (
# Limit $BaseName to enough characters to be under limit plus prefixes, and https://docs.microsoft.com/azure/architecture/best-practices/resource-naming.
[Parameter(Mandatory = $true, Position = 0)]
[Parameter()]
[ValidatePattern('^[-a-zA-Z0-9\.\(\)_]{0,80}(?<=[a-zA-Z0-9\(\)])$')]
[string] $BaseName,

[Parameter(Mandatory = $true)]
[ValidatePattern('^[-\w\._\(\)]+$')]
[string] $ResourceGroupName,

[Parameter(Mandatory = $true, Position = 0)]
[string] $ServiceDirectory,

[Parameter(Mandatory = $true)]
[Parameter()]
[ValidatePattern('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')]
[string] $TestApplicationId,

Expand Down Expand Up @@ -52,7 +55,7 @@ param (
[string] $Location = '',

[Parameter()]
[ValidateSet('AzureCloud', 'AzureUSGovernment', 'AzureChinaCloud')]
[ValidateSet('AzureCloud', 'AzureUSGovernment', 'AzureChinaCloud', 'Dogfood')]
[string] $Environment = 'AzureCloud',

[Parameter()]
Expand Down Expand Up @@ -115,6 +118,9 @@ $repositoryRoot = "$PSScriptRoot/../../.." | Resolve-Path
$root = [System.IO.Path]::Combine($repositoryRoot, "sdk", $ServiceDirectory) | Resolve-Path
$templateFileName = 'test-resources.json'
$templateFiles = @()
$environmentVariables = @{}
# Azure SDK Developer Playground
$defaultSubscription = "faa080af-c1d8-40ad-9cce-e1a450ca5b57"

Write-Verbose "Checking for '$templateFileName' files under '$root'"
Get-ChildItem -Path $root -Filter $templateFileName -Recurse | ForEach-Object {
Expand All @@ -129,6 +135,26 @@ if (!$templateFiles) {
exit
}

$UserName = if ($env:USER) { $env:USER } else { "${env:USERNAME}" }

# If no base name is specified use current user name
if (!$BaseName) {
$BaseName = "$UserName$ServiceDirectory"

Log "BaseName was not set. Using default base name: '$BaseName'"
}

# Try detecting repos that support OutFile and defaulting to it
if (!$CI -and !$PSBoundParameters.ContainsKey('OutFile') -and $IsWindows)
{
# TODO: find a better way to detect the language
if (Test-Path "$repositoryRoot/eng/service.proj")
{
$OutFile = $true
Log "Detected .NET repository. Defaulting OutFile to true. Test environment settings would be stored into the file so you don't need to set environment variables manually."
}
}

# If no location is specified use safe default locations for the given
# environment. If no matching environment is found $Location remains an empty
# string.
Expand All @@ -137,12 +163,13 @@ if (!$Location) {
'AzureCloud' = 'westus2';
'AzureUSGovernment' = 'usgovvirginia';
'AzureChinaCloud' = 'chinaeast2';
'Dogfood' = 'westus'
}[$Environment]

Write-Verbose "Location was not set. Using default location for environment: '$Location'"
}

# Log in if requested; otherwise, the user is expected to already be authenticated via Connect-AzAccount.
# Log in if requested; otherwise, try to login into playground subscription.
if ($ProvisionerApplicationId) {
$null = Disable-AzContextAutosave -Scope Process

Expand Down Expand Up @@ -171,6 +198,25 @@ if ($ProvisionerApplicationId) {
}
}
}
elseif (!$CI)
{
# check if user is logged in and login into
$context = Get-AzContext;
if (!$context)
{
Log "You are not logged in, connecting to 'Azure SDK Developer Playground'"
Connect-AzAccount -Subscription $defaultSubscription
}

# If no test application id is specified create a new service principal
if (!$TestApplicationId) {
Log "TestApplicationId was not specified, creating a new service principal."
$servicePrincipal = New-AzADServicePrincipal -Role Owner

$TestApplicationId = $servicePrincipal.ApplicationId
$TestApplicationSecret = (ConvertFrom-SecureString $servicePrincipal.Secret -AsPlainText);
}
}

# Get test application OID from ID if not already provided.
if ($TestApplicationId -and !$TestApplicationOid) {
Expand All @@ -194,19 +240,23 @@ $serviceName = if (Split-Path -IsAbsolute $ServiceDirectory) {
$ServiceDirectory
}

# Format the resource group name based on resource group naming recommendations and limitations.
$resourceGroupName = if ($CI) {
$BaseName = 't' + (New-Guid).ToString('n').Substring(0, 16)
Write-Verbose "Generated base name '$BaseName' for CI build"
if ($CI) {
$BaseName = 't' + (New-Guid).ToString('n').Substring(0, 16)
Write-Verbose "Generated base name '$BaseName' for CI build"
}

"rg-{0}-$BaseName" -f ($serviceName -replace '[\\\/:]', '-').Substring(0, [Math]::Min($serviceName.Length, 90 - $BaseName.Length - 4)).Trim('-')
$ResourceGroupName = if ($ResourceGroupName) {
$ResourceGroupName
} elseif ($CI) {
# Format the resource group name based on resource group naming recommendations and limitations.
"rg-{0}-$BaseName" -f ($serviceName -replace '[\\\/:]', '-').Substring(0, [Math]::Min($serviceName.Length, 90 - $BaseName.Length - 4)).Trim('-')
} else {
"rg-$BaseName"
"rg-$BaseName"
}

# Tag the resource group to be deleted after a certain number of hours if specified.
$tags = @{
Creator = if ($env:USER) { $env:USER } else { "${env:USERNAME}" }
Creator = $UserName
ServiceDirectory = $ServiceDirectory
}

Expand All @@ -225,13 +275,14 @@ if ($CI) {
}

# Set the resource group name variable.
Write-Host "Setting variable 'AZURE_RESOURCEGROUP_NAME': $resourceGroupName"
Write-Host "##vso[task.setvariable variable=AZURE_RESOURCEGROUP_NAME;]$resourceGroupName"
Write-Host "Setting variable 'AZURE_RESOURCEGROUP_NAME': $ResourceGroupName"
Write-Host "##vso[task.setvariable variable=AZURE_RESOURCEGROUP_NAME;]$ResourceGroupName"
$environmentVariables['AZURE_RESOURCEGROUP_NAME'] = $ResourceGroupName
}

Log "Creating resource group '$resourceGroupName' in location '$Location'"
Log "Creating resource group '$ResourceGroupName' in location '$Location'"
$resourceGroup = Retry {
New-AzResourceGroup -Name "$resourceGroupName" -Location $Location -Tag $tags -Force:$Force
New-AzResourceGroup -Name "$ResourceGroupName" -Location $Location -Tag $tags -Force:$Force
}

if ($resourceGroup.ProvisioningState -eq 'Succeeded') {
Expand Down Expand Up @@ -274,7 +325,7 @@ $shell, $shellExportFormat = if (($parentProcessName = (Get-Process -Id $PID).Pa
} elseif (@('bash', 'csh', 'tcsh', 'zsh') -contains $parentProcessName) {
'shell', 'export {0}={1}'
} else {
'PowerShell', '$env:{0} = ''{1}'''
'PowerShell', '${{env:{0}}} = ''{1}'''
}

# Deploy the templates
Expand All @@ -295,7 +346,7 @@ foreach ($templateFile in $templateFiles) {
$preDeploymentScript = $templateFile | Split-Path | Join-Path -ChildPath 'test-resources-pre.ps1'
if (Test-Path $preDeploymentScript) {
Log "Invoking pre-deployment script '$preDeploymentScript'"
&$preDeploymentScript -ResourceGroupName $resourceGroupName @PSBoundParameters
&$preDeploymentScript -ResourceGroupName $ResourceGroupName @PSBoundParameters
}

Log "Deploying template '$templateFile' to resource group '$($resourceGroup.ResourceGroupName)'"
Expand Down Expand Up @@ -364,6 +415,7 @@ foreach ($templateFile in $templateFiles) {
foreach ($key in $deploymentOutputs.Keys)
{
$value = $deploymentOutputs[$key]
$environmentVariables[$key] = $value

if ($CI) {
# Treat all ARM template output variables as secrets since "SecureString" variables do not set values.
Expand All @@ -386,12 +438,18 @@ foreach ($templateFile in $templateFiles) {
$postDeploymentScript = $templateFile | Split-Path | Join-Path -ChildPath 'test-resources-post.ps1'
if (Test-Path $postDeploymentScript) {
Log "Invoking post-deployment script '$postDeploymentScript'"
&$postDeploymentScript -ResourceGroupName $resourceGroupName -DeploymentOutputs $deploymentOutputs @PSBoundParameters
&$postDeploymentScript -ResourceGroupName $ResourceGroupName -DeploymentOutputs $deploymentOutputs @PSBoundParameters
}
}

$exitActions.Invoke()

# Suppress output locally
if ($CI)
{
return $environmentVariables
}

<#
.SYNOPSIS
Deploys live test resources defined for a service directory to Azure.
Expand Down Expand Up @@ -422,6 +480,10 @@ the ARM template. See also https://docs.microsoft.com/azure/architecture/best-pr
Note: The value specified for this parameter will be overriden and generated
by New-TestResources.ps1 if $CI is specified.

.PARAMETER ResourceGroupName
Set this value to deploy directly to a Resource Group that has already been
created.

.PARAMETER ServiceDirectory
A directory under 'sdk' in the repository root - optionally with subdirectories
specified - in which to discover ARM templates named 'test-resources.json'.
Expand Down Expand Up @@ -449,7 +511,7 @@ test resources (e.g. Role Assignments on resources). It is passed as to the ARM
template as 'testApplicationOid'

For more information on the relationship between AAD Applications and Service
Principals see: https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals
Principals see: https://docs.microsoft.com/azure/active-directory/develop/app-objects-and-service-principals

.PARAMETER TenantId
The tenant ID of a service principal when a provisioner is specified. The same
Expand Down Expand Up @@ -496,6 +558,7 @@ is based on the cloud to which the template is being deployed:
* AzureCloud -> 'westus2'
* AzureUSGovernment -> 'usgovvirginia'
* AzureChinaCloud -> 'chinaeast2'
* Dogfood -> 'westus'

.PARAMETER Environment
Name of the cloud environment. The default is the Azure Public Cloud
Expand Down Expand Up @@ -550,4 +613,4 @@ log redaction).

.LINK
Remove-TestResources.ps1
#>
#>
Binary file not shown.
69 changes: 69 additions & 0 deletions sdk/api-learn/Azure.Learn.AppConfig/samples/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Learn.AppConfig;

namespace Azure.Learn.AppConfig.Samples
{
class Program
{
public static async Task Main(string[] args)
{
var p = new Program();
p.GetConfigurationSetting();
await p.GetConfigurationSettingIfChanged();
}

public void GetConfigurationSetting()
{
string endpoint = Environment.GetEnvironmentVariable("API-LEARN_ENDPOINT");
ConfigurationClient client = new ConfigurationClient(new Uri(endpoint), new DefaultAzureCredential());

ConfigurationSetting color = client.GetConfigurationSetting("FontColor");
ConfigurationSetting greeting = client.GetConfigurationSetting("GreetingText");

Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), color.Value);
Console.WriteLine(greeting.Value);
Console.ResetColor();
}

public async Task GetConfigurationSettingIfChanged()
{
string endpoint = Environment.GetEnvironmentVariable("API-LEARN_ENDPOINT");
christothes marked this conversation as resolved.
Show resolved Hide resolved

ConfigurationClient client = new ConfigurationClient(new Uri(endpoint), new DefaultAzureCredential());

Dictionary<string, ConfigurationSetting> settingCache = new Dictionary<string, ConfigurationSetting>();
await InitializeCacheAsync(client, settingCache);
PrintGreeting(settingCache);

for (int i = 0; i < 4; i++)
{
await UpdateCacheAsync(client, settingCache);
PrintGreeting(settingCache);

await Task.Delay(2000);
}
}

private async Task InitializeCacheAsync(ConfigurationClient client, Dictionary<string, ConfigurationSetting> cache)
{
cache["FontColor"] = await client.GetConfigurationSettingAsync("FontColor");
cache["GreetingText"] = await client.GetConfigurationSettingAsync("GreetingText");
}

public async Task UpdateCacheAsync(ConfigurationClient client, Dictionary<string, ConfigurationSetting> cache)
{
cache["FontColor"] = await client.GetConfigurationSettingAsync(cache["FontColor"], onlyIfChanged: true);
cache["GreetingText"] = await client.GetConfigurationSettingAsync(cache["GreetingText"], onlyIfChanged: true);
}

public void PrintGreeting(Dictionary<string, ConfigurationSetting> cache)
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), cache["FontColor"].Value);
Console.WriteLine(cache["GreetingText"].Value);
Console.ResetColor();
}
}
}
16 changes: 16 additions & 0 deletions sdk/api-learn/Azure.Learn.AppConfig/samples/samples.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<ProjectReference Include="..\src\Azure.Learn.AppConfig.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.2.3" />
</ItemGroup>

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@

<!-- Shared source from Azure.Core -->
<ItemGroup>
<Compile Include="$(AzureCoreSharedSources)Argument.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)ArrayBufferWriter.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)ClientDiagnostics.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)ContentTypeUtilities.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)DiagnosticScope.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)DiagnosticScopeFactory.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)HttpMessageSanitizer.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)NoBodyResponse{T}.cs" />
<Compile Include="$(AzureCoreSharedSources)TaskExtensions.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)OperationHelpers.cs" Link="Shared\%(RecursiveDir)\%(Filename)%(Extension)" />
<Compile Include="$(AzureCoreSharedSources)AzureResourceProviderNamespaceAttribute.cs" />
Expand Down
Loading