共用方式為


使用 API 自動化 Git 整合

Microsoft Fabric Git 整合工具可讓團隊使用原始檔控制共同合作,為其 Fabric 內容建置有效率並可再使用的釋出程序。

有了 Microsoft Fabric REST API,您可以將 Fabric 程序和程序自動化,以更快完成工作,同時減少錯誤。 此效率可節省成本並提升生產力。

本文說明如何使用 Git 整合 REST API,將 Microsoft Fabric 中的 Git 整合自動化。

Prerequisites

若要使用 Fabric Git API,您需要:

您可以使用不含 PowerShell 的 REST API,但本文中的腳本會使用 PowerShell。 若要執行文稿,請執行下列步驟:

Git 整合工具 API 功能

Git 整合 REST API 有助於您達成內容的持續整合與持續傳遞 (CI/CD)。 以下是一些使用 API 可以完成的範例:

Examples

使用下列 PowerShell 指令碼來了解如何執行數個常見的自動化程序。 若要檢視或複製 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. 呼叫 Connect 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. 根據初始化連線 API 的回應,呼叫 從 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 的變更來更新工作區所涉及的步驟。 在此指令碼中,我們會使用 Git 的變更來更新工作區項目,但我們會保持 Git 存放庫不變。

如需完整的指令碼,請參閱<更新 Git 的工作區>。

  1. 登入 Git 並取得驗證。
  2. 呼叫 Get Status API,以建置來自 Git 請求正文的更新。
  3. 調用Update From Git API 以更新工作區,使用推送至連接分支的提交。

全部提交

本節提供詳細的逐步說明,介紹如何透過程式碼將工作區的所有變更提交至 Git。

如需完整的指令碼,請參閱<提交所有變更至 Git>。

  1. 登入 Git 並取得驗證。
  2. 連線到工作區。
  3. 調用提交到 Git REST API。
  4. 取得長時間執行的 OperationId,以輪詢作業的狀態。

選擇性認可

本節說明將工作區中的特定變更提交至 Git 的步驟。

如需完整的指令碼,請參閱<將選取的變更認可至 Git>。

  1. 登入 Git 並取得驗證。
  2. 連線到工作區。
  3. 呼叫 Get status API 以查看哪些項目工作區已變更。
  4. 選擇要提交的特定項目。
  5. 呼叫 Commit to Git API,將選取的變更從工作區認可到已連接的遠端的分支。

監視長時間執行作業的進度

如需完整的指令碼,請參閱<輪詢長時間執行的作業>。

  1. Update From GitCommit to Git 腳本擷取 operationId。
  2. 以指定的間隔呼叫取得 LRO 狀態 API(以秒為單位),並列印狀態。

取得或建立 Git 提供者認證連線

若要 連線 到 Git 存放庫或 更新您的 Git 認證 ,您需要提供 connectionIdconnectionId 可以來自您所建立的新連線或現有的連線。

建立儲存 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
  }
}

取得現有連線的清單

使用 清單連線 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
   }
  }
 ]
}

複製您想要的連線標識碼,並在 Git - ConnectGit - 更新我的 Git 認證 API 中使用。

考量與限制

  • 使用 API 的 Git 整合與 Git 整合使用者介面同樣受限於相同的限制
  • 若使用增強式重新整理 API 重新整理語意模型,系統會在每次重新整理之後產生 Git 差異