【问题标题】:How do I start a previously stopped Azure Container instance using C#?如何使用 C# 启动以前停止的 Azure 容器实例?
【发布时间】:2018-12-09 11:00:47
【问题描述】:

我有以下代码来停止一个 Azure 容器实例,并希望使用类似的方法来启动它。

using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

 var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal("XXXX",                "XXXX", "XXXX", AzureEnvironment.AzureGlobalCloud);

        var azure = Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(credentials)
            .WithSubscription("XXXXX");

        var containerName = "mycontainer";
        var containerGroup = azure.ContainerGroups.GetByResourceGroup("myResourceGroup", containerName);
        if (containerGroup.State == "Running")
        {
            containerGroup.Stop();
        }

我也想做同样的事情并启动我的 azure 容器实例。那么 containerGroup.Start() 在哪里? ?这似乎不存在于界面中。我试过使用 containerGroup.Restart();但这在停止状态下不起作用。我需要能够从 C# 代码中执行此操作,并且希望尽可能避免使用 powershell。

【问题讨论】:

  • 新的fluent SDK 还没有更新开始支持,但是已经在路上了!非流利的风格 SDK 有启动支持,如果这对你有用的话。
  • 还有问题吗?或者,如果答案有帮助,您可以接受。
  • 它没有回答我的问题。感谢您的意见
  • 你期待什么答案?以停止状态启动容器组的C#函数?

标签: c# azure azure-container-service


【解决方案1】:

有一种方法可以做到这一点,但它没有在 fluent API 中公开:

using Microsoft.Azure.Management.ContainerInstance.Fluent;

// azure is an instance of IAzure; the fluent Azure API
var resources = await azure.ContainerGroups.ListAsync();

foreach(var containerGroup in resources.Where(aci => aci.State != "Running"))
{
  await ContainerGroupsOperationsExtensions.StartAsync(
           containerGroup.Manager.Inner.ContainerGroups,
           containerGroup.ResourceGroupName, 
           containerGroup.Name);
}

正如其他人所提到的,您确实需要意识到这实际上是在启动一个新容器。除非您在其他地方(例如 mounted volume)坚持,否则不会保留上次运行的状态。

您还需要向执行此代码的人授予适当的权限。我正在使用一个函数,所以我必须设置一个服务帐户和一个角色,这个blog post 包含所有详细信息。

更新 我正在使用的代码在 GitHub 上:https://github.com/alanta/azure_scheduler/blob/master/src/StartACIs.cs

【讨论】:

  • 您好,有什么方法可以在启动容器组之前更改环境变量?文档似乎有点神秘
  • 我不知道管理 API 有什么方法可以做到这一点,但我可以想到一些将数据传递到容器组的替代方法。如果您想要更详细的答案,您可能应该发布一个新问题。
【解决方案2】:

很遗憾,当您停止容器实例时,它们将处于 Terminated 状态,您无法再次启动它们。

无法更新已终止或已删除的容器组。一旦 容器组已停止(处于已终止状态)或已 删除后,该组将作为新组部署。

即使您更新 ACI,也意味着将重新部署 ACI。你可以看看Update containers in Azure Container Instances。此外,当容器实例处于运行状态时,Restart 操作也有效。

因此,C# SDK 中没有适合您的启动功能,至少现在是这样。希望这会对你有所帮助。

更新

看看活动:

每次停止后启动容器组,容器组总是执行以下步骤:拉取镜像 -> 创建容器组 -> 启动容器实例。所以很明显,容器组是在停止后启动时重新创建的。

【讨论】:

  • 如果这是真的,为什么我可以从门户启动它们?如果您看到@Anders 上面的注释表明它将被添加到 fluent SDK 中并且已经存在于非 fluent SDK 中。它也存在于powershell中
  • @johnstaveley 我在答案中显示了测试屏幕截图。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2019-12-08
  • 2015-08-26
  • 2016-08-23
相关资源
最近更新 更多