Bicep の Date 関数

この記事では、日付を操作するための Bicep 関数について説明します。

dateTimeAdd

dateTimeAdd(base, duration, [format])

ベースの値に期間を加算します。 ISO 8601 形式である必要があります。

名前空間: sys

パラメーター

パラメーター 必須 タイプ 説明
base はい string 加算する期間の開始日時の値。 ISO 8601 タイムスタンプの形式を使用します。
duration はい string ベースに加算する時間の値。 負の値を指定することができます。 ISO 8601 期間の形式を使用します。
format いいえ string 日時の結果の出力形式。 指定しない場合、ベース値の形式が使用されます。 標準書式指定文字列またはカスタム書式指定文字列を使用します。

戻り値

ベースに期間の値を加算した結果の datetime 値。

解説

dateTimeAdd 関数は閏年を考慮しないため、P1YP365D と解釈する必要があります。一方、P1MP30D と解釈する必要があります。 いくつかの例を次の Bicep ファイルに示します。

output addOneYearNonLeap string = dateTimeAdd('2023-01-01 00:00:00Z', 'P1Y') //2024-01-01T00:00:00Z
output addOneYearLeap string = dateTimeAdd('2024-01-01 00:00:00Z', 'P1Y')  //2024-12-31T00:00:00Z

output addOneMonthNonLeap string = dateTimeAdd('2023-02-01 00:00:00Z', 'P1M') //2023-03-03T00:00:00Z
output addOneMonthLeap string = dateTimeAdd('2024-02-01 00:00:00Z', 'P1M') //2023-03-02T00:00:00Z

前の例では、2023 を非閏年と考えると、年の最初の日に 1 年を追加した結果は、2024-01-01T00:00:00Z です。 逆に、閏年である 2024 年の開始日に 1 年を加算すると、2025-01-01T00:00:00Z ではなく 2024-12-31T00:00:00Z になります。閏年が 365 日ではなく 366 日で構成されるためです。 さらに、2 月の最初の日に 1 か月を追加すると、閏年と非閏年の区別が明らかになり、何日になるかがさまざまに変動する結果になります。

次の例は、時間の値を加算するさまざまな方法を示します。

param baseTime string = utcNow('u')

var add3Years = dateTimeAdd(baseTime, 'P3Y')
var subtract9Days = dateTimeAdd(baseTime, '-P9D')
var add1Hour = dateTimeAdd(baseTime, 'PT1H')

output add3YearsOutput string = add3Years
output subtract9DaysOutput string = subtract9Days
output add1HourOutput string = add1Hour

以前の例がベースの日時 2020-04-07 14:53:14Zでデプロイされている場合、出力は次のようになります。

Name Type
add3YearsOutput String 4/7/2023 2:53:14 PM
subtract9DaysOutput String 3/29/2020 2:53:14 PM
add1HourOutput String 4/7/2020 3:53:14 PM

次の例は、Automation スケジュールの開始日時を設定する方法を示します。

param omsAutomationAccountName string = 'demoAutomation'
param scheduleName string = 'demSchedule1'
param baseTime string = utcNow('u')

var startTime = dateTimeAdd(baseTime, 'PT1H')

...

resource scheduler 'Microsoft.Automation/automationAccounts/schedules@2022-08-08' = {
  name: concat(omsAutomationAccountName, '/', scheduleName)
  properties: {
    description: 'Demo Scheduler'
    startTime: startTime
    interval: 1
    frequency: 'Hour'
  }
}

dateTimeFromEpoch

dateTimeFromEpoch(epochTime)

エポック時間整数値を ISO 8601 datetime に変換します。

名前空間: sys

パラメーター

パラメーター 必須 タイプ 説明
epochTime はい INT datetime 文字列に変換するエポック時間。

戻り値

ISO 8601 datetime 文字列。

解説

この関数は、Bicep CLI バージョン 0.5.X 以降が必要です。

次の例は、エポック時間関数の出力値を示しています。

param convertedEpoch int = dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))

var convertedDatetime = dateTimeFromEpoch(convertedEpoch)

output epochValue int = convertedEpoch
output datetimeValue string = convertedDatetime

出力は次のようになります。

名前 Type
datetimeValue String 2023-05-02T15:16:13Z
epochValue int 1683040573

dateTimeToEpoch

dateTimeToEpoch(dateTime)

ISO 8601 datetime 文字列をエポック時間整数値に変換します。

名前空間: sys

パラメーター

パラメーター 必須 タイプ 説明
dateTime はい string エポック時間に変換する datetime 文字列。

戻り値

1970 年 1 月 1 日の午前 0 時からの秒数を表す整数。

解説

この関数は、Bicep CLI バージョン 0.5.X 以降が必要です。

次の例は、エポック時間関数の出力値を示しています。

param convertedEpoch int = dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))

var convertedDatetime = dateTimeFromEpoch(convertedEpoch)

output epochValue int = convertedEpoch
output datetimeValue string = convertedDatetime

出力は次のようになります。

名前 Type
datetimeValue String 2023-05-02T15:16:13Z
epochValue int 1683040573

次の例では、エポック時間値を使用して、キー コンテナー内のキーの有効期限を設定します。

@description('The location into which the resources should be deployed.')
param location string = resourceGroup().location

@description('The Tenant Id that should be used throughout the deployment.')
param tenantId string = subscription().tenantId

@description('The name of the existing User Assigned Identity.')
param userAssignedIdentityName string

@description('The name of the resource group for the User Assigned Identity.')
param userAssignedIdentityResourceGroupName string

@description('The name of the Key Vault.')
param keyVaultName string  = 'vault-${uniqueString(resourceGroup().id)}'

@description('Name of the key in the Key Vault')
param keyVaultKeyName string = 'cmkey'

@description('Expiration time of the key')
param keyExpiration int = dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))

@description('The name of the Storage Account')
param storageAccountName string =  'storage${uniqueString(resourceGroup().id)}'


resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' existing = {
  scope: resourceGroup(userAssignedIdentityResourceGroupName)
  name: userAssignedIdentityName  
}

resource keyVault 'Microsoft.KeyVault/vaults@2021-10-01' = {
  name: keyVaultName
  location: location
  properties: {
    sku: {
      name: 'standard'
      family: 'A'
    }
    enableSoftDelete: true
    enablePurgeProtection: true
    enabledForDiskEncryption: true
    tenantId: tenantId
    accessPolicies: [
      {
        tenantId: tenantId
        permissions: {
          keys: [
            'unwrapKey'
            'wrapKey'
            'get'
          ]
        }
        objectId: userAssignedIdentity.properties.principalId
      }
    ]
  }
}

resource kvKey 'Microsoft.KeyVault/vaults/keys@2021-10-01' = {
  parent: keyVault
  name: keyVaultKeyName
  properties: {
    attributes: {
      enabled: true
      exp: keyExpiration
    }
    keySize: 4096
    kty: 'RSA'
  }
}

resource storage 'Microsoft.Storage/storageAccounts@2021-04-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${userAssignedIdentity.id}': {}
    }
  }
  properties: {
    accessTier: 'Hot'
    supportsHttpsTrafficOnly: true
    minimumTlsVersion: 'TLS1_2'
    encryption: {
      identity: {
        userAssignedIdentity: userAssignedIdentity.id
      }
      services: {
         blob: {
           enabled: true
         }
      }
      keySource: 'Microsoft.Keyvault'
      keyvaultproperties: {
        keyname: kvKey.name
        keyvaulturi: endsWith(keyVault.properties.vaultUri,'/') ? substring(keyVault.properties.vaultUri,0,length(keyVault.properties.vaultUri)-1) : keyVault.properties.vaultUri
      }
    }
  }
}

utcNow

utcNow(format)

指定された形式で現在 (UTC) の datetime 値を返します。 形式を指定しないと、ISO 8601 (yyyyMMddTHHmmssZ) 形式が使われます。 この関数は、パラメーターの既定値でのみ使用できます。

名前空間: sys

パラメーター

パラメーター 必須 タイプ 説明
format いいえ string 文字列に変換する URI エンコードされた値。 標準書式指定文字列またはカスタム書式指定文字列を使用します。

解説

この関数は、パラメーターの既定値に対する式の中でのみ使用できます。 この関数を Bicep ファイルのその他の場所で使用すると、エラーが返されます。 Bicep ファイルの他の場所でこの関数を使用することは、呼び出しのたびに異なる値が返されるため、許可されていません。 同じパラメーターで同じ Bicep ファイルをデプロイしても、同じ結果が生成される保証はありません。

エラー発生時に以前の正常なデプロイにロールバックするオプションを使用し、以前のデプロイに utcNow を使用するパラメーターが含まれている場合、パラメーターは再評価されません。 代わりに、以前のデプロイのパラメーター値が、ロールバック デプロイで自動的に再利用されます。

既定値に対する utcNow 関数に依存する Bicep ファイルを再デプロイするときは注意が必要です。 再デプロイを行うときに、パラメーターの値を指定しないと、関数が再評価されます。 新しいリソースを作成するのではなく、既存のリソースを更新する場合は、以前のデプロイのパラメーター値を渡します。

戻り値

現在の UTC の datetime 値。

次の例では、datetime 値のさまざまな形式を示します。

param utcValue string = utcNow()
param utcShortValue string = utcNow('d')
param utcCustomValue string = utcNow('M d')

output utcOutput string = utcValue
output utcShortOutput string = utcShortValue
output utcCustomOutput string = utcCustomValue

前の例からの出力はデプロイごとに変わりますが、次のようになります。

名前 Type
utcOutput string 20190305T175318Z
utcShortOutput string 03/05/2019
utcCustomOutput string 3 5

次の例では、タグ値を設定するときに関数からの値を使用する方法を示します。

param utcShort string = utcNow('d')
param rgName string

resource myRg 'Microsoft.Resources/resourceGroups@2022-09-01' = {
  name: rgName
  location: 'westeurope'
  tags: {
    createdDate: utcShort
  }
}

output utcShortOutput string = utcShort

次のステップ