Partilhar via


Autenticar o Terraform usando o Managed Identity para serviços do Azure

Terraform permite a definição, visualização e implantação de infraestrutura em nuvem. Usando Terraform, você cria arquivos de configuração usando a sintaxe HCL. A sintaxe HCL permite especificar o provedor de nuvem - como o Azure - e os elementos que compõem sua infraestrutura de nuvem. Depois de criar os arquivos de configuração, você cria um plano de execução que permite visualizar as alterações na infraestrutura antes que elas sejam implantadas. Depois de verificar as alterações, você aplica o plano de execução para implantar a infraestrutura.

As identidades gerenciadas para recursos do Azure são usadas para autenticar no Azure Ative Directory. A HashiCorp recomenda o uso de uma entidade de serviço ou identidade gerenciada se você estiver executando o Terraform de maneira não interativa. Existem dois tipos de identidades gerenciadas: atribuídas pelo sistema e atribuídas pelo usuário. Neste artigo, você aprenderá a usar identidades atribuídas ao sistema.

Definir uma identidade gerenciada atribuída ao sistema

Para usar uma identidade gerenciada atribuída ao sistema, use as seguintes etapas:

  1. Especifique o identity bloco e defina type como SystemAssigned.

    resource "azurerm_linux_virtual_machine" "example" {
      # ...
    
      identity {
        type = "SystemAssigned"
      }
    }
    
  2. Conceda a Contributor função à identidade.

    data "azurerm_subscription" "current" {}
    
    data "azurerm_role_definition" "contributor" {
      name = "Contributor"
    }
    
    resource "azurerm_role_assignment" "example" {
      scope              = data.azurerm_subscription.current.id
      role_definition_name = "Contributor"
      principal_id       = azurerm_linux_virtual_machine.example.identity[0].principal_id
    }
    
  3. Configure com variáveis de ambiente, especificando suas credenciais do Azure.

    export ARM_USE_MSI=true
    export ARM_SUBSCRIPTION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    export ARM_TENANT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    

Exemplo: Criar uma máquina virtual com uma identidade gerenciada

  1. Crie um diretório no qual testar o código Terraform de exemplo e torná-lo o diretório atual.

  2. Crie um arquivo chamado providers.tf e insira o código a seguir.

    terraform {
      required_version = ">=0.12"
    
      required_providers {
        azapi = {
          source  = "azure/azapi"
          version = "~>1.5"
        }
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>2.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
  3. Crie um arquivo chamado main.tf e insira o seguinte código:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    data "azurerm_subscription" "current" {}
    
    resource "azurerm_virtual_network" "example" {
      name                = "myVnet"
      address_space       = ["10.0.0.0/16"]
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    }
    
    resource "azurerm_subnet" "example" {
      name                 = "mySubnet"
      resource_group_name  = azurerm_resource_group.rg.name
      virtual_network_name = azurerm_virtual_network.example.name
      address_prefixes     = ["10.0.2.0/24"]
    }
    
    resource "azurerm_network_interface" "example" {
      name                = "myNic"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      ip_configuration {
        name                          = "internal"
        subnet_id                     = azurerm_subnet.example.id
        private_ip_address_allocation = "Dynamic"
      }
    }
    
    resource "azurerm_linux_virtual_machine" "example" {
      name                = "myVm"
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      size                = "Standard_F2"
      network_interface_ids = [
        azurerm_network_interface.example.id,
      ]
    
      computer_name  = "hostname"
      admin_username = var.username
    
      admin_ssh_key {
        username   = var.username
        public_key = azapi_resource_action.ssh_public_key_gen.output.publicKey
      }
    
      identity {
        type = "SystemAssigned"
      }
    
      os_disk {
        caching              = "ReadWrite"
        storage_account_type = "Standard_LRS"
      }
    
      source_image_reference {
        publisher = "Canonical"
        offer     = "0001-com-ubuntu-server-jammy"
        sku       = "22_04-lts"
        version   = "latest"
      }
    }
    
    data "azurerm_role_definition" "contributor" {
      name = "Contributor"
    }
    
    resource "azurerm_role_assignment" "example" {
      scope              = data.azurerm_subscription.current.id
      role_definition_name = "Contributor"
      principal_id       = azurerm_linux_virtual_machine.example.identity[0].principal_id
    }
    
  4. Crie um arquivo chamado ssh.tf e insira o código a seguir.

    resource "random_pet" "ssh_key_name" {
      prefix    = "ssh"
      separator = ""
    }
    
    resource "azapi_resource_action" "ssh_public_key_gen" {
      type        = "Microsoft.Compute/sshPublicKeys@2022-11-01"
      resource_id = azapi_resource.ssh_public_key.id
      action      = "generateKeyPair"
      method      = "POST"
    
      response_export_values = ["publicKey", "privateKey"]
    }
    
    resource "azapi_resource" "ssh_public_key" {
      type      = "Microsoft.Compute/sshPublicKeys@2022-11-01"
      name      = random_pet.ssh_key_name.id
      location  = azurerm_resource_group.rg.location
      parent_id = azurerm_resource_group.rg.id
    }
    
    output "key_data" {
      value = azapi_resource_action.ssh_public_key_gen.output.publicKey
    }
        ```
    
    
  5. Crie um arquivo chamado variables.tf e insira o seguinte código:

    variable "resource_group_location" {
      type        = string
      description = "Location of the resource group."
      default     = "eastus"
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
      default     = "rg"
    }
    
    variable "username" {
      type        = string
      description = "The username for the local account that will be created on the new VM."
      default     = "azureadmin"
    }
    
  6. Crie um arquivo chamado outputs.tf e insira o seguinte código:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "azurerm_linux_virtual_machine_name" {
      value = azurerm_linux_virtual_machine.example.name
    }
    

Próximos passos