次の方法で共有


APIを使用してGit統合を自動化する

Microsoft Fabric のGit 統合 ツールを使うと、チームが共同作業をするためにソース管理を使用して、Fabric コンテンツのための効率的で再利用可能なリリース プロセスを構築できます。

Microsoft Fabric REST API を使用すると、Fabric の手順とプロセスを自動化して、タスクをより迅速かつ、より少ないエラーで完了できます。 この効率は、コスト削減と生産性の向上につながります。

この記事では、Git integration REST API を使用して Microsoft Fabric での Git 統合を自動化する方法について説明します。

Prerequisites

Fabric Git API を使用するには、以下が必要です:

PowerShell なしで REST API を使用できますが、この記事のスクリプトでは PowerShell を使用します。 スクリプトを実行するには、次の手順を実行します。

Git 統合 API 関数

Git integration REST API は、コンテンツの継続的インテグレーションと継続的デリバリー (CI/CD) を実現するのに役立ちます。 API を使用して実行できることの例をいくつか次に示します。

Examples

以下の PowerShell Scriptを使って、いくつかの共通の自動化プロセスを実行する方法を理解します。 PowerShell サンプルのテキストを表示またはコピーするには、このセクションのリンクを使用します。 Fabric Git 統合サンプル GitHub リポジトリですべての例を確認することもできます。

接続して更新する

このセクションでは、Git でワークスペースに接続して更新するときの手順について説明します。

完全なスクリプトについては、Git からの接続と更新に関するページをご覧ください。 (スクリプトの互換性は PowerShell 5.1 です)

  1. Azure アカウントに接続してアクセス トークンを取得 する - ユーザーまたはサービス プリンシパルとして Fabric にサインインします。 Connect-AzAccount コマンドを使用して接続します。 アクセス トークンを取得するには、Get-AzAccessToken コマンドを使用し、セキュリティで保護された文字列トークンをプレーン テキストに変換します

    コードは次のようになります。

     $global:resourceUrl = "https://api.fabric.microsoft.com"
    
     $global:fabricHeaders = @{}
    
     function SetFabricHeaders() {
    
        #Login to Azure
        Connect-AzAccount | Out-Null
    
        # Get authentication
        $secureFabricToken = (Get-AzAccessToken -AsSecureString -ResourceUrl $global:resourceUrl).Token
    
        # Convert secure string to plain test
        $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureFabricToken)
        try {
            $fabricToken = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
        } finally {
            [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
       }
    
      $global:fabricHeaders = @{
         'Content-Type' = "application/json"
         'Authorization' = "Bearer {0}" -f $fabricToken
     }
    }
    
  2. 接続 API を呼び出して、ワークスペースを Git リポジトリとブランチに接続します。 (最初に 接続を作成 する必要がある場合があります)

    接続の詳細 (ID、名前) を取得する方法については、「 Git プロバイダーの資格情報の接続を取得または作成する」を参照してください。

    $global:baseUrl = "https://api.fabric.microsoft.com/v1"
    $workspaceName = "<WORKSPACE NAME>"
    $getWorkspacesUrl = "{0}/workspaces" -f $global:baseUrl
    $workspaces = (Invoke-RestMethod -Headers $global:fabricHeaders -Uri $getWorkspacesUrl -Method GET).value
    
    # Find the workspace by display name
    $workspace = $workspaces | Where-Object {$_.DisplayName -eq $workspaceName}
    
    # Connect to Git
    Write-Host "Connecting the workspace '$workspaceName' to Git."
    $connectUrl = "{0}/workspaces/{1}/git/connect" -f $global:baseUrl, $workspace.Id
    
    # AzureDevOps details
    $azureDevOpsDetails = @{
        gitProviderType = "AzureDevOps"
        organizationName = "<ORGANIZATION NAME>"
        projectName = "<PROJECT NAME>"
        repositoryName = "<REPOSITORY NAME>"
        branchName = "<BRANCH NAME>"
        directoryName = "<DIRECTORY NAME>"
    }
    
    $connectToGitBody = @{}
    #Leave only one of the following two (delete the other one):
    #-----------------------------------------------------------------------------------------------
    # 1. Automatic (SSO)
    $connectToGitBody = @{
        gitProviderDetails = $gitProviderDetails
    } | ConvertTo-Json
    #-----------------------------------------------------------------------------------------------
    # 2. ConfiguredConnection (User or service principal)
    # Get workspaces
    $connectionName = "<CONNECTION Name>"
    $getConnectionsUrl = "{0}/connections" -f $global:baseUrl
    $connections = (Invoke-RestMethod -Headers $global:fabricHeaders -Uri $getConnectionsUrl -Method GET).value
    
    # Find the connection by display name
    $connection = $connections | Where-Object {$_.DisplayName -eq $connectionName}
    $connectToGitBody = @{
        gitProviderDetails = $azureDevOpsDetails
        myGitCredentials = @{
            source = "ConfiguredConnection"
            connectionId = $connection.id
            }
        } | ConvertTo-Json
    #-----------------------------------------------------------------------------------------------
    
    Invoke-RestMethod -Headers $global:fabricHeaders -Uri $connectUrl -Method POST -Body $connectToGitBody
    
  3. Initialize Connection APIを呼び出して、ワークスペースとGitリポジトリ/ブランチの間の接続を初期化します。

    # Initialize Connection
    
    Write-Host "Initializing Git connection for workspace '$workspaceName'."
    
    $initializeConnectionUrl = "{0}/workspaces/{1}/git/initializeConnection" -f $global:baseUrl, $workspace.Id
    $initializeConnectionResponse = Invoke-RestMethod -Headers $global:fabricHeaders -Uri $initializeConnectionUrl -Method POST -Body "{}"
    
  4. Initialize Connection API からの応答に基づいて、Update From Git API を呼び出して更新を完了するか、アクションが必要ない場合は何も行いません。

    次のスクリプトは、更新を行って進行状況を監視します。

    if ($initializeConnectionResponse.RequiredAction -eq "UpdateFromGit") {
    
        # Update from Git
        Write-Host "Updating the workspace '$workspaceName' from Git."
    
        $updateFromGitUrl = "{0}/workspaces/{1}/git/updateFromGit" -f $global:baseUrl, $workspace.Id
    
        $updateFromGitBody = @{ 
            remoteCommitHash = $initializeConnectionResponse.RemoteCommitHash
      workspaceHead = $initializeConnectionResponse.WorkspaceHead
        } | ConvertTo-Json
    
        $updateFromGitResponse = Invoke-WebRequest -Headers $global:fabricHeaders -Uri $updateFromGitUrl -Method POST -Body $updateFromGitBody
    
        $operationId = $updateFromGitResponse.Headers['x-ms-operation-id']
        $retryAfter = $updateFromGitResponse.Headers['Retry-After']
        Write-Host "Long Running Operation ID: '$operationId' has been scheduled for updating the workspace '$workspaceName' from Git with a retry-after time of '$retryAfter' seconds." -ForegroundColor Green
    
        # Poll Long Running Operation
        $getOperationState = "{0}/operations/{1}" -f $global:baseUrl, $operationId
        do
        {
            $operationState = Invoke-RestMethod -Headers $global:fabricHeaders -Uri $getOperationState -Method GET
    
            Write-Host "Update from Git operation status: $($operationState.Status)"
    
            if ($operationState.Status -in @("NotStarted", "Running")) {
                Start-Sleep -Seconds $retryAfter
            }
        } while($operationState.Status -in @("NotStarted", "Running"))
    }
    

Git から更新する

このセクションでは、Git からの変更を使用してワークスペースを更新する手順について説明します。 このScriptでは、Git からの変更でワークスペース項目を更新しますが、Git リポジトリは変更されません。

完全なスクリプトについては、「Git からワークスペースを更新する」を参照してください。

  1. Git にログインして認証を取得します。
  2. Get Status API を呼び出して、Git 要求本文から更新をビルドします。
  3. Update From Git API を呼び出して、接続されたブランチにプッシュされたコミットでワークスペースを更新します。

すべてコミットする

このセクションでは、ワークスペースから Git にすべての変更をプログラムでコミットする方法について詳しく説明します。

完全なスクリプトについては、「すべての変更を Git にコミットする」を参照してください。

  1. Git にログインして認証を取得します。
  2. ワークスペースへ接続します。
  3. Commit to Git REST API を呼び出します。
  4. 操作の状態をポーリングするための、実行時間の長い OperationId を取得します。

選択的コミット

このセクションでは、ワークスペースから Git に特定の変更のみをコミットする手順について説明します。

完全なスクリプトは、「Git への変更のコミット選択」を参照してください。

  1. Git にログインして認証を取得します。
  2. ワークスペースへ接続します。
  3. Get status API を呼び出して、変更された項目ワークスペースを確認します。
  4. コミットする特定の項目を選択します。
  5. Commit to Git API を呼び出して、選択した変更をワークスペースから接続されたリモート ブランチにコミットします。

長期間実行する操作の進行状況を監視する

完全なスクリプトについては、「実行時間の長い操作のポーリング」を参照してください。

  1. Update From Git または Commit to Git スクリプトから operationId を取得します。
  2. 指定された間隔 (秒単位) で Get LRO Status API を呼び出して、状態を出力します。

Git プロバイダーの資格情報接続を取得または作成する

Git リポジトリに 接続 したり、Git 資格情報を更新 したりするには、 connectionId を指定する必要があります。 connectionId は、作成した新しい接続または既存の接続から取得できます。

Git 資格情報を格納する新しい接続を作成する

次のコード スニペットは、Azure DevOps 資格情報を格納する接続を作成するためのサンプル要求本文を示しています。 完全な例は、 Fabric サンプル リポジトリにあります。

# Connection with ServicePrincipal details for AzureDevOpsSourceControl
$adoSPConnection = @{
    connectivityType = "ShareableCloud"
    displayName = "<CONNECTION NAME>"
    connectionDetails = @{
        type = "AzureDevOpsSourceControl"
        creationMethod = "AzureDevOpsSourceControl.Contents"
        parameters = @(
            @{
                dataType = "Text"
                name = "url"
                value = "<Repo url in Azure DevOps>"
            }
        )
    }
    credentialDetails = @{
        credentials = @{
            credentialType = "ServicePrincipal"
            tenantId = "<SP tenant (directory) id (Guid)>"
            servicePrincipalClientId = "<SP APP (client) id (Guid)>"
            servicePrincipalSecret = "<SP Secret>"
        }
    }
}

#Note: AzureDevOps for UserPrincipal is not supported (since it requires interactive OAuth2)

要求のサンプル

POST https://api.fabric.microsoft.com/v1/connections

{
  "displayName": "<CONNECTION NAME>",
  "connectivityType": "ShareableCloud",
  "connectionDetails": {
    "creationMethod": "AzureDevOpsSourceControl.Contents",
    "type": "AzureDevOpsSourceControl",
    "parameters": [
     {
      "dataType": "Text",
      "name": "url",
      "value": "<Repo url in Azure DevOps>”
     }
    ]
  },
  "credentialDetails": {
    "credentials": {
      "credentialType": "ServicePrincipal",
      "tenantId": “<SP tenant (directory) id (Guid)>”,
      "servicePrincipalClientId": “<SP APP (client) id (Guid)>”,
      "servicePrincipalSecret": “<SP Secret>”
    }
  }
}
 

サンプルの応答:

{
  "allowConnectionUsageInGateway": false,
  "id": "********-****-****-****-c13b543982ac",
  "displayName": "<CONNECTION NAME>",
  "connectivityType": "ShareableCloud",
  "connectionDetails": {
    "path": "<Repo url in Azure DevOps>",
    "type": "AzureDevOpsSourceControl"
  },
  "privacyLevel": "Organizational",
  "credentialDetails": {
    "credentialType": "ServicePrincipal",
    "singleSignOnType": "None",
    "connectionEncryption": "NotEncrypted",
    "skipTestConnection": false
  }
}

既存の接続の一覧を取得する

List connections API を使用して、アクセス許可を持つ既存の接続とそのプロパティの一覧を取得します。

サンプルリクエスト

GET https://api.fabric.microsoft.com/v1/connections

サンプル応答

{
 "value": [
  {
   "id": "e3607d15-6b41-4d11-b8f4-57cdcb19ffc8",
   "displayName": "MyGitHubPAT1",
   "gatewayId": null,
   "connectivityType": "ShareableCloud",
   "connectionDetails": {
    "path": "https://github.com",
    "type": "GitHubSourceControl"
   },
   "privacyLevel": "Organizational",
   "credentialDetails": {
    "credentialType": "Key",
    "singleSignOnType": "None",
    "connectionEncryption": "NotEncrypted",
    "skipTestConnection": false
   }
  },
  {
   "id": "3aba8f7f-d1ba-42b1-bb41-980029d5a1c1",
   "displayName": "MyGitHubPAT2",
   "gatewayId": null,
   "connectivityType": "ShareableCloud",
   "connectionDetails": {
    "path": "https://github.com/OrganizationName/RepositoryName",
    "type": "GitHubSourceControl"
   },
   "privacyLevel": "Organizational",
   "credentialDetails": {
    "credentialType": "Key",
    "singleSignOnType": "None",
    "connectionEncryption": "NotEncrypted",
    "skipTestConnection": false
   }
  }
 ]
}

目的の接続の ID をコピーし、 Git - Connect または Git - Update My Git Credentials API で使用します。

考慮事項と制限事項

  • API を使用した Git 統合には、Git 統合ユーザー インターフェイスと同じ制限があります。
  • 拡張更新 API を使ってセマンティック モデルを更新すると、更新のたびに Git diff が行われます。