Partilhar via


Usar SDKs do Azure para criar uma máquina virtual

Use os SDKs do Azure para criar e excluir uma máquina virtual do Azure.

Configurar o ambiente de desenvolvimento

  • Uma conta de usuário do Azure com uma assinatura ativa. Crie um gratuitamente.
  • Node.js LTS com NPM, o gerenciador de pacotes Node.js instalado em sua máquina local.
  • Visual Studio Code instalado em sua máquina local.
  • Crie uma entidade de serviço e copie o Tenant Id, Client ID, Client secret.
  • Use a página de assinatura do portal do Azure para localizar sua ID de assinatura, copie esse valor para usar nesses scripts.

Máquinas virtuais do Azure

Uma máquina virtual do Azure requer vários recursos para dar suporte à máquina virtual. A melhor maneira de gerenciar esses recursos é criar todos os recursos em um único grupo de recursos. O script cria o grupo de recursos e posta um número aleatório para garantir que o grupo de recursos seja exclusivo, independentemente de quantas vezes você usar o script.

Os recursos criados nesses scripts incluem:

Criar uma máquina virtual

  1. Crie um arquivo com o nome ou copie o create-vm.js arquivo do GitHub.

    const util = require("util");
    const {
      ClientSecretCredential,
      DefaultAzureCredential,
    } = require("@azure/identity");
    const { ComputeManagementClient } = require("@azure/arm-compute");
    const { ResourceManagementClient } = require("@azure/arm-resources");
    const { StorageManagementClient } = require("@azure/arm-storage");
    const { NetworkManagementClient } = require("@azure/arm-network");
    
    // Store function output to be used elsewhere
    let randomIds = {};
    let subnetInfo = null;
    let publicIPInfo = null;
    let vmImageInfo = null;
    let nicInfo = null;
    
    // CHANGE THIS - used as prefix for naming resources
    const yourAlias = "diberry";
    
    // CHANGE THIS - used to add tags to resources
    const projectName = "azure-samples-create-vm";
    
    // Resource configs
    const location = "eastus";
    const accType = "Standard_LRS";
    
    // Ubuntu config for VM
    const publisher = "Canonical";
    const offer = "UbuntuServer";
    const sku = "14.04.3-LTS";
    const adminUsername = "notadmin";
    const adminPassword = "Pa$$w0rd92";
    
    // Azure authentication in environment variables for DefaultAzureCredential
    const tenantId =
      process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID";
    const clientId =
      process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID";
    const secret =
      process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";
    const subscriptionId =
      process.env["AZURE_SUBSCRIPTION_ID"] || "REPLACE-WITH-YOUR-SUBSCRIPTION_ID";
    
    let credentials = null;
    
    if (process.env.production) {
      // production
      credentials = new DefaultAzureCredential();
    } else {
      // development
      credentials = new ClientSecretCredential(tenantId, clientId, secret);
      console.log("development");
    }
    // Azure services
    const resourceClient = new ResourceManagementClient(
      credentials,
      subscriptionId
    );
    const computeClient = new ComputeManagementClient(credentials, subscriptionId);
    const storageClient = new StorageManagementClient(credentials, subscriptionId);
    const networkClient = new NetworkManagementClient(credentials, subscriptionId);
    
    // Create resources then manage them (on/off)
    async function createResources() {
      try {
        result = await createResourceGroup();
        accountInfo = await createStorageAccount();
        vnetInfo = await createVnet();
        subnetInfo = await getSubnetInfo();
        publicIPInfo = await createPublicIP();
        nicInfo = await createNIC(subnetInfo, publicIPInfo);
        vmImageInfo = await findVMImage();
        nicResult = await getNICInfo();
        vmInfo = await createVirtualMachine(nicInfo.id, vmImageInfo[0].name);
        return;
      } catch (err) {
        console.log(err);
      }
    }
    
    async function createResourceGroup() {
      console.log("\n1.Creating resource group: " + resourceGroupName);
      const groupParameters = {
        location: location,
        tags: { project: projectName },
      };
      const resCreate = await resourceClient.resourceGroups.createOrUpdate(
        resourceGroupName,
        groupParameters
      );
      return resCreate;
    }
    
    async function createStorageAccount() {
      console.log("\n2.Creating storage account: " + storageAccountName);
      const createParameters = {
        location: location,
        sku: {
          name: accType,
        },
        kind: "Storage",
        tags: {
          project: projectName,
        },
      };
      return await storageClient.storageAccounts.beginCreateAndWait(
        resourceGroupName,
        storageAccountName,
        createParameters
      );
    }
    
    async function createVnet() {
      console.log("\n3.Creating vnet: " + vnetName);
      const vnetParameters = {
        location: location,
        addressSpace: {
          addressPrefixes: ["10.0.0.0/16"],
        },
        dhcpOptions: {
          dnsServers: ["10.1.1.1", "10.1.2.4"],
        },
        subnets: [{ name: subnetName, addressPrefix: "10.0.0.0/24" }],
      };
      return await networkClient.virtualNetworks.beginCreateOrUpdateAndWait(
        resourceGroupName,
        vnetName,
        vnetParameters
      );
    }
    
    async function getSubnetInfo() {
      console.log("\nGetting subnet info for: " + subnetName);
      const getResult = await networkClient.subnets.get(
        resourceGroupName,
        vnetName,
        subnetName
      );
      return getResult;
    }
    
    async function createPublicIP() {
      console.log("\n4.Creating public IP: " + publicIPName);
      const publicIPParameters = {
        location: location,
        publicIPAllocationMethod: "Dynamic",
        dnsSettings: {
          domainNameLabel: domainNameLabel,
        },
      };
      return await networkClient.publicIPAddresses.beginCreateOrUpdateAndWait(
        resourceGroupName,
        publicIPName,
        publicIPParameters
      );
    }
    
    async function createNIC(subnetInfo, publicIPInfo) {
      console.log("\n5.Creating Network Interface: " + networkInterfaceName);
      const nicParameters = {
        location: location,
        ipConfigurations: [
          {
            name: ipConfigName,
            privateIPAllocationMethod: "Dynamic",
            subnet: subnetInfo,
            publicIPAddress: publicIPInfo,
          },
        ],
      };
      return await networkClient.networkInterfaces.beginCreateOrUpdateAndWait(
        resourceGroupName,
        networkInterfaceName,
        nicParameters
      );
    }
    
    async function findVMImage() {
      console.log(
        util.format(
          "\nFinding a VM Image for location %s from " +
            "publisher %s with offer %s and sku %s",
          location,
          publisher,
          offer,
          sku
        )
      );
      const listResult = new Array();
      for await (const item of computeClient.virtualMachineImages.list(
        location,
        publisher,
        offer,
        sku
      )) {
        listResult.push(item);
      }
      return listResult;
    }
    
    async function getNICInfo() {
      return await networkClient.networkInterfaces.get(
        resourceGroupName,
        networkInterfaceName
      );
    }
    
    async function createVirtualMachine() {
      const vmParameters = {
        location: location,
        osProfile: {
          computerName: vmName,
          adminUsername: adminUsername,
          adminPassword: adminPassword,
        },
        hardwareProfile: {
          vmSize: "Standard_B1ls",
        },
        storageProfile: {
          imageReference: {
            publisher: publisher,
            offer: offer,
            sku: sku,
            version: vmImageVersionNumber,
          },
          osDisk: {
            name: osDiskName,
            caching: "None",
            createOption: "fromImage",
            vhd: {
              uri:
                "https://" +
                storageAccountName +
                ".blob.core.windows.net/nodejscontainer/osnodejslinux.vhd",
            },
          },
        },
        networkProfile: {
          networkInterfaces: [
            {
              id: nicId,
              primary: true,
            },
          ],
        },
      };
      console.log("6.Creating Virtual Machine: " + vmName);
      console.log(
        " VM create parameters: " + util.inspect(vmParameters, { depth: null })
      );
      const resCreate = await computeClient.virtualMachines.beginCreateOrUpdateAndWait(
        resourceGroupName,
        vmName,
        vmParameters
      );
      return await computeClient.virtualMachines.get(
        resourceGroupName,
        vmName
      );
    }
    
    const _generateRandomId = (prefix, existIds) => {
      var newNumber;
      while (true) {
        newNumber = prefix + Math.floor(Math.random() * 10000);
        if (!existIds || !(newNumber in existIds)) {
          break;
        }
      }
      return newNumber;
    };
    
    //Random number generator for service names and settings
    const resourceGroupName = _generateRandomId(`${yourAlias}-testrg`, randomIds);
    const vmName = _generateRandomId(`${yourAlias}vm`, randomIds);
    const storageAccountName = _generateRandomId(`${yourAlias}ac`, randomIds);
    const vnetName = _generateRandomId(`${yourAlias}vnet`, randomIds);
    const subnetName = _generateRandomId(`${yourAlias}subnet`, randomIds);
    const publicIPName = _generateRandomId(`${yourAlias}pip`, randomIds);
    const networkInterfaceName = _generateRandomId(`${yourAlias}nic`, randomIds);
    const ipConfigName = _generateRandomId(`${yourAlias}crpip`, randomIds);
    const domainNameLabel = _generateRandomId(`${yourAlias}domainname`, randomIds);
    const osDiskName = _generateRandomId(`${yourAlias}osdisk`, randomIds);
    
    async function main() {
      await createResources();
    }
    
    main()
      .then(() => {
        console.log(
          `success - resource group name: ${resourceGroupName}, vm resource name: ${vmName}`
        );
      })
      .catch((err) => {
        console.log(err);
      });
    

    Os métodos SDK usados neste script incluem:

  2. Instale os pacotes npm usados no trabalho do Azure:

    npm init -y && install @azure/identity @azure/arm-compute @azure/arm-network @azure/arm-resources @azure/arm-storage
    
  3. Para desenvolvimento local, altere variáveis no arquivo para autenticação:

    // Azure authentication in environment variables for DefaultAzureCredential
    const tenantId =
      process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID";
    const clientId =
      process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID";
    const secret =
      process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";
    const subscriptionId =
      process.env["AZURE_SUBSCRIPTION_ID"] || "REPLACE-WITH-YOUR-SUBSCRIPTION_ID";    
    
  4. Alterar variáveis para nomenclatura de recursos:

    // CHANGE THIS - used as prefix for naming resources
    const yourAlias = "johnsmith";
    
    // CHANGE THIS - used to add tags to resources
    const projectName = "azure-samples-create-vm"
    
  5. Execute o código para criar uma VM:

    node create-vm.js
    

    A saída inclui o nome do grupo de recursos:

    success - resource group name: johnsmith-testrg1689
    

Clean up resources (Limpar recursos)

Quando terminar de usar a máquina virtual, exclua o grupo de recursos.

  1. Crie um arquivo com o nome ou copie o delete-resources.js arquivo do GitHub.

    const {
      ClientSecretCredential,
      DefaultAzureCredential,
    } = require("@azure/identity");
    const { ResourceManagementClient } = require("@azure/arm-resources");
    
    // Azure authentication in environment variables for DefaultAzureCredential
    let credentials = null;
    const tenantId =
      process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID";
    const clientId =
      process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID";
    const secret =
      process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";
    const subscriptionId =
      process.env["AZURE_SUBSCRIPTION_ID"] || "REPLACE-WITH-YOUR-SUBSCRIPTION_ID";
    
    const resourceGroupName = "REPLACE-WITH-YOUR-RESOURCE_GROUP-NAME";
    
    if (process.env.production) {
      // production
      credentials = new DefaultAzureCredential();
    } else {
      // development
      credentials = new ClientSecretCredential(tenantId, clientId, secret);
      console.log("development");
    }
    
    async function deleteResourceGroup() {
      // Create Azure SDK client for Resource Management such as resource groups
      const resourceClient = new ResourceManagementClient(
        credentials,
        subscriptionId
      );
    
      const result = await resourceClient.resourceGroups.deleteMethod(
        resourceGroupName
      );
      console.log(JSON.stringify(result));
    }
    
    deleteResourceGroup()
      .then((result) => {
        console.log(result);
      })
      .catch((ex) => {
        console.log(ex);
      });
    
  2. Para desenvolvimento local, altere variáveis no arquivo para autenticação:

    // Azure authentication in environment variables for DefaultAzureCredential
    const tenantId =
      process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID";
    const clientId =
      process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID";
    const secret =
      process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";
    const subscriptionId =
      process.env["AZURE_SUBSCRIPTION_ID"] || "REPLACE-WITH-YOUR-SUBSCRIPTION_ID";    
    
  3. Obtenha o nome do grupo de recursos, que foi retornado como a última linha do script de criação e altere a variável no script delete:

    const resourceGroupName = "REPLACE-WITH-YOUR-RESOURCE_GROUP-NAME";
    
  4. Execute o código para criar uma VM:

    node delete-resources.js
    

    A eliminação pode demorar alguns minutos.

    Os métodos SDK usados neste script incluem:

Próximos passos