/// <summary> /// Checks for the existence of a specific Azure Web Site, if it doesn't exist it will create it. /// </summary> /// <param name="client">The <see cref="WebSiteManagementClient"/> that is performing the operation.</param> /// <param name="webSpace">The name of the Web Space where the site should be.</param> /// <param name="parameters">The <see cref="WebSiteCreateParameters"/> that define the site we want to create.</param> /// <returns>The async <see cref="Task"/> wrapper.</returns> public static async Task CreateWebSiteIfNotExistsAsync(this WebSiteManagementClient client, string webSpace, WebSiteCreateParameters parameters) { Contract.Requires(client != null); Contract.Requires(!string.IsNullOrWhiteSpace(webSpace)); Contract.Requires(parameters != null); WebSiteGetResponse service = null; FlexStreams.BuildEventsObserver.OnNext(new CheckIfExistsEvent(AzureResource.WebSite, parameters.Name)); try { service = await client.WebSites.GetAsync(webSpace, parameters.Name, null); } catch (CloudException cex) { if (cex.Error.Code != "NotFound") { throw; } } if (service != null) { FlexStreams.BuildEventsObserver.OnNext(new FoundExistingEvent(AzureResource.WebSite, parameters.Name)); return; } await client.WebSites.CreateAsync(webSpace, parameters); FlexStreams.BuildEventsObserver.OnNext(new ProvisionEvent(AzureResource.WebSite, parameters.Name)); }
public static async Task <PublishingProfile> GetPublishingProfile(TargetSite targetSite, ServicePrincipalAccount account) { string mgmtEndpoint = account.ResourceManagementEndpointBaseUri; var token = new TokenCredentials(await Auth.GetAuthTokenAsync(account)); var azureCredentials = new AzureCredentials( token, token, account.TenantId, new AzureKnownEnvironment(account.AzureEnvironment).AsAzureSDKEnvironment()) .WithDefaultSubscription(account.SubscriptionNumber); var restClient = RestClient .Configure() .WithBaseUri(mgmtEndpoint) .WithEnvironment(new AzureKnownEnvironment(account.AzureEnvironment).AsAzureSDKEnvironment()) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(azureCredentials) .Build(); var webAppClient = new WebSiteManagementClient(restClient) { SubscriptionId = account.SubscriptionNumber }; var options = new CsmPublishingProfileOptions { Format = PublishingProfileFormat.WebDeploy }; await webAppClient.WebApps.GetWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site); using var publishProfileStream = targetSite.HasSlot ? await webAppClient.WebApps.ListPublishingProfileXmlWithSecretsSlotAsync(targetSite.ResourceGroupName, targetSite.Site, options, targetSite.Slot) : await webAppClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(targetSite.ResourceGroupName, targetSite.Site, options); using var streamReader = new StreamReader(publishProfileStream); var document = XDocument.Parse(await streamReader.ReadToEndAsync()); var profile = (from el in document.Descendants("publishProfile") where string.Compare(el.Attribute("publishMethod")?.Value, "MSDeploy", StringComparison.OrdinalIgnoreCase) == 0 select new PublishingProfile { PublishUrl = $"https://{el.Attribute("publishUrl")?.Value}", Username = el.Attribute("userName")?.Value, Password = el.Attribute("userPWD")?.Value, Site = el.Attribute("msdeploySite")?.Value }).FirstOrDefault(); if (profile == null) { throw new Exception("Failed to retrieve publishing profile."); } return(profile); }
/// <summary> /// Provisions all the components in the <see cref="DevOpsFlexDbContext"/>. /// </summary> /// <param name="context">The database context that we want to provision components from.</param> /// <param name="subscriptionId">The subscription Id where we want to provision in.</param> /// <param name="settingsPath">The path to the settings file with the management certificate.</param> /// <returns>The async <see cref="Task"/> wrapper.</returns> public static async Task ProvisionAllAsync(this DevOpsFlexDbContext context, string subscriptionId, string settingsPath) { Contract.Requires(context != null); Contract.Requires(string.IsNullOrEmpty(subscriptionId)); Contract.Requires(string.IsNullOrEmpty(settingsPath)); var azureSubscription = new AzureSubscription(settingsPath, subscriptionId); var azureCert = new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate)); using (var computeClient = new ComputeManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) using (var networkClient = new NetworkManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) using (var sbClient = new ServiceBusManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) using (var sqlClient = new SqlManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) using (var storageClient = new StorageManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) using (var webSiteClient = new WebSiteManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert))) { var tasks = new[] { context.Components.OfType <AzureCloudService>().ToList().ProvisionAllAsync(computeClient), context.Components.OfType <AzureCloudService>().ToList().ReserveAllIpsAsync(networkClient), context.Components.OfType <AzureServiceBusNamespace>().ToList().ProvisionAllAsync(sbClient), context.Components.OfType <SqlAzureDb>().ToList().ProvisionAllAsync(sqlClient), context.Components.OfType <AzureStorageContainer>().ToList().ProvisionAllAsync(storageClient), context.Components.OfType <AzureWebSite>().ToList().ProvisionAllAsync(webSiteClient) }; await Task.WhenAll(tasks); } }
static void Main(string[] args) { if (args.Length < 1) { throw new ArgumentNullException("publish settings informations"); } SubscriptionCloudCredentials cred = GetCredentials(args[0]); //WATM TrafficManagerManagementClient watmClient = new TrafficManagerManagementClient(cred); string atmDns = "adxsdk12345.trafficmanager.net"; DnsPrefixAvailabilityCheckResponse watmResp = watmClient.Profiles.CheckDnsPrefixAvailability("adxsdk12345.trafficmanager.net"); Console.WriteLine("Invoke WATM->CheckDnsPrefixAvailability(\'{0}\'). Result: {1}", atmDns, watmResp.Result); //Compute ComputeManagementClient computeClient = new ComputeManagementClient(cred); string hostServiceName = "adxsdk12345"; HostedServiceCheckNameAvailabilityResponse computeResp = computeClient.HostedServices.CheckNameAvailability(hostServiceName); Console.WriteLine("Invoke Compute->CheckNameAvailability(\'{0}\'). Result: {1}", hostServiceName, computeResp.IsAvailable); //Websites WebSiteManagementClient websiteClient = new WebSiteManagementClient(cred); string webSiteName = "adxsdk12345"; WebSiteIsHostnameAvailableResponse webSiteResp = websiteClient.WebSites.IsHostnameAvailable(webSiteName); Console.WriteLine("Invoke WebSite->IsHostnameAvailable(\'{0}\'). Result: {1}", webSiteName, webSiteResp.IsAvailable); //Scheduler SchedulerManagementClient schedulerClient = new SchedulerManagementClient(cred); string schedulerCloudServiceName = "foobarrr"; string expectedSchedulerException = string.Format( "ResourceNotFound: The cloud service with name {0} was not found.", schedulerCloudServiceName); bool exceptionFromSchedulerServiceOccurred = false; try { schedulerClient.JobCollections.CheckNameAvailability(schedulerCloudServiceName, "doesnotmatter"); } catch (Exception ex) { if (ex.Message == expectedSchedulerException) { exceptionFromSchedulerServiceOccurred = true; Console.WriteLine("Invoke Scheduler->CheckNameAvailability(\'{0}\'). Get back correct exception", schedulerCloudServiceName, expectedSchedulerException); } } if (!exceptionFromSchedulerServiceOccurred) { throw new Exception("we didn't get expected exception message from scheduler service"); } Console.WriteLine("Smoke test is good"); }
public async Task Setup() { resourceGroupName = Guid.NewGuid().ToString(); clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "eastus"; authToken = await GetAuthToken(tenantId, clientId, clientSecret); var resourcesClient = new ResourcesManagementClient(subscriptionId, new ClientSecretCredential(tenantId, clientId, clientSecret)); resourceGroupClient = resourcesClient.ResourceGroups; var resourceGroup = new ResourceGroup(resourceGroupLocation); resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup); webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId, HttpClient = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint) }, }; var svcPlan = await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new AppServicePlan(resourceGroup.Location) { Kind = "linux", Reserved = true, Sku = new SkuDescription { Name = "S1", Tier = "Standard" } }); site = await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new Site(resourceGroup.Location) { ServerFarmId = svcPlan.Id, SiteConfig = new SiteConfig { LinuxFxVersion = @"DOCKER|mcr.microsoft.com/azuredocs/aci-helloworld", AppSettings = new List <NameValuePair> { new NameValuePair("DOCKER_REGISTRY_SERVER_URL", "https://index.docker.io"), new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false") }, AlwaysOn = true } }); webappName = site.Name; await AssertSetupSuccessAsync(); }
private async Task <WebSiteGetPublishProfileResponse> GetPublishProfile(WebSiteManagementClient client, string SiteName) { string Location = "SouthCentralUSwebspace"; WebSiteGetPublishProfileResponse res = await client.WebSites.GetPublishProfileAsync(Location, SiteName); return(res); }
public static async Task PutSlotSettingsListAsync(WebSiteManagementClient webAppClient, TargetSite targetSite, IEnumerable <string> slotConfigNames, string authToken) { var client = webAppClient.HttpClient; client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var targetUrl = $"https://management.azure.com/subscriptions/{webAppClient.SubscriptionId}/resourceGroups/{targetSite.ResourceGroupName}/providers/Microsoft.Web/sites/{targetSite.Site}/config/slotconfignames?api-version=2018-11-01"; var slotSettingsJson = new appSettingNamesRoot { properties = new properties { appSettingNames = slotConfigNames }, name = targetSite.Site }; var postBody = JsonConvert.SerializeObject(slotSettingsJson); //var body = new StringContent(postBody); var body = new StringContent(postBody, Encoding.UTF8, "application/json"); var response = await client.PutAsync(targetUrl, body); if (!response.IsSuccessStatusCode) { throw new HttpRequestException(response.ReasonPhrase); } }
public static async Task <ConnectionStringDictionary> GetConnectionStringsAsync( WebSiteManagementClient webAppClient, TargetSite targetSite) { var conStringDict = await webAppClient.WebApps.ListConnectionStringsAsync(targetSite); return(conStringDict); }
public AzureActiveDirectoryHelper(AzureActiveDirectoryConfig configuration) { var token = GetAuthorizationHeader(configuration); var cred = new TokenCloudCredentials(configuration.azureSubscriptionID, token); client = new WebSiteManagementClient(cred, APIENDPOINT); }
public void TestClientInitialization() { var tokenCredentials = new TokenCloudCredentials("123", "abc"); var fakeClient = new WebSiteManagementClient(tokenCredentials); Assert.IsNotNull(fakeClient); }
static async Task MainAsync() { // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; // Get the credentials TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal(); var tokenCreds = new TokenCredentials(cloudCreds.Token); var loggingHandler = new LoggingHandler(new HttpClientHandler()); // Create our own HttpClient so we can do logging var httpClient = new HttpClient(loggingHandler); // Use the creds to create the clients we need _resourceGroupClient = new ResourceManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler); _resourceGroupClient.SubscriptionId = cloudCreds.SubscriptionId; _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler); _websiteClient.SubscriptionId = cloudCreds.SubscriptionId; await ListResourceGroupsAndSites(); // Note: site names are globally unique, so you may need to change it to avoid conflicts await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI", "West US"); // Upload certificate to resource group await UpdateLoadCertificate("MyResourceGroup", "CertificateName", "West US", "PathToPfxFile", "CertificatePassword"); // Bind certificate to resource group await BindCertificateToSite("MyResourceGroup", "SiteName", "CertificateName", "hostName"); }
static void Main(string[] args) { Console.WriteLine("Starting"); var subscriptionId = ConsoleApp.Run("az", "account show --query id -o tsv").Output.Trim(); var token = ConsoleApp.Run("az", "account get-access-token --query accessToken -o tsv").Output.Trim(); Console.WriteLine($"Running with Sub: {subscriptionId}"); Console.WriteLine($"Running with Token: {token}"); var serviceCreds = new TokenCredentials(token, "Bearer"); var webClient = new WebSiteManagementClient(serviceCreds); webClient.SubscriptionId = subscriptionId; var functionSecrets = webClient.WebApps.ListFunctionSecrets("funcRestSpecTest", "testfuncx8b7a", "testfunc"); if (functionSecrets.Name == null) { Console.WriteLine("Due to spec issue #2 we see unpopulated Name properties"); } if (functionSecrets.Key == null) { Console.WriteLine("Due to spec issue #1 we end up here"); } }
public static async Task Run([TimerTrigger("0 0 * * * 0")] TimerInfo myTimer, ILogger log) { // clean up blimp app every sunday secretsUtils = new SecretsUtils(); await secretsUtils.GetSecrets(); pipelineUtils = new PipelineUtils( new ContainerRegistryManagementClient(secretsUtils._credentials), new WebSiteManagementClient(secretsUtils._credentials), secretsUtils._subId ); resourceGroupName = "blimprg"; webClient = new WebSiteManagementClient(secretsUtils._credentials) { SubscriptionId = secretsUtils._subId }; DeleteApps("blimp-dotnetcore-plan"); DeleteApps("blimp-node-plan"); DeleteApps("blimp-php-plan"); DeleteApps("blimp-python-plan"); DeleteApps("blimp-ruby-plan"); DeleteImages("blimpacr", "dotnetcore"); DeleteImages("blimpacr", "node"); DeleteImages("blimpacr", "php"); DeleteImages("blimpacr", "python"); DeleteImages("blimpacr", "ruby"); }
public override void Initialize(AzureCredentials credentials) { Client = new WebSiteManagementClient(credentials) { SubscriptionId = credentials.DefaultSubscriptionId }; }
private static async Task <WebSiteManagementClient> CreateWebSiteManagementClientAsync(string subscriptionId) { var tokenProvider = new AzureServiceTokenProvider(); var accessToken = await tokenProvider.GetAccessTokenAsync("https://management.azure.com/"); var tokenCredentials = new TokenCredentials(accessToken); var azureCredentials = new AzureCredentials( tokenCredentials, tokenCredentials, "common", AzureEnvironment.AzureGlobalCloud); var client = RestClient .Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(azureCredentials) .Build(); var websiteClient = new WebSiteManagementClient(client) { SubscriptionId = subscriptionId }; return(websiteClient); }
public PipelineUtils(ContainerRegistryManagementClient registryClient, WebSiteManagementClient webappClient, String subscriptionID) { _registryClient = registryClient; _registryClient.SubscriptionId = subscriptionID; _webappClient = webappClient; _webappClient.SubscriptionId = subscriptionID; }
/// <summary> /// Provisions all the components in the <see cref="DevOpsFlexDbContext"/>. /// </summary> /// <param name="context">The database context that we want to provision components from.</param> /// <param name="subscriptionId">The subscription Id where we want to provision in.</param> /// <param name="settingsPath">The path to the settings file with the management certificate.</param> /// <returns>The async <see cref="Task"/> wrapper.</returns> public static Task[] ProvisionAll(this DevOpsFlexDbContext context, string subscriptionId, string settingsPath) { Contract.Requires(context != null); Contract.Requires(!string.IsNullOrEmpty(subscriptionId)); Contract.Requires(!string.IsNullOrEmpty(settingsPath)); var azureSubscription = new AzureSubscription(settingsPath, subscriptionId); var azureCert = new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate)); var computeClient = new ComputeManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var networkClient = new NetworkManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var sbClient = new ServiceBusManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var sqlClient = new SqlManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var storageClient = new StorageManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var webSiteClient = new WebSiteManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)); var foo = context.Components.Include(o => o.System).OfType <AzureCloudService>().ToList().ProvisionAllAsync(computeClient) .Concat(context.Components.Include(o => o.System).OfType <AzureCloudService>().ToList().ReserveAllIpsAsync(networkClient)) .Concat(context.Components.Include(o => o.System).OfType <AzureServiceBusNamespace>().ToList().ProvisionAllAsync(sbClient)) .Concat(context.Components.Include(o => o.System).OfType <SqlAzureDb>().ToList().ProvisionAllAsync(sqlClient)) .Concat(context.Components.Include(o => o.System).OfType <AzureStorageContainer>().ToList().ProvisionAllAsync(storageClient)) .Concat(context.Components.Include(o => o.System).OfType <AzureWebSite>().ToList().ProvisionAllAsync(webSiteClient)) .ToArray(); return(foo); }
private async Task ShouldExecute(CloudOdsApiOperationContext context) { var token = await GetAccessTokenCredentialsAsync(); var site = await GetApiWebsiteAsync(context.TargetEnvironment); var client = new WebSiteManagementClient(token) { SubscriptionId = DefaultAzureActiveDirectoryClientInfo.SubscriptionId }; var settings = await client.Sites.ListSiteAppSettingsAsync(DefaultTestCloudOdsInstance.SystemName, site.Name); settings.Properties[CloudOdsApiWebsiteSettings.BearerTokenTimeoutSettingName] = "20"; settings.Properties[CloudOdsApiWebsiteSettings.LogLevelSettingName] = LogLevel.Warn.DisplayName; await client.Sites.UpdateSiteAppSettingsAsync(DefaultTestCloudOdsInstance.SystemName, site.Name, settings); var getAzureCloudOdsHostedInstanceQuery = new GetAzureCloudOdsHostedInstanceQuery(DefaultAzureActiveDirectoryClientInfo, DefaultTokenCache); var getWebsiteQuery = new GetAzureCloudOdsHostedComponentsQuery(DefaultAzureActiveDirectoryClientInfo, DefaultTokenCache, getAzureCloudOdsHostedInstanceQuery); var query = new GetAzureCloudOdsApiWebsiteSettingsQuery(DefaultAzureActiveDirectoryClientInfo, getWebsiteQuery, DefaultTokenCache, getAzureCloudOdsHostedInstanceQuery); var result = await query.Execute(context); result.BearerTokenTimeoutInMinutes.ShouldBe(20); result.LogLevel.ShouldBe(LogLevel.Warn); }
/// <summary> /// Flow to create a new SwapGroup /// </summary> /// <returns></returns> private static async Task CreateSwapGroup() { Console.WriteLine("Creating new Swap Group"); //Get GroupName Console.WriteLine("Enter new group name:"); var groupName = Console.ReadLine(); SwapGroup newGroup = new SwapGroup(); newGroup.Name = groupName; var client = new WebSiteManagementClient(credentials); client.SubscriptionId = subscriptionId; var resourceClient = new ResourceManagementClient(credentials); resourceClient.SubscriptionId = subscriptionId; var resourceGroups = resourceClient.ResourceGroups.List(); var resourceGroepMenu = new TypedMenu <ResourceGroup>(resourceGroups.ToList(), "Choose a resource group", x => x.Name); var resourceGroup = resourceGroepMenu.Display(); var allWebsites = client.WebApps.ListByResourceGroup(resourceGroup.Name).ToList(); AskForSlot(newGroup, resourceGroup, client, allWebsites); //Save group //Write JSON to file _groupFileService.SaveGroupToFile(newGroup); Console.WriteLine("Saved SwapSlots Group {0} with {1} SwapSlots", newGroup.Name, newGroup.SwapSlots.Count); }
public static SitePublishProfile GetPublishProperties(AzureAccount account, AzureTargetSite targetSite) { Log.Verbose($"Service Management endpoint is {account.ServiceManagementEndpointBaseUri}"); Log.Verbose($"Retrieving publishing profile for {targetSite.SiteAndSlotLegacy}"); using (var cloudClient = new WebSiteManagementClient( new CertificateCloudCredentials(account.SubscriptionNumber, new X509Certificate2(account.CertificateBytes)), new Uri(account.ServiceManagementEndpointBaseUri))) { var webApp = cloudClient.WebSpaces.List() .SelectMany(webSpace => cloudClient.WebSpaces.ListWebSites(webSpace.Name, new WebSiteListParameters())) .FirstOrDefault(webSite => webSite.Name.Equals(targetSite.SiteAndSlotLegacy, StringComparison.OrdinalIgnoreCase)); if (webApp == null) { throw new CommandException($"Could not find Azure WebSite '{targetSite.SiteAndSlotLegacy}' in subscription '{account.SubscriptionNumber}'"); } Log.Verbose("Retrieving publishing profile..."); var publishProfile = cloudClient.WebSites.GetPublishProfile(webApp.WebSpace, targetSite.SiteAndSlotLegacy) .PublishProfiles.First(x => x.PublishMethod.StartsWith("MSDeploy")); Log.Verbose($"Retrieved publishing profile: URI: {publishProfile.PublishUrl} UserName: {publishProfile.UserName}"); return(new SitePublishProfile(publishProfile.UserName, publishProfile.UserPassword, new Uri("https://" + publishProfile.PublishUrl))); } }
public static SitePublishProfile GetPublishProperties(string subscriptionId, string siteName, string tenantId, string applicationId, string password) { var token = ServicePrincipal.GetAuthorizationToken(tenantId, applicationId, password); using (var resourcesClient = new ResourceManagementClient(new TokenCloudCredentials(subscriptionId, token))) using (var webSiteClient = new WebSiteManagementClient(new TokenCredentials(token)) { SubscriptionId = subscriptionId }) { // Because we only know the site name, we need to search the ResourceGroups to find it var resourceGroups = resourcesClient.ResourceGroups.List(new ResourceGroupListParameters()).ResourceGroups.Select(rg => rg.Name).ToList(); foreach (var resourceGroup in resourceGroups) { var sites = webSiteClient.Sites.GetSites(resourceGroup, null, null, true).Value; var matchingSite = sites.FirstOrDefault(x => x.Name.Equals(siteName, StringComparison.OrdinalIgnoreCase)); if (matchingSite == null) { continue; } // Once we know the Resource Group, we have to POST a request to the URI below to retrieve the publishing credentials var publishSettingsUri = new Uri(resourcesClient.BaseUri, $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{matchingSite.Name}/config/publishingCredentialz/list?api-version=2015-08-01"); Log.Verbose($"Retrieving publishing profile from {publishSettingsUri}"); SitePublishProfile publishProperties = null; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = publishSettingsUri }; // Add the authentication headers var requestTask = resourcesClient.Credentials.ProcessHttpRequestAsync(request, new CancellationToken()) .ContinueWith(authResult => resourcesClient.HttpClient.SendAsync(request), TaskContinuationOptions.NotOnFaulted) .ContinueWith(publishSettingsResponse => { var result = publishSettingsResponse.Result.Result; if (!result.IsSuccessStatusCode) { Log.Error($"Retrieving publishing credentials failed. Publish-settings URI: {publishSettingsUri}"); throw new Exception($"Retrieving publishing credentials failed with HTTP status {(int)result.StatusCode} - {result.ReasonPhrase}"); } dynamic response = JObject.Parse(result.Content.AsString()); string publishUserName = response.properties.publishingUserName; string publishPassword = response.properties.publishingPassword; string scmUri = response.properties.scmUri; Log.Verbose($"Retrieved publishing profile. URI: {scmUri} UserName: {publishUserName}"); publishProperties = new SitePublishProfile(publishUserName, publishPassword, new Uri(scmUri)); }, TaskContinuationOptions.NotOnFaulted); requestTask.Wait(); return(publishProperties); } throw new CommandException($"Could not find Azure WebSite '{siteName}' in subscription '{subscriptionId}'"); } }
public static async Task <IPage <Certificate> > ListCertificatesAsync(this WebSiteManagementClient Client, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await Client.ListCertificatesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public static KuduRestClient GetKuduClient(this WebSiteManagementClient client, IAzureWebAppEnvironment settings) { var user = client.WebApps.GetPublsihingCredentialSiteOrSlot(settings.ResourceGroupName, settings.WebAppName, settings.SiteSlotName); var site = client.WebApps.GetSiteOrSlot(settings.ResourceGroupName, settings.WebAppName, settings.SiteSlotName); var defaultHostName = site.DefaultHostName; return new KuduRestClient(MakeScmUri(defaultHostName,settings), user.PublishingUserName, user.PublishingPassword); }
public async Task Execute(RunningDeployment context) { // Read/Validate variables Log.Verbose("Starting App Settings Deploy"); var variables = context.Variables; var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); if (webAppName == null) { throw new Exception("Web App Name must be specified"); } var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); if (resourceGroupName == null) { throw new Exception("resource group name must be specified"); } var targetSite = AzureWebAppHelper.GetAzureTargetSite(webAppName, slotName, resourceGroupName); string token = await Auth.GetAuthTokenAsync(principalAccount); var webAppClient = new WebSiteManagementClient(new Uri(principalAccount.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) { SubscriptionId = principalAccount.SubscriptionNumber, HttpClient = { BaseAddress = new Uri(principalAccount.ResourceManagementEndpointBaseUri) } }; // If app settings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.AppSettings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.AppSettings])) { var appSettingsJson = variables.Get(SpecialVariables.Action.Azure.AppSettings, ""); Log.Verbose($"Updating application settings:\n{appSettingsJson}"); var appSettings = JsonConvert.DeserializeObject <AppSetting[]>(appSettingsJson); await PublishAppSettings(webAppClient, targetSite, appSettings, token); Log.Info("Updated application settings"); } // If connection strings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.ConnectionStrings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.ConnectionStrings])) { var connectionStringsJson = variables.Get(SpecialVariables.Action.Azure.ConnectionStrings, ""); Log.Verbose($"Updating connection strings:\n{connectionStringsJson}"); var connectionStrings = JsonConvert.DeserializeObject <ConnectionStringSetting[]>(connectionStringsJson); await PublishConnectionStrings(webAppClient, targetSite, connectionStrings); Log.Info("Updated connection strings"); } }
public static WebDeployPublishSettings GetPublishProperties(AzureServicePrincipalAccount account, string resourceGroupName, AzureTargetSite azureTargetSite) { if (account.ResourceManagementEndpointBaseUri != DefaultVariables.ResourceManagementEndpoint) { Log.Info("Using override for resource management endpoint - {0}", account.ResourceManagementEndpointBaseUri); } if (account.ActiveDirectoryEndpointBaseUri != DefaultVariables.ActiveDirectoryEndpoint) { Log.Info("Using override for Azure Active Directory endpoint - {0}", account.ActiveDirectoryEndpointBaseUri); } var token = ServicePrincipal.GetAuthorizationToken(account.TenantId, account.ClientId, account.Password, account.ResourceManagementEndpointBaseUri, account.ActiveDirectoryEndpointBaseUri); var baseUri = new Uri(account.ResourceManagementEndpointBaseUri); using (var resourcesClient = new ResourceManagementClient(new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber, BaseUri = baseUri, }) using (var webSiteClient = new WebSiteManagementClient(new Uri(account.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber }) { webSiteClient.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 3)); resourcesClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); resourcesClient.HttpClient.BaseAddress = baseUri; Log.Verbose($"Looking up site {azureTargetSite.Site} {(string.IsNullOrWhiteSpace(resourceGroupName) ? string.Empty : $"in resourceGroup {resourceGroupName}")}"); Site matchingSite; if (string.IsNullOrWhiteSpace(resourceGroupName)) { matchingSite = FindSiteByNameWithRetry(account, azureTargetSite, webSiteClient) ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite)); resourceGroupName = matchingSite.ResourceGroup; } else { var site = webSiteClient.WebApps.Get(resourceGroupName, azureTargetSite.Site); Log.Verbose("Found site:"); LogSite(site); matchingSite = site ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite, resourceGroupName)); } // ARM resource ID of the source app. App resource ID is of the form: // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName} for production slots and // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/slots/{slotName} for other slots. // We allow the slot to be defined on both the target directly (which will come through on the matchingSite.Name) or on the // step for backwards compatibility with older Azure steps. if (azureTargetSite.HasSlot) { Log.Verbose($"Using the deployment slot {azureTargetSite.Slot}"); } return(GetWebdeployPublishProfile(webSiteClient, resourceGroupName, matchingSite.Name, azureTargetSite.HasSlot ? azureTargetSite.Slot : null).GetAwaiter().GetResult()); }
public static async Task Main(string[] args) { var credentials = await GetTokenCredentialsAsync().ConfigureAwait(false); _webClient = new WebSiteManagementClient(credentials) { SubscriptionId = _subscriptionId }; _resourceClient = new ResourceManagementClient(credentials) { SubscriptionId = _subscriptionId }; Console.WriteLine("Enter name of site without spaces: "); var newSiteName = Console.ReadLine(); Console.WriteLine("Enter the name of the app service plan witnout spaces:"); var newAppServicePlanName = Console.ReadLine(); Console.WriteLine("Enter the name of the resource group without spaces:"); var newResourceGroupName = Console.ReadLine(); Console.Clear(); Console.WriteLine("Creating site." + Environment.NewLine + "Please wait."); //Create resource group var resourceGroup = await _resourceClient.ResourceGroups .CreateOrUpdateAsync(newResourceGroupName, new ResourceGroup(_location)).ConfigureAwait(false); if (resourceGroup == null) { return; } //Create app service plan var appServicePlan = await _webClient.AppServicePlans .CreateOrUpdateAsync(resourceGroup.Name, newAppServicePlanName, new AppServicePlan(_location)).ConfigureAwait(false); if (appServicePlan == null) { return; } //Create site Site website = await _webClient.WebApps.CreateOrUpdateAsync(resourceGroup.Name, newSiteName, new Site(_location, null, newSiteName) { ServerFarmId = appServicePlan.Id }).ConfigureAwait(false); if (website == null) { return; } Console.Clear(); Console.WriteLine($"New {website.Name} was successfully created. And has state {website.State}."); Console.WriteLine($"Hostname is - {website.DefaultHostName}"); Console.ReadKey(); }
public WebSiteManagementClient GetWebSiteManagementClient(RecordedDelegatingHandler handler) { handler.IsPassThrough = false; var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123"); var client = new WebSiteManagementClient(token).WithHandler(handler); client = client.WithHandler(handler); return(client); }
public static void SwapSlotSlot(this ICakeContext ctx, ServiceClientCredentials credentials, string subscriptionId, string resourceGroupName, string websiteName, string srcSlot, string destSlot, bool preserveVnet) { var client = new WebSiteManagementClient(credentials) { SubscriptionId = subscriptionId }; client.WebApps.SwapSlotSlot(resourceGroupName, websiteName, new CsmSlotEntity(destSlot, preserveVnet), srcSlot); }
public SharedFunctions(IHttpClientFactory httpClientFactory, LookupClient lookupClient, IAcmeProtocolClientFactory acmeProtocolClientFactory, WebSiteManagementClient webSiteManagementClient, DnsManagementClient dnsManagementClient) { _httpClientFactory = httpClientFactory; _lookupClient = lookupClient; _acmeProtocolClientFactory = acmeProtocolClientFactory; _webSiteManagementClient = webSiteManagementClient; _dnsManagementClient = dnsManagementClient; }
private void SetupManagementClients(MockContext context) { ResourceManagementClient = GetResourceManagementClient(context); LogicManagementClient = GetLogicManagementClient(context); WebsiteManagementClient = GetWebsiteManagementClient(context); _helper.SetupManagementClients(ResourceManagementClient, LogicManagementClient, WebsiteManagementClient); }