{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.46.1.21595",
      "templateHash": "11642959755289207486"
    },
    "VeloDBAzureBYOCTemplate": {
      "version": "2024-10-30",
      "description": "During deployment, two user identities will be created with relevant permissions.\n  A virtual machine will be deployed in your virtual network to install agent for management.\n  We'll also establish a private link to velodb virtual network for commands and metrics.\n  Rest assured, data always stays in your environment.\n  Find more for BYOC guidance: https://docs.velodb.io/cloud/management-guide/warehouse-management/create-byoc-warehouse/azure\n"
    }
  },
  "parameters": {
    "Token": {
      "type": "string",
      "metadata": {
        "source": "velodb",
        "description": "The token generated by VeloDB Cloud uniquely identifies the your virtual network. Please do not modify it."
      }
    },
    "VirtualNetworkResourceGroup": {
      "type": "string",
      "defaultValue": "[resourceGroup().name]",
      "metadata": {
        "source": "user",
        "description": "Please enter the resource group containing the virtual network. It may differ from the deployment resource group, but the virtual network must be in the same location as the deployment."
      }
    },
    "VirtualNetwork": {
      "type": "string",
      "metadata": {
        "source": "user",
        "description": "Please enter the virtual network name where the BYOC warehouse is deployed."
      }
    },
    "Subnet": {
      "type": "string",
      "metadata": {
        "source": "user",
        "description": "Please enter the subnet name where the BYOC warehouse is deployed."
      }
    },
    "SkipStack": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "source": "velodb",
        "description": "Skip the deployment stack if the vpc has been used."
      }
    },
    "InstanceType": {
      "type": "string",
      "metadata": {
        "source": "velodb",
        "description": "The instance type of agent."
      }
    }
  },
  "variables": {
    "RegionMap": {
      "westus3": {
        "DefaultZone": "westus3-az1",
        "EndpointService": "/subscriptions/c24ebfdf-23c3-4c41-950e-d4d2169aa546/resourceGroups/cmp-westus3/providers/Microsoft.Network/privateLinkServices/pls-84g8h6sf",
        "PublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCD8kjuxibmTFMOIiHFTx7RarrbMUcQN09uHAKLf/4JwtKg79m+w2/j8rv28PFxCnWaxwQX5QW44daZLXy9HiU4VuIBlN2Yxd9kMGt0PqkgtiVuF9nSu6+fmchjaMjgO3sA2YQTCGrIuTNedOvfD6CcxyOC4T5VMdZ1GFK36rd/O5WBgiyTrm77dNRsbY1MHzaMYgaRnqXCxFlHUdBHHDG74KFyclBah8KlihfxX9t9ipZcLf7Wk4BSZVIV3EhOmJfkOxlXF2SmgoOaaVH15Dmm/Dzzy3DcK2IzE1OWyPE3nm7Gpid3PDgl69t9z0zwakfqDRGC/ooXGoNzGOYWAqw7",
        "ImageEndpointUrl": "https://onlinevelodbwestus3.blob.core.windows.net/velodb-cloud-online-westus3",
        "SampleBucket": "velodb-import-data-westus3"
      },
      "centralindia": {
        "DefaultZone": "centralindia-az1",
        "EndpointService": "/subscriptions/c24ebfdf-23c3-4c41-950e-d4d2169aa546/resourceGroups/cmp-centralindia/providers/Microsoft.Network/privateLinkServices/pls-d0srx9cp",
        "PublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCD8kjuxibmTFMOIiHFTx7RarrbMUcQN09uHAKLf/4JwtKg79m+w2/j8rv28PFxCnWaxwQX5QW44daZLXy9HiU4VuIBlN2Yxd9kMGt0PqkgtiVuF9nSu6+fmchjaMjgO3sA2YQTCGrIuTNedOvfD6CcxyOC4T5VMdZ1GFK36rd/O5WBgiyTrm77dNRsbY1MHzaMYgaRnqXCxFlHUdBHHDG74KFyclBah8KlihfxX9t9ipZcLf7Wk4BSZVIV3EhOmJfkOxlXF2SmgoOaaVH15Dmm/Dzzy3DcK2IzE1OWyPE3nm7Gpid3PDgl69t9z0zwakfqDRGC/ooXGoNzGOYWAqw7",
        "ImageEndpointUrl": "https://velodbcentralindia.blob.core.windows.net/velodb-cloud-online-centralindia",
        "SampleBucket": "velodb-import-data-centralindia"
      },
      "eastus2": {
        "DefaultZone": "eastus2-az1",
        "EndpointService": "/subscriptions/c24ebfdf-23c3-4c41-950e-d4d2169aa546/resourceGroups/cmp-eastus2/providers/Microsoft.Network/privateLinkServices/pls-c3ema8n7",
        "PublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCD8kjuxibmTFMOIiHFTx7RarrbMUcQN09uHAKLf/4JwtKg79m+w2/j8rv28PFxCnWaxwQX5QW44daZLXy9HiU4VuIBlN2Yxd9kMGt0PqkgtiVuF9nSu6+fmchjaMjgO3sA2YQTCGrIuTNedOvfD6CcxyOC4T5VMdZ1GFK36rd/O5WBgiyTrm77dNRsbY1MHzaMYgaRnqXCxFlHUdBHHDG74KFyclBah8KlihfxX9t9ipZcLf7Wk4BSZVIV3EhOmJfkOxlXF2SmgoOaaVH15Dmm/Dzzy3DcK2IzE1OWyPE3nm7Gpid3PDgl69t9z0zwakfqDRGC/ooXGoNzGOYWAqw7",
        "InstanceType": "Standard_B2s",
        "ImageEndpointUrl": "https://velodbeastus2.blob.core.windows.net/velodb-cloud-online-eastus2",
        "SampleBucket": "velodb-import-data-eastus2"
      },
      "germanywestcentral": {
        "DefaultZone": "germanywestcentral-az1",
        "EndpointService": "/subscriptions/c24ebfdf-23c3-4c41-950e-d4d2169aa546/resourceGroups/cmp-germanywestcentral/providers/Microsoft.Network/privateLinkServices/pls-z0gwv6uf",
        "PublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCD8kjuxibmTFMOIiHFTx7RarrbMUcQN09uHAKLf/4JwtKg79m+w2/j8rv28PFxCnWaxwQX5QW44daZLXy9HiU4VuIBlN2Yxd9kMGt0PqkgtiVuF9nSu6+fmchjaMjgO3sA2YQTCGrIuTNedOvfD6CcxyOC4T5VMdZ1GFK36rd/O5WBgiyTrm77dNRsbY1MHzaMYgaRnqXCxFlHUdBHHDG74KFyclBah8KlihfxX9t9ipZcLf7Wk4BSZVIV3EhOmJfkOxlXF2SmgoOaaVH15Dmm/Dzzy3DcK2IzE1OWyPE3nm7Gpid3PDgl69t9z0zwakfqDRGC/ooXGoNzGOYWAqw7",
        "InstanceType": "Standard_B2s",
        "ImageEndpointUrl": "https://velodbgermanywestcentral.blob.core.windows.net/velodb-cloud-online-germanywestcentral",
        "SampleBucket": "velodb-import-data-germanywestcentral"
      }
    },
    "location": "[resourceGroup().location]",
    "uniqueSuffix": "[uniqueString(resourceGroup().id, parameters('VirtualNetwork'))]",
    "veloDBPublicKey": "[variables('RegionMap')[variables('location')].PublicKey]",
    "VeloDBBucketName": "[format('velodb{0}', variables('uniqueSuffix'))]",
    "VPCId": "[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork'))]",
    "RoleName": "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-data-access-identity-{0}', variables('StackName')))]",
    "ProjectId": "[resourceGroup().name]",
    "SubsId": "[split(subscription().id, '/')[2]]",
    "stackPrefix": "velodb-deployment-stack-",
    "stackSeed": "[substring(deployment().name, length(variables('stackPrefix')), sub(length(deployment().name), length(variables('stackPrefix'))))]",
    "lastIndex": "[lastIndexOf(variables('stackSeed'), '-')]",
    "StackName": "[if(equals(variables('lastIndex'), -1), variables('stackSeed'), substring(variables('stackSeed'), 0, variables('lastIndex')))]",
    "SgId": "[split(resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName'))), '/')[8]]",
    "Region": "[variables('location')]",
    "Zone": "[variables('RegionMap')[variables('location')].DefaultZone]",
    "ImageEndpointUrl": "[variables('RegionMap')[variables('location')].ImageEndpointUrl]",
    "SampleBucket": "[variables('RegionMap')[variables('location')].SampleBucket]",
    "customDataTemplate": "#!/bin/bash -xe\necho \"========== Start of User Data Script ==========\"\necho \"Timestamp: $(date '+%Y-%m-%d %H:%M:%S')\"\n\n# add linux user\nuseradd -m -s /bin/bash velodb\nmkdir -p /home/velodb/.ssh\nchown velodb:velodb /home/velodb/.ssh\nchmod 700 /home/velodb/.ssh\n\ntouch /home/velodb/.ssh/authorized_keys\nchown velodb:velodb /home/velodb/.ssh/authorized_keys\nchmod 600 /home/velodb/.ssh/authorized_keys\n\n# create sudoers for velodb\necho \"velodb ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/velodb\n\n# turn off the SELinux option permanently\nsed -i 's/^SELINUX=.*/SELINUX=disabled/' \"/etc/selinux/config\"\nsetenforce 0\n\n# install azure-cli\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\ndnf install -y https://packages.microsoft.com/config/rhel/9/packages-microsoft-prod.rpm\ndnf install -y azure-cli\naz version\naz login --identity --client-id {15}\n\n# get endpoint nic ip\nEndpointDns=$(az network nic show \\\n  --ids {0} \\\n  --query \"ipConfigurations[0].privateIPAddress\" -o tsv)\necho \"The endpoint nic private ip address is: $EndpointDns\"\n\n# env\nexport VPC_ID={1}\nexport SUBNET_ID={2}\nexport BUCKET_ID={3}\nexport USER_AK={4}\nexport USER_SK={5}\nexport BYOC_TOKEN={6}\nexport ENDPOINT_DNS=\"$EndpointDns\"\nexport ENDPOINT_URL=\"http://$EndpointDns\"\nexport IMAGE_ENDPOINT_URL={7}\nexport ROLE_NAME={8}\nexport PROVIDER='azure'\nexport REGION={9}\nexport ZONE={10}\nexport SAMPLE_BUCKET={11}\nexport PROJECT={12}\nexport STACK_NAME={13}\nexport STACK_ID='https://portal.azure.com/#@/resource/subscriptions/{14}/resourceGroups/{12}/providers/Microsoft.Resources/deploymentStacks/{13}/overview'\nexport SUBS_ID={14}\nexport CLIENT_ID={15}\nexport SG_ID={16}\nexport LOGICAL_ENDPOINT=\"apps-api.$REGION.$PROVIDER.velodb.cloud\"\n\n# install\nAGENT_DOWNLOAD='{7}/selectdb/packages/agent.tar.gz'\ncurl -fsSL -o configure_agent_byoc.sh '{7}/selectdb/packages/configure_agent_byoc_velodb.sh'\nchmod +x ./configure_agent_byoc.sh\n./configure_agent_byoc.sh $AGENT_DOWNLOAD $VPC_ID $SUBNET_ID $BUCKET_ID $USER_AK $USER_SK $BYOC_TOKEN $ENDPOINT_URL $IMAGE_ENDPOINT_URL \"\" $ROLE_NAME $PROVIDER $REGION $SAMPLE_BUCKET $PROJECT $ZONE $STACK_ID $STACK_NAME $SUBS_ID $CLIENT_ID $SG_ID \"\" \"\" \"\" \"\" \"online\"\n\ncurl -fsSL -o configure_byoc_modules.sh '{7}/selectdb/packages/configure_byoc_modules.sh'\nchmod +x ./configure_byoc_modules.sh\n./configure_byoc_modules.sh $IMAGE_ENDPOINT_URL $PROVIDER $REGION $VPC_ID $LOGICAL_ENDPOINT $BYOC_TOKEN\n\necho \"========== End of User Data Script ==========\"\necho \"Timestamp: $(date '+%Y-%m-%d %H:%M:%S')\"\n"
  },
  "resources": [
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2023-05-01",
      "name": "[format('velodb-sg-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      },
      "properties": {
        "flushConnection": false,
        "securityRules": [
          {
            "name": "[format('velodb-sg-ingress-{0}', variables('StackName'))]",
            "properties": {
              "access": "Allow",
              "description": "Allow traffic from the same vpc to access port 8000-10000",
              "destinationAddressPrefix": "*",
              "destinationPortRange": "8000-10000",
              "direction": "Inbound",
              "priority": 100,
              "protocol": "Tcp",
              "sourceAddressPrefix": "[if(and(and(contains(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01'), 'addressSpace'), contains(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace, 'addressPrefixes')), greater(length(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace.addressPrefixes), 0)), reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace.addressPrefixes[0], '0.0.0.0/0')]",
              "sourcePortRange": "*"
            }
          },
          {
            "name": "[format('velodb-sg-ingress-443-{0}', variables('StackName'))]",
            "properties": {
              "access": "Allow",
              "description": "Allow traffic from the same vpc to access port 443 for HTTPS unified communication",
              "destinationAddressPrefix": "*",
              "destinationPortRange": "443-443",
              "direction": "Inbound",
              "priority": 101,
              "protocol": "Tcp",
              "sourceAddressPrefix": "[if(and(and(contains(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01'), 'addressSpace'), contains(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace, 'addressPrefixes')), greater(length(reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace.addressPrefixes), 0)), reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks', parameters('VirtualNetwork')), '2023-05-01').addressSpace.addressPrefixes[0], '0.0.0.0/0')]",
              "sourcePortRange": "*"
            }
          },
          {
            "name": "[format('velodb-sg-egress-{0}', variables('StackName'))]",
            "properties": {
              "access": "Allow",
              "description": "Allow outbound traffic to all addresses",
              "destinationAddressPrefix": "*",
              "destinationPortRange": "*",
              "direction": "Outbound",
              "priority": 100,
              "protocol": "Tcp",
              "sourceAddressPrefix": "*",
              "sourcePortRange": "*"
            }
          }
        ]
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Network/privateEndpoints",
      "apiVersion": "2023-05-01",
      "name": "[format('velodb-endpoint-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      },
      "properties": {
        "subnet": {
          "id": "[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks/subnets', parameters('VirtualNetwork'), parameters('Subnet'))]",
          "properties": {
            "networkSecurityGroup": {
              "id": "[resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName')))]"
            }
          }
        },
        "manualPrivateLinkServiceConnections": [
          {
            "name": "[format('velodb-endpoint-connection-{0}', variables('StackName'))]",
            "properties": {
              "privateLinkServiceId": "[variables('RegionMap')[variables('location')].EndpointService]",
              "requestMessage": "Please approve my connection."
            }
          }
        ],
        "customNetworkInterfaceName": "[format('velodb-endpoint-nic-{0}', variables('StackName'))]"
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName')))]"
      ]
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[format('velodb{0}', variables('uniqueSuffix'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      },
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "properties": {
        "allowBlobPublicAccess": false,
        "allowSharedKeyAccess": true,
        "supportsHttpsTrafficOnly": false
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-05-01-preview",
      "name": "[guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'))]",
      "properties": {
        "roleName": "[format('velodb-control-plane-role-{0}', variables('StackName'))]",
        "type": "CustomRole",
        "assignableScopes": [
          "[resourceGroup().id]"
        ],
        "description": "The custom role will have the permissions allowing agent to quickly deploy and set up some Azure services.",
        "permissions": [
          {
            "actions": [
              "Microsoft.Compute/register/action",
              "Microsoft.Compute/virtualMachines/read",
              "Microsoft.Compute/virtualMachines/write",
              "Microsoft.Compute/virtualMachines/delete",
              "Microsoft.Compute/virtualMachines/start/action",
              "Microsoft.Compute/virtualMachines/powerOff/action",
              "Microsoft.Compute/virtualMachines/redeploy/action",
              "Microsoft.Compute/virtualMachines/restart/action",
              "Microsoft.Compute/virtualMachines/deallocate/action",
              "Microsoft.Compute/virtualMachines/runCommand/action",
              "Microsoft.Compute/virtualMachines/attachDetachDataDisks/action",
              "Microsoft.Compute/virtualMachines/vmSizes/read",
              "Microsoft.Compute/virtualMachines/runCommands/read",
              "Microsoft.Compute/virtualMachines/runCommands/write",
              "Microsoft.Compute/virtualMachines/instanceView/read",
              "Microsoft.Compute/virtualMachines/extensions/read",
              "Microsoft.Compute/locations/diskOperations/read",
              "Microsoft.Compute/disks/read",
              "Microsoft.Compute/disks/write",
              "Microsoft.Compute/disks/delete",
              "Microsoft.Compute/skus/read",
              "Microsoft.Compute/locations/usages/read",
              "Microsoft.Compute/locations/publishers/artifacttypes/offers/skus/read",
              "Microsoft.Compute/locations/publishers/artifacttypes/offers/read",
              "Microsoft.Compute/locations/publishers/artifacttypes/offers/skus/versions/read",
              "Microsoft.Compute/operations/read",
              "Microsoft.Compute/images/read",
              "Microsoft.Compute/locations/operations/read",
              "Microsoft.Compute/locations/vmSizes/read",
              "Microsoft.Compute/locations/runCommands/read",
              "Microsoft.Network/register/action",
              "Microsoft.Network/operations/read",
              "Microsoft.Network/loadBalancers/read",
              "Microsoft.Network/loadBalancers/write",
              "Microsoft.Network/loadBalancers/delete",
              "Microsoft.Network/loadBalancers/health/action",
              "Microsoft.Network/loadBalancers/backendAddressPools/queryInboundNatRulePortMapping/action",
              "Microsoft.Network/loadBalancers/backendAddressPools/updateAdminState/action",
              "Microsoft.Network/loadBalancers/backendAddressPools/health/action",
              "Microsoft.Network/loadBalancers/backendAddressPools/read",
              "Microsoft.Network/loadBalancers/backendAddressPools/write",
              "Microsoft.Network/loadBalancers/backendAddressPools/delete",
              "Microsoft.Network/loadBalancers/backendAddressPools/backendPoolAddresses/read",
              "Microsoft.Network/loadBalancers/backendAddressPools/join/action",
              "Microsoft.Network/loadBalancers/providers/Microsoft.Insights/diagnosticSettings/read",
              "Microsoft.Network/loadBalancers/providers/Microsoft.Insights/diagnosticSettings/write",
              "Microsoft.Network/loadBalancers/frontendIPConfigurations/read",
              "Microsoft.Network/loadBalancers/frontendIPConfigurations/join/action",
              "Microsoft.Network/loadBalancers/frontendIPConfigurations/loadBalancerPools/read",
              "Microsoft.Network/loadBalancers/frontendIPConfigurations/loadBalancerPools/write",
              "Microsoft.Network/loadBalancers/frontendIPConfigurations/loadBalancerPools/delete",
              "Microsoft.Network/loadBalancers/loadBalancingRules/read",
              "Microsoft.Network/loadBalancers/loadBalancingRules/health/action",
              "Microsoft.Network/loadBalancers/networkInterfaces/read",
              "Microsoft.Network/loadBalancers/outboundRules/read",
              "Microsoft.Network/loadBalancers/virtualMachines/read",
              "Microsoft.Network/loadBalancers/probes/read",
              "Microsoft.Network/loadBalancers/probes/join/action",
              "Microsoft.Network/loadBalancers/providers/Microsoft.Insights/metricDefinitions/read",
              "Microsoft.Network/networkInterfaces/read",
              "Microsoft.Network/networkInterfaces/write",
              "Microsoft.Network/networkInterfaces/join/action",
              "Microsoft.Network/networkInterfaces/delete",
              "Microsoft.Network/networkInterfaces/effectiveRouteTable/action",
              "Microsoft.Network/networkInterfaces/effectiveNetworkSecurityGroups/action",
              "Microsoft.Network/networkInterfaces/ipconfigurations/read",
              "Microsoft.Network/networkInterfaces/loadBalancers/read",
              "Microsoft.Network/networkSecurityGroups/read",
              "Microsoft.Network/networkSecurityGroups/write",
              "Microsoft.Network/networkSecurityGroups/delete",
              "Microsoft.Network/networkSecurityGroups/join/action",
              "Microsoft.Network/virtualNetworks/read",
              "Microsoft.Network/virtualNetworks/joinLoadBalancer/action",
              "Microsoft.Network/virtualNetworks/subnets/read",
              "Microsoft.Network/virtualNetworks/subnets/join/action",
              "Microsoft.Network/virtualNetworks/subnets/joinLoadBalancer/action",
              "Microsoft.Network/ipAllocations/read",
              "Microsoft.Network/publicIPAddresses/read",
              "Microsoft.Storage/storageAccounts/blobServices/containers/read",
              "Microsoft.Storage/storageAccounts/blobServices/containers/write",
              "Microsoft.Storage/storageAccounts/blobServices/containers/delete",
              "Microsoft.ManagedIdentity/userAssignedIdentities/read",
              "Microsoft.ManagedIdentity/userAssignedIdentities/assign/action"
            ]
          }
        ]
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-05-01-preview",
      "name": "[guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBVnetReadRole')]",
      "properties": {
        "roleName": "[format('velodb-vnet-read-role-{0}', variables('StackName'))]",
        "type": "CustomRole",
        "assignableScopes": [
          "[resourceGroup().id]",
          "[subscriptionResourceId('Microsoft.Resources/resourceGroups', parameters('VirtualNetworkResourceGroup'))]"
        ],
        "description": "This read-only role lets the agent read the virtual network and subnets (e.g. to get the subnet CIDR).",
        "permissions": [
          {
            "actions": [
              "Microsoft.Network/virtualNetworks/read",
              "Microsoft.Network/virtualNetworks/subnets/read",
              "Microsoft.Network/virtualNetworks/subnets/join/action"
            ]
          }
        ]
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
      "apiVersion": "2018-11-30",
      "name": "[format('velodb-data-access-identity-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "scope": "[resourceId('Microsoft.Storage/storageAccounts', format('velodb{0}', variables('uniqueSuffix')))]",
      "name": "[guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBDataAccessRole')]",
      "properties": {
        "principalType": "ServicePrincipal",
        "principalId": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-data-access-identity-{0}', variables('StackName'))), '2018-11-30').principalId]",
        "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b')]",
        "description": "This data-access role grants access to the ms/fe/be identity."
      },
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', format('velodb{0}', variables('uniqueSuffix')))]",
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-data-access-identity-{0}', variables('StackName')))]"
      ]
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
      "apiVersion": "2018-11-30",
      "name": "[format('velodb-agent-identity-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      }
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "name": "[guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBControlPlaneRoleForAgent')]",
      "properties": {
        "principalType": "ServicePrincipal",
        "principalId": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName'))), '2018-11-30').principalId]",
        "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName')))]",
        "description": "This control-plane role grants access to the agent identity."
      },
      "dependsOn": [
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName')))]"
      ]
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2023-05-01",
      "name": "[format('velodb-agent-nic-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      },
      "properties": {
        "networkSecurityGroup": {
          "id": "[resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName')))]"
        },
        "ipConfigurations": [
          {
            "name": "[format('velodb-agent-ipconfig-{0}', variables('StackName'))]",
            "properties": {
              "subnet": {
                "id": "[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('VirtualNetworkResourceGroup')), 'Microsoft.Network/virtualNetworks/subnets', parameters('VirtualNetwork'), parameters('Subnet'))]"
              },
              "privateIPAllocationMethod": "Dynamic"
            }
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName')))]"
      ]
    },
    {
      "condition": "[not(parameters('SkipStack'))]",
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2023-07-01",
      "name": "[format('velodb-agent-{0}', variables('StackName'))]",
      "location": "[variables('location')]",
      "tags": {
        "resource-created-by": "velodb",
        "cloud-resource-profile": "online",
        "resource-used-by-app": "BYOC"
      },
      "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
          "[format('{0}', resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName'))))]": {}
        }
      },
      "properties": {
        "hardwareProfile": {
          "vmSize": "[parameters('InstanceType')]"
        },
        "storageProfile": {
          "imageReference": {
            "publisher": "almalinux",
            "offer": "almalinux-x86_64",
            "sku": "9-gen2",
            "version": "latest"
          },
          "osDisk": {
            "osType": "Linux",
            "name": "[format('velodb-agent-bootdisk-{0}', variables('StackName'))]",
            "caching": "ReadWrite",
            "createOption": "FromImage",
            "deleteOption": "Delete",
            "diskSizeGB": 64
          }
        },
        "osProfile": {
          "computerName": "[format('velodb-agent-{0}', variables('StackName'))]",
          "adminUsername": "velodbadmin",
          "linuxConfiguration": {
            "disablePasswordAuthentication": true,
            "ssh": {
              "publicKeys": [
                {
                  "path": "/home/velodbadmin/.ssh/authorized_keys",
                  "keyData": "[variables('veloDBPublicKey')]"
                }
              ]
            }
          },
          "customData": "[base64(format(variables('customDataTemplate'), reference(resourceId('Microsoft.Network/privateEndpoints', format('velodb-endpoint-{0}', variables('StackName'))), '2023-05-01').networkInterfaces[0].id, variables('VPCId'), parameters('Subnet'), variables('VeloDBBucketName'), variables('VeloDBBucketName'), listKeys(resourceId('Microsoft.Storage/storageAccounts', format('velodb{0}', variables('uniqueSuffix'))), '2023-01-01').keys[0].value, parameters('Token'), variables('ImageEndpointUrl'), variables('RoleName'), variables('Region'), variables('Zone'), variables('SampleBucket'), variables('ProjectId'), variables('StackName'), variables('SubsId'), reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName'))), '2018-11-30').clientId, variables('SgId')))]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', format('velodb-agent-nic-{0}', variables('StackName')))]",
              "properties": {
                "primary": true,
                "deleteOption": "Delete"
              }
            }
          ]
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Network/networkInterfaces', format('velodb-agent-nic-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Storage/storageAccounts', format('velodb{0}', variables('uniqueSuffix')))]",
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-data-access-identity-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Network/privateEndpoints', format('velodb-endpoint-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups', format('velodb-sg-{0}', variables('StackName')))]"
      ]
    },
    {
      "condition": "[and(not(parameters('SkipStack')), not(equals(parameters('VirtualNetworkResourceGroup'), resourceGroup().name)))]",
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2025-04-01",
      "name": "[format('velodb-agent-vnet-read-role-{0}', variables('StackName'))]",
      "resourceGroup": "[parameters('VirtualNetworkResourceGroup')]",
      "properties": {
        "expressionEvaluationOptions": {
          "scope": "inner"
        },
        "mode": "Incremental",
        "parameters": {
          "roleDefinitionId": {
            "value": "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBVnetReadRole'))]"
          },
          "principalId": {
            "value": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName'))), '2018-11-30').principalId]"
          },
          "assignmentName": {
            "value": "[guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBVnetReadRoleCrossRG')]"
          },
          "description": {
            "value": "This read-only role grants the agent identity read access to the virtual network."
          }
        },
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "metadata": {
            "_generator": {
              "name": "bicep",
              "version": "0.46.1.21595",
              "templateHash": "12019534964584642873"
            }
          },
          "parameters": {
            "roleDefinitionId": {
              "type": "string"
            },
            "principalId": {
              "type": "string"
            },
            "assignmentName": {
              "type": "string"
            },
            "description": {
              "type": "string",
              "defaultValue": ""
            }
          },
          "resources": [
            {
              "type": "Microsoft.Authorization/roleAssignments",
              "apiVersion": "2022-04-01",
              "name": "[parameters('assignmentName')]",
              "properties": {
                "principalType": "ServicePrincipal",
                "principalId": "[parameters('principalId')]",
                "roleDefinitionId": "[parameters('roleDefinitionId')]",
                "description": "[parameters('description')]"
              }
            }
          ]
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', format('velodb-agent-identity-{0}', variables('StackName')))]",
        "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceGroup().id, parameters('VirtualNetwork'), variables('StackName'), 'VeloDBVnetReadRole'))]"
      ]
    }
  ],
  "outputs": {
    "VeloDBStackName": {
      "type": "string",
      "value": "[variables('StackName')]"
    },
    "VeloDBSkipStack": {
      "type": "bool",
      "value": "[parameters('SkipStack')]"
    },
    "VeloDBSecurityGroupName": {
      "type": "string",
      "value": "[format('velodb-sg-{0}', variables('StackName'))]"
    },
    "VeloDBEndpointName": {
      "type": "string",
      "value": "[format('velodb-endpoint-{0}', variables('StackName'))]"
    },
    "VeloDBBucketName": {
      "type": "string",
      "value": "[format('velodb{0}', variables('uniqueSuffix'))]"
    },
    "VeloDBBucket": {
      "type": "string",
      "value": "[reference(resourceId('Microsoft.Storage/storageAccounts', format('velodb{0}', variables('uniqueSuffix'))), '2023-01-01').primaryEndpoints.blob]"
    },
    "VeloDBAgentName": {
      "type": "string",
      "value": "[format('velodb-agent-{0}', variables('StackName'))]"
    }
  }
}