Skip to content

Commit

Permalink
AzureFileCopyV6: Supports WIF and remove usage of SAS token. (#19650)
Browse files Browse the repository at this point in the history
* new task creation

* sas removal+ WIF+ Azlogin

* build

* update finally block

* task version to 237

* remove sas tc

* update gdnguidlines to fix pr failure

* added v6 in make-option.json

* updated gdn

* updated releaseNotes

* updated utility.ps1 file

* added issue link

* add RBAC related link

* Storage context creation with
Microsoft Entra credentials.

* build storage context creation with
Microsoft Entra credentials.
  • Loading branch information
v-mohithgc authored Mar 22, 2024
1 parent 9e519cb commit f530b05
Show file tree
Hide file tree
Showing 117 changed files with 18,355 additions and 0 deletions.
66 changes: 66 additions & 0 deletions .gdn/.gdnbaselines
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,72 @@
}
},
"results": {
"407cc257f37ce2a1a83660de9e661902b2aad514f7ca760e16ed4ac555cff1c3": {
"signature": "407cc257f37ce2a1a83660de9e661902b2aad514f7ca760e16ed4ac555cff1c3",
"alternativeSignatures": [
"fee414b5ea08713bc228b9edf15baee950baba8f8fa35f9c67be6e86795b77ee"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 15:10:36Z"
},
"9115d8d02bc9d2b3aa7a0509f742da5087765a603bf954512923566fa4ffa946": {
"signature": "9115d8d02bc9d2b3aa7a0509f742da5087765a603bf954512923566fa4ffa946",
"alternativeSignatures": [
"5330e2e2159d8073e5a7492e49d705b60c40b85436b9406e2ef4b8a19af77cca"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 15:10:36Z"
},
"784fc91626d8ee62fd3f99d56999618147f2b68218768aeeb7ea064ded65e6db": {
"signature": "784fc91626d8ee62fd3f99d56999618147f2b68218768aeeb7ea064ded65e6db",
"alternativeSignatures": [
"b67a25df17a2218170da5aa5eff32ed84727c6ba9f02f7a2308c7162a0821dfa"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 15:10:36Z"
},
"158c4b23b4ff681530f30aa80653ae6261210f9777a2cfd0f3535ebc66dfb227": {
"signature": "158c4b23b4ff681530f30aa80653ae6261210f9777a2cfd0f3535ebc66dfb227",
"alternativeSignatures": [
"c832f5a0cc0e2ce50496a2860c006279a37505b1a69c6a2ccb70295481910468"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 10:25:39Z",
"justification": "PSAvoidUsingConvertToSecureStringWithPlainText"
},
"2c02eec8cf96bc63fb8ff72417da0e84215ba8dead870baedfdad351e7659372": {
"signature": "2c02eec8cf96bc63fb8ff72417da0e84215ba8dead870baedfdad351e7659372",
"alternativeSignatures": [
"92f202b770c277f86d23afc5fc79c53b64a7f2fe00544f9f4e0019e36403fd40"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 10:25:39Z",
"justification": "PSAvoidUsingUsernameAndPasswordParams"
},
"60a0aa841d38e44479e47d9d4349475efeb49a3e8f4cd8adfbe8ec832160713b": {
"signature": "60a0aa841d38e44479e47d9d4349475efeb49a3e8f4cd8adfbe8ec832160713b",
"alternativeSignatures": [
"30cc30f55e8853b028db85e8d8056968a779e3376453b4a28abafd228153f6be"
],
"memberOf": [
"default"
],
"createdDate": "2024-03-20 10:25:39Z",
"justification": "PSAvoidUsingConvertToSecureStringWithPlainText"
},



"a2a4017726eb18c7612da6ab3828cfdfd1218160fbd5d373c715476df1847499": {
"signature": "a2a4017726eb18c7612da6ab3828cfdfd1218160fbd5d373c715476df1847499",
"alternativeSignatures": [
Expand Down
4 changes: 4 additions & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ Tasks/AzureFileCopyV3/ @microsoft/release-management-task-team @manolerazvan

Tasks/AzureFileCopyV4/ @microsoft/release-management-task-team @manolerazvan

Tasks/AzureFileCopyV5/ @microsoft/release-management-task-team @manolerazvan

Tasks/AzureFileCopyV6/ @microsoft/release-management-task-team @manolerazvan

Tasks/AzureFunctionAppV1/ @finvamp1 @patelchandni @microsoft/release-management-task-team @manolerazvan

Tasks/AzureFunctionAppV2/ @finvamp1 @patelchandni @microsoft/release-management-task-team @manolerazvan
Expand Down
257 changes: 257 additions & 0 deletions Tasks/AzureFileCopyV6/AzureFileCopy.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
[CmdletBinding()]
param()

Trace-VstsEnteringInvocation $MyInvocation

# Get inputs for the task
$sourcePath = Get-VstsInput -Name SourcePath -Require
$destination = Get-VstsInput -Name Destination -Require
$connectedServiceName = Get-VstsInput -Name ConnectedServiceNameARM -Require
$storageAccount = Get-VstsInput -Name StorageAccountRM
$containerName = Get-VstsInput -Name ContainerName
$blobPrefix = Get-VstsInput -Name BlobPrefix
$environmentName = Get-VstsInput -Name EnvironmentNameRM
$resourceFilteringMethod = Get-VstsInput -Name ResourceFilteringMethod
$machineNames = Get-VstsInput -Name MachineNames
$vmsAdminUserName = Get-VstsInput -Name VmsAdminUsername
$vmsAdminPassword = Get-VstsInput -Name VmsAdminPassword
$targetPath = Get-VstsInput -Name TargetPath
$additionalArgumentsForBlobCopy = Get-VstsInput -Name AdditionalArgumentsForBlobCopy
$additionalArgumentsForVMCopy = Get-VstsInput -Name AdditionalArgumentsForVMCopy
$cleanTargetBeforeCopy = Get-VstsInput -Name CleanTargetBeforeCopy -AsBool
$copyFilesInParallel = Get-VstsInput -Name CopyFilesInParallel -AsBool
$skipCACheck = Get-VstsInput -Name SkipCACheck -AsBool
$enableCopyPrerequisites = Get-VstsInput -Name EnableCopyPrerequisites -AsBool

if ($destination -ne "AzureBlob") {
$blobPrefix = ""
}

# Constants
$useHttpsProtocolOption = ''
$ErrorActionPreference = 'Stop'
$telemetrySet = $false
$isPremiumStorage = $false

$sourcePath = $sourcePath.Trim('"')
$storageAccount = $storageAccount.Trim()
$containerName = $containerName.Trim().ToLower()

$additionalArgumentsForBlobCopy = $additionalArgumentsForBlobCopy.Trim()
$additionalArgumentsForVMCopy = $additionalArgumentsForVMCopy.Trim()
$useDefaultArgumentsForBlobCopy = ($additionalArgumentsForBlobCopy -eq "")

# azcopy location on automation agent
$azCopyExeLocation = 'AzCopy\AzCopy.exe'
$azCopyLocation = [System.IO.Path]::GetDirectoryName($azCopyExeLocation)

# Import RemoteDeployer
Import-Module $PSScriptRoot\ps_modules\RemoteDeployer

# Initialize Azure.
Import-Module $PSScriptRoot\ps_modules\VstsAzureHelpers_

$endpoint = Get-VstsEndpoint -Name $connectedServiceName -Require

# Update PSModulePath for hosted agent
. "$PSScriptRoot\Utility.ps1"

CleanUp-PSModulePathForHostedAgent

$vstsEndpoint = Get-VstsEndpoint -Name SystemVssConnection -Require
$vstsAccessToken = $vstsEndpoint.auth.parameters.AccessToken

if (Get-Module Az.Accounts -ListAvailable) {
$encryptedToken = ConvertTo-SecureString $vstsAccessToken -AsPlainText -Force
Initialize-AzModule -Endpoint $endpoint -connectedServiceNameARM $connectedServiceName -encryptedToken $encryptedToken
}
else {
Write-Verbose "No module found with name: Az.Accounts"
throw ("Could not find the module Az.Accounts with given version. If the module was recently installed, retry after restarting the Azure Pipelines task agent.")
}

# Import the loc strings.
Import-VstsLocStrings -LiteralPath $PSScriptRoot/Task.json

# Load all dependent files for execution
. "$PSScriptRoot\AzureFileCopyRemoteJob.ps1"

# Enabling detailed logging only when system.debug is true
$enableDetailedLogging = ($env:system_debug -eq "true")

# Telemetry
Import-Module $PSScriptRoot\ps_modules\TelemetryHelper

# Sanitizer
Import-Module $PSScriptRoot\ps_modules\Sanitizer
$useSanitizerCall = Get-SanitizerCallStatus
$useSanitizerActivate = Get-SanitizerActivateStatus

if ($useSanitizerCall) {
$sanitizedArgumentsForBlobCopy = Protect-ScriptArguments -InputArgs $additionalArgumentsForBlobCopy -TaskName "AzureFileCopyV5"
$sanitizedArgumentsForVMCopy = Protect-ScriptArguments -InputArgs $additionalArgumentsForVMCopy -TaskName "AzureFileCopyV5"
}

if ($useSanitizerActivate) {
$additionalArgumentsForBlobCopy = $sanitizedArgumentsForBlobCopy -join " "
$additionalArgumentsForVMCopy = $sanitizedArgumentsForVMCopy -join " "
}

#### MAIN EXECUTION OF AZURE FILE COPY TASK BEGINS HERE ####
try {
try {
# Importing required version of azure cmdlets according to azureps installed on machine
$azureUtility = Get-AzureUtility

Write-Verbose -Verbose "Loading $azureUtility"
. "$PSScriptRoot/$azureUtility"

# Telemetry for endpoint id
$telemetryJsonContent = "{`"endpointId`":`"$connectedServiceName`"}"
Write-Host "##vso[telemetry.publish area=TaskEndpointId;feature=AzureFileCopy]$telemetryJsonContent"


# creating storage context to be used while creating container, deleting container
$storageContext = Create-AzureStorageContextWithConnectedAcc -StorageAccountName $storageAccount

# Geting Azure Storage Account type
$storageAccountType = Get-StorageAccountType $storageAccount $endpoint $connectedServiceName $vstsAccessToken
Write-Verbose "Obtained Storage Account type: $storageAccountType"
if (-not [string]::IsNullOrEmpty($storageAccountType) -and $storageAccountType.Contains('Premium')) {
$isPremiumStorage = $true
}

# creating temporary container for uploading files if no input is provided for container name
if ([string]::IsNullOrEmpty($containerName) -or ($destination -ne "AzureBlob")) {
$containerName = [guid]::NewGuid().ToString()
Write-Verbose "Container Name input not found. Creating Temporary container for uploading files."
Create-AzureContainer -containerName $containerName -storageContext $storageContext
}
else {
#checking if the containerName provided exist or not
$containerPresent = Get-AzureContainer -containerName $containerName -storageContext $storageContext

#creating container if the containerName provided does not exist
if ($null -eq $containerPresent) {
Write-Verbose "Creating container if the containerName provided does not exist"
Create-AzureContainer -containerName $containerName -storageContext $storageContext
}
}


# Getting Azure Blob Storage Endpoint
$blobStorageEndpoint = Get-blobStorageEndpoint -storageAccountName $storageAccount -endpoint $endpoint -vstsAccessToken $vstsAccessToken

# Setting environment variable for tracking Azure Pipelines usage in AzCopy telemetry
$env:AZCOPY_USER_AGENT_PREFIX = "TFS_useragent"
}
catch {
Write-Verbose $_.Exception.ToString()
Write-Telemetry "Task_InternalError" "TemporaryCopyingToBlobContainerFailed"
throw
}

# Set optional arguments for azcopy blob upload
if ($useDefaultArgumentsForBlobCopy) {
# Adding default optional arguments:
# log-level: Defines the log verbosity for the log file. Default is INFO(all requests/responses)

Write-Verbose "Using default AzCopy arguments for uploading to blob storage"

$additionalArgumentsForBlobCopy = "--log-level=INFO"

# Add more arguments if required

# Premium storage accounts only support page blobs
if ($isPremiumStorage) {
Write-Verbose "Setting BlobType to page for Premium Storage account."
$additionalArgumentsForBlobCopy += " --blob-type=PageBlob"
}

# $root container does not support sub folders. So excluding recursive copy option for $root container.
if ($containerName -ne '$root') {
Write-Verbose "Adding argument for recursive copy"
$additionalArgumentsForBlobCopy += " --recursive"
}
}

Check-ContainerNameAndArgs -containerName $containerName -additionalArguments $additionalArgumentsForBlobCopy

# Uploading files to container
Upload-FilesToAzureContainer -sourcePath $sourcePath `
-endPoint $endpoint `
-storageAccountName $storageAccount `
-containerName $containerName `
-blobPrefix $blobPrefix `
-blobStorageEndpoint $blobStorageEndpoint `
-azCopyLocation $azCopyLocation `
-additionalArguments $additionalArgumentsForBlobCopy `
-destinationType $destination `
-useDefaultArguments $useDefaultArgumentsForBlobCopy `
-cleanTargetBeforeCopy $cleanTargetBeforeCopy `
-useSanitizerActivate $useSanitizerActivate

# Complete the task if destination is azure blob
if ($destination -eq "AzureBlob") {
# Get URI for output variable
$storageAccountContainerURI = $storageContext.BlobEndPoint + $containerName + "/"
Write-Host "##vso[task.setvariable variable=StorageContainerUri]$storageAccountContainerURI"

Remove-EndpointSecrets
Write-Verbose "Completed Azure File Copy Task for Azure Blob Destination"

return
}

# Copying files to Azure VMs
try {
# Normalize admin username
if ($vmsAdminUserName -and (-not $vmsAdminUserName.StartsWith(".\")) -and ($vmsAdminUserName.IndexOf("\") -eq -1) -and ($vmsAdminUserName.IndexOf("@") -eq -1)) {
$vmsAdminUserName = ".\" + $vmsAdminUserName
}
# getting azure vms properties(name, fqdn, winrmhttps port)
$azureVMResourcesProperties = Get-AzureVMResourcesProperties -resourceGroupName $environmentName `
-resourceFilteringMethod $resourceFilteringMethod -machineNames $machineNames -enableCopyPrerequisites $enableCopyPrerequisites `
-connectedServiceName $connectedServiceName -vstsAccessToken $vstsAccessToken

$azureVMsCredentials = Get-AzureVMsCredentials -vmsAdminUserName $vmsAdminUserName -vmsAdminPassword $vmsAdminPassword

# Get Invoke-RemoteScript parameters
$invokeRemoteScriptParams = Get-InvokeRemoteScriptParameters -azureVMResourcesProperties $azureVMResourcesProperties `
-networkCredentials $azureVMsCredentials `
-skipCACheck $skipCACheck

# Copies files on azureVMs
Copy-FilesToAzureVMsFromStorageContainer -targetMachineNames $invokeRemoteScriptParams.targetMachineNames `
-credential $invokeRemoteScriptParams.credential `
-protocol $invokeRemoteScriptParams.protocol `
-sessionOption $invokeRemoteScriptParams.sessionOption `
-blobStorageEndpoint $blobStorageEndpoint `
-containerName $containerName `
-targetPath $targetPath `
-cleanTargetBeforeCopy $cleanTargetBeforeCopy `
-copyFilesInParallel $copyFilesInParallel `
-additionalArguments $additionalArgumentsForVMCopy `
-azCopyToolLocation $azCopyLocation `
-fileCopyJobScript $AzureFileCopyRemoteJob `
-enableDetailedLogging $enableDetailedLogging `
-useSanitizerActivate $useSanitizerActivate

Write-Output (Get-VstsLocString -Key "AFC_CopySuccessful" -ArgumentList $sourcePath, $environmentName)
}
catch {
Write-Verbose $_.Exception.ToString()

Write-Telemetry "Task_InternalError" "CopyingToAzureVMFailed"
throw
}
finally {
Remove-AzureContainer -containerName $containerName -storageContext $storageContext
Remove-EndpointSecrets
Write-Verbose "Completed Azure File Copy Task for Azure VMs Destination" -Verbose
Trace-VstsLeavingInvocation $MyInvocation
}
}
finally {
Disconnect-AzureAndClearContext -authScheme $endpoint.Auth.Scheme -ErrorAction SilentlyContinue
}
Loading

0 comments on commit f530b05

Please sign in to comment.