Private RepositoryのARM テンプレートをAzure PipelinesでDeployする方法

## 背景
Privateで管理されているRepositoryを、microsoftの [チュートリアル:Azure Pipelines を使用した ARM テンプレートの継続的インテグレーション](https://learn.microsoft.com/ja-jp/azure/azure-resource-manager/templates/deployment-tutorial-pipeline) 通り実施したら、失敗したので解決方法を記載します。

## 発生した問題
csmFileLinkで指定したARMテンプレートが、404 Not Found 見つからない....

```bash
##[error]Check out the troubleshooting guide to see if your issue is addressed: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-resource-group-deployment?view=azure-devops#troubleshooting
##[error]Failed to download the file. URL: 'https://raw.githubusercontent.com/NorihitoYamazaki1/azure-sample-templates/main/keyvault/create/azuredeploy.json'. Error: 404: Not Found
```

## 原因
GitHub様の仕様です。

## 解決方法
tyang さんのTechBlogにあるGitHubPrivateRepoFileFecherを利用します！！！

では解決方法を見ていきましょう！！
#### GitHub Personal Access Token(PAT)の生成

生成方法は[公式ドキュメント](https://docs.github.com/ja/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token#personal-access-token-classic-%E3%81%AE%E4%BD%9C%E6%88%90)を見てください。

*Select scopes*で必ず"repo"にチェックを入れてください。
![new-personal-access-token.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3154443/2e613f92-2fb4-467c-2e0b-1bb3fed7f8ba.png)

#### GitHubPrivateRepoFileFecherをAzureFunctionにDeploy
どちらかのGitHubPrivateRepoFileFecherをAzureFuntionにDeployしてください。
どっちらもAPI仕様は同じです。
- tyang さんの[GitHubPrivateRepoFileFecher](https://gist.github.com/tyconsulting/f8de503de3df164a6163a3299656d516)
- 私の[GitHubPrivateRepoFileFecher](https://github.com/NorihitoYamazaki1/GitHubPrivateRepoFileFecher)

必ず動作確認してください。
- GitHubPrivateRepoFileFecherからazuredeploy.jsonの内容が返ってくること

```url
https://<Function App Name>.azurewebsites.net/api/GitHubPrivateRepoFileFecher?githuburi=https://raw.githubusercontent.com/<GitHub User Name>/<Repository>/<branch>/<path to the file>&githubaccesstoken=<GitHub Person Access Token>
```


#### Piplineの修正
```yaml
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:
- task: AzureResourceManagerTemplateDeployment@3
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: 'learning-service-connection'
    subscriptionId: '{自身のsubscriptionId}'
    action: 'Create Or Update Resource Group'
    resourceGroupName: '{自身のresourceGroupName}'
    location: 'East US'
    templateLocation: 'URL of the file'
    csmFileLink: 'https://{自身のAzureFunctionSubDomain}.azurewebsites.net/api/GitHubPrivateRepoFileFetcher?githuburi={自身のazuredeploy.json}&githubaccesstoken={自身のPAT}'
    deploymentMode: 'Incremental'
    deploymentName: 'Deploy-ARMsample'
```

以上となります。

参考までに私のPiplineとARM Templateをのせておきます

##### MYPiline&ARM Template
中括弧{}の部分は隠しています。

*Piline*
```yaml
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:
- task: AzureResourceManagerTemplateDeployment@3
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: 'learning-service-connection'
    subscriptionId: '{自身のsubscriptionId}'
    action: 'Create Or Update Resource Group'
    resourceGroupName: '{自身のresourceGroupName}'
    location: 'East US'
    templateLocation: 'URL of the file'
    csmFileLink: 'https://{自身のAzureFunctionSubDomain}.azurewebsites.net/api/GitHubPrivateRepoFileFetcher?githuburi=https://raw.githubusercontent.com/NorihitoYamazaki1/azure-sample-templates/main/keyvault/create/azuredeploy.json&githubaccesstoken={自身のPAT}'
    deploymentMode: 'Incremental'
    deploymentName: 'Deploy-ARMsample'
```

*ARM*
```json
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "functions": [],
  "variables": {
    "keyVaultName": "[concat('kv-', 'sample-1234')]"
  },
  "resources": [
    {
      "type": "Microsoft.KeyVault/vaults",
      "apiVersion": "2022-11-01",
      "name": "[variables('keyVaultName')]",
      "location": "[resourceGroup().location]",
      "properties": {
        "sku": {
          "family": "A",
          "name": "Standard"
        },
        "tenantId": "[subscription().tenantId]",
        "accessPolicies": [],
        "enabledForDeployment": true,
        "enabledForDiskEncryption": true,
        "enabledForTemplateDeployment": true,
        "enableSoftDelete": true,
        "softDeleteRetentionInDays": 10,
        "enableRbacAuthorization": false,
        "vaultUri": "[concat('https://', variables('keyVaultName'), '.vault.azure.net/')]",
        "provisioningState": "Succeeded",
        "publicNetworkAccess": "Enabled"
      }
    },
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "apiVersion": "2022-11-01",
      "name": "[format('{0}/{1}', variables('keyVaultName'), 'my-config-data-secret')]",
      "tags": {
        "tagName1": "tagValue1",
        "tagName2": "tagValue2"
      },
      "properties": {
        "attributes": {
          "enabled": true
        },
        "contentType": "application/json",
        "value": "{name:'secrets values'}"
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    }
  ],
  "outputs": {}
}
```

※keyVaultNameは、Globalで[一意](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name)で設定する必要があるよ


#### 参考リンク
- [Failure to retrieve file from connected github repository when running AzureResourceManagerTemplateDeployment@3 - 404 Not Found](https://github.com/microsoft/azure-pipelines-tasks/issues/15827)
- [チュートリアル:Azure Pipelines を使用した ARM テンプレートの継続的インテグレーション](https://learn.microsoft.com/ja-jp/azure/azure-resource-manager/templates/deployment-tutorial-pipeline)
- [Deploying ARM Templates with Artifacts Located in a Private GitHub Repository](https://blog.tyang.org/2017/05/19/deploying-arm-templates-with-artifacts-located-in-a-private-github-repository/)
- https://github.com/NorihitoYamazaki1/GitHubPrivateRepoFileFecher/tree/main
- [Azure Key Vault keys, secrets and certificates overview](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name)