Azure 容器实例 - .net sdk - 更改环境变量并重新启动任务容器

Azure Container Instances - .net sdk - change environment variable and restart task container

我已经部署了一个容器组,其中只有一个容器,重启策略为从不。我想再次 运行 这个容器,但使用不同的环境变量。我在 powershell 和 azure cmdlet 中看到了执行此操作的方法,但 Azure .net SDK 并不清楚如何实现此操作。

有人对如何使用 Fluent API 实现这一目标有任何指示吗?这对我很有用,因为不需要再次拉取图像,只需重新启动容器实例即可。

当你想再次运行这个容器时,意味着你需要更新这个容器组的配置,即使你只想更改环境变量。详细了解Update containers. For Azure Container Instance, the update means to create again. For .NET, you can use the IWithEnvironmentVariables in the Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Definition设置环境变量,然后重新创建容器组。

我不确定您是否能够阻止镜像在容器启动时再次被拉取。我经常看到 ACI 在重新启动时再次拉入图像,而不管之前是否拉过完全相同的图像。我想这就是无服务器的真正含义 ;)

从您的问题来看,您并不完全清楚您要实现的目标以及使用环境变量重新启动容器是否是执行此操作的最佳方法。

所以在不知道具体细节的情况下,这里有一些想法:

如果您 运行 偶尔使用容器并且只是想给它一些指令,您可以考虑从参数化 ARM 模板重新部署容器。肯定可以通过ARM模板传入环境变量。

您可以将 Azure 存储帐户中的文件共享装载到容器中,并 运行 从那里加载变量的脚本。您将要处理的数据上传到文件共享并启动容器。

我已将其用于 运行 通用容器中的任意 (.NET) 可执行文件,例如用于测试目的。

对于更频繁的 运行s,您可以将配置数据粘贴到数据库、队列或 blob 中,然后从容器中进行处理。 Blob 和队列可以很容易地绑定到 Azure Functions,这样你就可以拥有一个在有工作要处理时自动启动容器的函数。

从你的问题来看,我猜你正在寻找一些 .NET 代码来实现这一点。管理 SDK 中似乎对此提供了一些支持,但到目前为止我无法让它工作:

using System.Threading.Tasks;
using Microsoft.Azure.Management.ContainerInstance.Fluent;
using Microsoft.Azure.Management.ContainerInstance.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;

// ...

public static async Task SetEnvAndStart(string varName, string customValue)
{
    // connect to Azure
    var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
        Configuration.ClientId(), 
        Configuration.ClientSecret(), 
        Configuration.TenantId(), 
        AzureEnvironment.AzureGlobalCloud);            

    var azure = await Azure.Authenticate(credentials).WithDefaultSubscriptionAsync();
    // Find your container group
    var containerGroup = await azure.ContainerGroups.GetByIdAsync("<resource id>");
    // Add the environment variable
    containerGroup.Containers["mycontainer"].EnvironmentVariables.Add(new EnvironmentVariable(varName, customValue));
    // Apply the changes
    await containerGroup.Update().ApplyAsync();
    // Restart the container
    await ContainerGroupsOperationsExtensions.StartAsync(containerGroup.Manager.Inner.ContainerGroups, containerGroup.ResourceGroupName, containerGroup.Name);
}

如果您真的想使用环境变量,我认为最好的办法是重新创建容器。您可能会发现 some of the example code 对 Azure 管理 SDK 很有帮助。