记录在容器创建时配置环境变量信息遇到的问题
一、代码
简单解释下代码:
使用配置好的azureResourceManager先查出要使用容器注册表
容器镜像在容器注册表在资源组 container-registry 内名字叫 registry 的容器注册表中
使用自己上传的容器镜像imageName
创建container instanse并设定环境信息后create。
Registry registry = azureResourceManager.containerRegistries().getByResourceGroup("container-registry", "registry");
RegistryCredentials acrCredentials = registry.getCredentials();
String imageName = registry.loginServerUrl() + "/" + image;
ContainerGroup.DefinitionStages.WithNextContainerInstance attach =
(ContainerGroup.DefinitionStages.WithNextContainerInstance) azureResourceManager
.containerGroups()
.define(containerName)
.withRegion(this.region)
.withNewResourceGroup(groupName)
.withLinux()
.withPrivateImageRegistry(registry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY))
.withoutVolume()
.defineContainerInstance(containerGroupName)
.withImage(imageName)
.withExternalTcpPort(80)
.withCpuCoreCount(cpu)
.withMemorySizeInGB(ram)
.withEnvironmentVariables(environment)
.attach();
ContainerGroup container = attach.withNewNetworkProfileOnExistingVirtualNetwork(networkId, subnetName)
.withRestartPolicy(ContainerGroupRestartPolicy.NEVER)
.create();
二、记录遇到的坑
-
简写的坑
在 Azure SDK for Java 中 有很多简写的代码,比如在创建容器实例时
.defineContainerInstance(containerGroupName) .withImage(imageName) .withExternalTcpPort(80) .withCpuCoreCount(cpu) .withMemorySizeInGB(ram)
//上面的简写方法 默认cpu1 memorySize1.5 .withContainerInstance(imageName, 80)
看上面两段代码下方就是上方的简写方法,点进源码内部可以看到他帮我们设置了默认的cpu与内存大小与在平台上创建时一致(截图绿框)并且非常好心的帮你attach,attach本人理解就是平台上的next但代码中的创建流程与平台的创建流程略有不同,平台上配置环境变量是要next两次后配置,但此时azure帮你attach后就无法设置环境变量,但他们下一步都是配置网络 好好好~
@Override public ContainerGroupImpl withContainerInstance(String imageName, int port) { return this .defineContainerInstance(this.name()) .withImage(imageName) .withExternalTcpPort(port) .withCpuCoreCount(1) .withMemorySizeInGB(1.5) .attach(); }
-
稀奇古怪的坑
读者可以看到我代码中创建container代码并没有使用链式调用直接点到create而是在attach后中断后强转了类型后再设置网络后创建,但是在我加环境配置前是可以的当时也很疑惑为什么设置完后返回值变成了Object(懂得大佬帮我解释一下)
可以看到两段代码只有红框内一点不同且设置内存与设置环境的方法返回值是一样的,最后返回Object? 还好强转后的代码没有报错也成功创建了容器实例并设置环境参数。
三、总结
做定制开发肯定会配置很多稀奇古怪的东西,能细节就细节不要偷懒。
尽信AI则无AI。