Share via


Inicio rápido: Creación de un presupuesto Bicep

Los presupuestos en Cost Management le ayudan a planear y dirigir la presentación de cuentas de la organización. Con presupuestos, puede tener en cuenta los servicios de Azure que consume o a los que se suscribe durante un período específico. Le ayudan a informar a otros usuarios sobre sus gastos a fin de administrar de manera proactiva los costos y supervisar cómo avanza el gasto a lo largo del tiempo. Cuando se superan los umbrales presupuestarios que ha creado, se desencadenan las notificaciones. Ninguno de los recursos se ve afectado y no se detiene el consumo. Puede usar los presupuestos para comparar y realizar un seguimiento de gastos para analizar los costos. En este inicio rápido se muestra cómo crear un presupuesto denominado "MyBudget" mediante Bicep.

Bicep es un lenguaje específico de dominio (DSL) que usa una sintaxis declarativa para implementar recursos de Azure. Brinda sintaxis concisa, seguridad de tipos confiable y compatibilidad con la reutilización de código. Bicep ofrece la mejor experiencia de creación para sus soluciones de infraestructura como código en Azure.

Requisitos previos

Si no tiene una suscripción a Azure, cree una cuenta gratuita antes de empezar.

Si tiene una suscripción nueva, no puede crear un presupuesto ni usar las características de Cost Management de inmediato. Para poder hacerlo deberán transcurrir un máximo de 48 horas.

Se admiten los presupuestos para los siguientes tipos de cuentas y ámbitos de Azure:

  • Ámbitos del control de acceso basado en roles de Azure (RBAC de Azure)
    • Grupos de administración
    • Subscription
  • Ámbitos del Contrato Enterprise
    • Cuenta de facturación
    • department
    • Cuenta de inscripción
  • Acuerdos individuales
    • Cuenta de facturación
  • Ámbitos de contrato de cliente de Microsoft
    • Cuenta de facturación
    • Perfil de facturación
    • Sección de factura
    • Customer
  • Ámbitos de AWS
    • Cuenta externa
    • Suscripción externa

Para ver los presupuestos, se necesita al menos acceso de lectura en la cuenta de Azure.

En el caso de las suscripciones con contrato Enterprise de Azure, debe tener acceso de lectura para ver los presupuestos. Para crear y administrar presupuestos, debe tener permiso de colaborador.

Se admiten los siguientes permisos o ámbitos de Azure por suscripción para los presupuestos por usuario y grupo. Para más información sobre los ámbitos, consulte Descripción y uso de ámbitos.

  • Propietario: puede crear, modificar o eliminar los presupuestos de una suscripción.
  • Colaborador y colaborador de Cost Management: puede crear, modificar o eliminar sus propios presupuestos. Puede modificar el importe presupuestario para los presupuestos creados por otros usuarios.
  • Lector y lector de Cost Management: puede ver los presupuestos para los que tiene permiso.

Para más información sobre cómo asignar permisos a los datos de Cost Management, consulte Asignación del acceso a los datos de Cost Management.

Sin filtro

Revisión del archivo de Bicep

El archivo de Bicep usado en este inicio rápido forma parte de las plantillas de inicio rápido de Azure.

targetScope = 'subscription'

@description('Name of the Budget. It should be unique within a resource group.')
param budgetName string = 'MyBudget'

@description('The total amount of cost or usage to track with the budget')
param amount int = 1000

@description('The time covered by a budget. Tracking of the amount will be reset based on the time grain.')
@allowed([
  'Monthly'
  'Quarterly'
  'Annually'
])
param timeGrain string = 'Monthly'

@description('The start date must be first of the month in YYYY-MM-DD format. Future start date should not be more than three months. Past start date should be selected within the timegrain preiod.')
param startDate string

@description('The end date for the budget in YYYY-MM-DD format. If not provided, we default this to 10 years from the start date.')
param endDate string

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param firstThreshold int = 90

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param secondThreshold int = 110

@description('The list of email addresses to send the budget notification to when the threshold is exceeded.')
param contactEmails array

resource budget 'Microsoft.Consumption/budgets@2023-11-01' = {
  name: budgetName
  properties: {
    timePeriod: {
      startDate: startDate
      endDate: endDate
    }
    timeGrain: timeGrain
    amount: amount
    category: 'Cost'
    notifications: {
      NotificationForExceededBudget1: {
        enabled: true
        operator: 'GreaterThan'
        threshold: firstThreshold
        contactEmails: contactEmails
      }
      NotificationForExceededBudget2: {
        enabled: true
        operator: 'GreaterThan'
        threshold: secondThreshold
        contactEmails: contactEmails
      }
    }
  }
}

output name string = budget.name
output resourceId string = budget.id

En el archivo Bicep se define un recurso de Azure:

Implementación del archivo de Bicep

  1. Guarde el archivo de Bicep como main.bicep en el equipo local.

  2. Implemente el archivo de Bicep mediante la CLI de Azure o Azure PowerShell.

    myContactEmails ='("user1@contoso.com", "user2@contoso.com")'
    
    az deployment sub create --name demoSubDeployment --location centralus --template-file main.bicep --parameters startDate=<start-date> endDate=<end-date> contactEmails=$myContactEmails
    

    Debe introducir los parámetros siguientes:

    • startDate: reemplace <start-date> por la fecha de inicio. Debe ser el primero del mes en formato AAAA-MM-DD. La fecha de inicio futura no puede ser superior a tres meses en el futuro. Se debe seleccionar una fecha de inicio anterior dentro del período del valor de timegrain.
    • endDate: reemplace <end-date> por la fecha de finalización en formato AAAA-MM-DD. Si no se proporciona, el valor predeterminado es de diez años a partir de la fecha de inicio.
    • contactEmails: primero cree una variable que contenga los correos electrónicos y, luego, pase esa variable. Reemplace los correos electrónicos con las direcciones de correo electrónico para enviar la notificación de presupuesto cuando se supere el umbral.

    Nota

    Una vez finalizada la implementación, debería mostrarse un mensaje indicando que la implementación se realizó correctamente.

Un filtro

Revisión del archivo de Bicep

El archivo de Bicep usado en este inicio rápido forma parte de las plantillas de inicio rápido de Azure.

targetScope = 'subscription'

@description('Name of the Budget. It should be unique within a resource group.')
param budgetName string = 'MyBudget'

@description('The total amount of cost or usage to track with the budget')
param amount int = 1000

@description('The time covered by a budget. Tracking of the amount will be reset based on the time grain.')
@allowed([
  'Monthly'
  'Quarterly'
  'Annually'
])
param timeGrain string = 'Monthly'

@description('The start date must be first of the month in YYYY-MM-DD format. Future start date should not be more than three months. Past start date should be selected within the timegrain preiod.')
param startDate string

@description('The end date for the budget in YYYY-MM-DD format. If not provided, we default this to 10 years from the start date.')
param endDate string

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param firstThreshold int = 90

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param secondThreshold int = 110

@description('The list of email addresses to send the budget notification to when the threshold is exceeded.')
param contactEmails array

@description('The set of values for the resource group filter.')
param resourceGroupFilterValues array

resource budget 'Microsoft.Consumption/budgets@2021-10-01' = {
  name: budgetName
  properties: {
    timePeriod: {
      startDate: startDate
      endDate: endDate
    }
    timeGrain: timeGrain
    amount: amount
    category: 'Cost'
    notifications: {
      NotificationForExceededBudget1: {
        enabled: true
        operator: 'GreaterThan'
        threshold: firstThreshold
        contactEmails: contactEmails
      }
      NotificationForExceededBudget2: {
        enabled: true
        operator: 'GreaterThan'
        threshold: secondThreshold
        contactEmails: contactEmails
      }
    }
    filter: {
      dimensions: {
        name: 'ResourceGroupName'
        operator: 'In'
        values: resourceGroupFilterValues
      }
    }
  }
}

En el archivo Bicep se define un recurso de Azure:

Implementación del archivo de Bicep

  1. Guarde el archivo de Bicep como main.bicep en el equipo local.

  2. Implemente el archivo de Bicep mediante la CLI de Azure o Azure PowerShell.

    myContactEmails ='("user1@contoso.com", "user2@contoso.com")'
    myRgFilterValues ='("resource-group-01", "resource-group-02")'
    
    az deployment sub create --name demoSubDeployment --location centralus --template-file main.bicep --parameters startDate=<start-date> endDate=<end-date> contactEmails=$myContactEmails resourceGroupFilterValues=$myRgFilterValues
    

    Debe introducir los parámetros siguientes:

    • startDate: reemplace <start-date> por la fecha de inicio. Debe ser el primero del mes en formato AAAA-MM-DD. La fecha de inicio futura no puede ser superior a tres meses en el futuro. Se debe seleccionar una fecha de inicio anterior dentro del período del valor de timegrain.
    • endDate: reemplace <end-date> por la fecha de finalización en formato AAAA-MM-DD. Si no se proporciona, el valor predeterminado es de diez años a partir de la fecha de inicio.
    • contactEmails: primero cree una variable que contenga los correos electrónicos y, luego, pase esa variable. Reemplace los correos electrónicos con las direcciones de correo electrónico para enviar la notificación de presupuesto cuando se supere el umbral.
    • resourceGroupFilterValues En primer lugar, cree una variable que contenga los valores del filtro del grupo de recursos y, luego, pase esa variable. Reemplace los valores del filtro de ejemplo por el conjunto de valores para el filtro del grupo de recursos.

    Nota

    Una vez finalizada la implementación, debería mostrarse un mensaje indicando que la implementación se realizó correctamente.

Dos o más filtros

Revisión del archivo de Bicep

El archivo de Bicep usado en este inicio rápido forma parte de las plantillas de inicio rápido de Azure.

targetScope = 'subscription'

@description('Name of the Budget. It should be unique within a resource group.')
param budgetName string = 'MyBudget'

@description('The total amount of cost or usage to track with the budget')
param amount int = 1000

@description('The time covered by a budget. Tracking of the amount will be reset based on the time grain.')
@allowed([
  'Monthly'
  'Quarterly'
  'Annually'
])
param timeGrain string = 'Monthly'

@description('The start date must be first of the month in YYYY-MM-DD format. Future start date should not be more than three months. Past start date should be selected within the timegrain preiod.')
param startDate string

@description('The end date for the budget in YYYY-MM-DD format. If not provided, we default this to 10 years from the start date.')
param endDate string

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param firstThreshold int = 90

@description('Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0.01 and 1000.')
param secondThreshold int = 110

@description('The list of contact roles to send the budget notification to when the threshold is exceeded.')
param contactRoles array = [
  'Owner'
  'Contributor'
  'Reader'
]

@description('The list of email addresses to send the budget notification to when the threshold is exceeded.')
param contactEmails array

@description('The list of action groups to send the budget notification to when the threshold is exceeded. It accepts array of strings.')
param contactGroups array

@description('The set of values for the resource group filter.')
param resourceGroupFilterValues array

@description('The set of values for the meter category filter.')
param meterCategoryFilterValues array

resource budget 'Microsoft.Consumption/budgets@2021-10-01' = {
  name: budgetName
  properties: {
    timePeriod: {
      startDate: startDate
      endDate: endDate
    }
    timeGrain: timeGrain
    amount: amount
    category: 'Cost'
    notifications: {
      NotificationForExceededBudget1: {
        enabled: true
        operator: 'GreaterThan'
        threshold: firstThreshold
        contactEmails: contactEmails
        contactRoles: contactRoles
        contactGroups: contactGroups
      }
      NotificationForExceededBudget2: {
        enabled: true
        operator: 'GreaterThan'
        threshold: secondThreshold
        contactEmails: contactEmails
        contactRoles: contactRoles
        contactGroups: contactGroups
        thresholdType: 'Forecasted'
      }
    }
    filter: {
      and: [
        {
          dimensions: {
            name: 'ResourceGroupName'
            operator: 'In'
            values: resourceGroupFilterValues
          }
        }
        {
          dimensions: {
            name: 'MeterCategory'
            operator: 'In'
            values: meterCategoryFilterValues
          }
        }
      ]
    }
  }
}

En el archivo Bicep se define un recurso de Azure:

Implementación del archivo de Bicep

  1. Guarde el archivo de Bicep como main.bicep en el equipo local.

  2. Implemente el archivo de Bicep mediante la CLI de Azure o Azure PowerShell.

    myContactEmails ='("user1@contoso.com", "user2@contoso.com")'
    myContactGroups ='("/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/microsoft.insights/actionGroups/groupone", "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/microsoft.insights/actionGroups/grouptwo")'
    myRgFilterValues ='("resource-group-01", "resource-group-02")'
    myMeterCategoryFilterValues ='("meter-category-01", "meter-category-02")'
    
    az deployment sub create --name demoSubDeployment --location centralus --template-file main.bicep --parameters startDate=<start-date> endDate=<end-date> contactEmails=$myContactEmails contactGroups=$myContactGroups resourceGroupFilterValues=$myRgFilterValues meterCategoryFilterValues=$myMeterCategoryFilterValues
    

    Debe introducir los parámetros siguientes:

    • startDate: reemplace <start-date> por la fecha de inicio. Debe ser el primero del mes en formato AAAA-MM-DD. La fecha de inicio futura no puede ser superior a tres meses en el futuro. Se debe seleccionar una fecha de inicio anterior dentro del período del valor de timegrain.
    • endDate: reemplace <end-date> por la fecha de finalización en formato AAAA-MM-DD. Si no se proporciona, el valor predeterminado es de diez años a partir de la fecha de inicio.
    • contactEmails: primero cree una variable que contenga los correos electrónicos y, luego, pase esa variable. Reemplace los correos electrónicos con las direcciones de correo electrónico para enviar la notificación de presupuesto cuando se supere el umbral.
    • contactGroups: cree primero una variable que contenga los grupos de contactos y, luego, pase esa variable. Reemplace los grupos de contactos de ejemplo por la lista de grupo de acciones para enviar la notificación del presupuesto cuando se supere el umbral. Debe pasar el identificador de recurso del grupo de acciones, que puede obtener con az monitor action-group show o Get-AzActionGroup.
    • resourceGroupFilterValues: en primer lugar, cree una variable que contenga los valores del filtro del grupo de recursos y, luego, pase esa variable. Reemplace los valores del filtro de ejemplo por el conjunto de valores para el filtro del grupo de recursos.
    • meterCategoryFilterValues: en primer lugar, cree una variable que contenga los valores del filtro de la categoría del medidor y, luego, pase esa variable. Reemplace los valores del filtro de ejemplo entre paréntesis por el conjunto de valores del filtro de la categoría del medidor.

    Nota

    Una vez finalizada la implementación, debería mostrarse un mensaje indicando que la implementación se realizó correctamente.

Revisión de los recursos implementados

Use los Azure Portal, CLI de Azure o Azure PowerShell para enumerar los recursos implementados en el grupo de recursos.

az consumption budget list

Limpieza de recursos

Cuando ya no necesite el presupuesto, use Azure Portal, la CLI de Azure o Azure PowerShell para eliminarlo:

az consumption budget delete --budget-name MyBudget

Pasos siguientes

En este inicio rápido, ha creado un presupuesto y lo ha implementado mediante Bicep. Para más información sobre Cost Management and Billing y Bicep, continúe con los artículos siguientes.