使用Azure Cli创建自定义Azure镜像
分类: Azure虚拟机 ◆ 标签: #虚拟机 #Linux #Azure #基础 ◆ 发布于: 2023-05-27 21:02:28

定制镜像和在Azure市场的镜像是类似的,Azure提供了工具可以自己创建自己需要的镜像,创建自定义的镜像可以非常方便的为了某些任务定制,而且很容易使用定制的镜像进行扩展。如果需要在Azure上定制镜像请参考本章如下的步骤:
创建一个Shared Image Gallery
创建镜像定义
创建镜像版本
从镜像中创建虚拟机
分享Image Gallery
Shared Image Gallery
是由Azure提供的工具,方便用户创建自定义镜像,关于Shared Image Gallery
有一些基本的概念需要理解:
镜像源:镜像源可以是一个已经存在的虚拟机主机,也可以是一个快照,
Shared Image Gallery
使用它来创建一个版本的镜像。镜像Gallery: 和Azure市场类似,是一个私人的镜像库,帮助用户分享和管理自定义镜像。
镜像定义(Image definition): 类似一个配置文件,不过它存储在
Shared Image Gallery
中,用于定义自定义镜像的相关信息。镜像版本(Image Version): 镜像版本是
Shared Image Gallery
用于创建虚拟机的实体。类似于镜像的版本管理。
开始之前
由于自定义的镜像需要一台虚拟机作为蓝本,因此您可以参考这个系列的第一篇来创建一个现成的虚拟机,以便于完成本章的教程。
然后需要注意本章教程最好是在Azure PowerShell
环境下运行Azure Cli
, 如果想了解Powershell
和Azure Cli
的安装和使用,请参考我们之前的系列文章。包括使用Azure Cli登录云环境,设定默认的订阅等等。
创建一个Image Gallery
我们前面学习了Image Gallery
是我们用于创建自定义镜像的主要工具,我们先来创建它。
az group create --name myGalleryRG --location eastus
az sig create --resource-group myGalleryRG --gallery-name myGallery
我们现在已经创建好了一个Image Gallery
, 那么我们接下来需要之前准备好的虚拟机的基本信息,通过如下的命令拿到虚拟机的基本信息:
az vm list --output table
查询该虚拟机的resource id
az vm get-instance-view -g MyResourceGroup -n MyVm --query id
创建镜像定义
我们使用如下的指令创建一个镜像的定义:
az sig image-definition create \
--resource-group myGalleryRG \
--gallery-name myGallery \
--gallery-image-definition myImageDefinition \
--publisher myPublisher \
--offer myOffer \
--sku mySKU \
--os-type Linux \
--os-state specialized
注意我们在这个镜像定义里指定了需要使用的Image Gallery
以及 指定了OS的类型以及特定的Linux镜像。
有了镜像的定义之后,我们需要根据该定义创建一个镜像版本(实际上就已经是一个镜像了)
创建镜像版本
创建镜像版本我们需要使用到之前查询到的已经存在的虚拟机的resource id, 命令如下:
az sig image-version create \
--resource-group myGalleryRG \
--gallery-name myGallery \
--gallery-image-definition myImageDefinition \
--gallery-image-version 1.0.0 \
--target-regions "chinaeast2" "southcentralus=1" "eastus=1=standard_zrs" \
--replica-count 2 \
--managed-image "/subscriptions/<Subscription ID>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"
同时指定了该镜像可以使用的region。
到这里我们自定义的镜像算是结束了,那么接下来我们使用该镜像来创建一个虚拟机作为实验。
创建虚拟机
使用自定义镜像来创建虚拟机使用如下的命令:
az group create --name myResourceGroup --location eastus
az vm create --resource-group myResourceGroup \
--name myVM \
--image "/subscriptions/<Subscription ID>/resourceGroups/myGalleryRG/providers/Microsoft.Compute/galleries/myGallery/images/myImageDefinition" \
--specialized
通过如上的命令即能创建一个虚拟机。
有了自定义的镜像之后如何分享到自己的组织中?
分享Image Gallery
可以使用如下的方式分享:
az sig show \
--resource-group myGalleryRG \
--gallery-name myGallery \
--query id
az role assignment create \
--role "Reader" \
--assignee <email address> \
--scope <gallery ID>
但是需要注意的是Azure使用RBAC通过AAD进行权限控制,关于这个部分,您可以参考:https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli