This blog will help to setup and use of the encrypted password in Azure DevOps Pipeline to connect to Azure. This technique can be also customize as per your requirement.
Note: This is applicable for self hosted Agent and If you want to learn how to configure self hosted agent please follow below article.
Encrypt the Password/Secret using the Pipeline [Self Hosted Agent]
Save the encrypted Public Key [Which can only be decrypted by Agent]
Encryption will use the Self signed Certificate.
Decrypt the Key and connect to Azure
First we need to encrypt the password/secret using the Azure DevOps Pipeline which is using self hosted Agent. Hence the password/secret will be encrypted using the agent and the agent service account.
Create a test pipeline to encrypt the password and make sure the self hosted agent is configured with the Pipeline. Download the build yaml file from below link.
Check in the downloaded yaml file into you Azure DevOps Repos.
Create one yaml Pipeline with checked in "azure-pipelines.yml".
Once the Pipeline created. Make sure to update the Pool setting under the Azure-pipelines.yml with your self-hosted- agent pool name.
In my case it is : custom-agent.
code snipped from Azure-pipelines.yml
- name: User
displayName: 'UserID like: email@example.com'
- name: Password
- name: SelfSignCertificateName
Once the pool information updated from step 4. Run the Pipeline with below Parameter.
UserID [User Details to connect to Azure]
Password [User Password for Encryption]
Self Signed Certificate Name [Certificate Name will be created during the execution]
On successful execution the Encrypted Password will be stored on the Agent Machine.
Now this encrypted password can be used further in the Pipeline execution or for your Automation work.
You can keep this pipeline for any Password/Secret Encryption and only Agent will be able to decrypt it since it has the Private Key.
if you want to learn more about this encryption method. You can follow below Link.
Connect to Azure
Since we have encrypted the Password now we can use this encrypted password to connect to Azure.
The encrypted password is stored at C:\CredentialEncryption\credentials.txt. you can keep this file at any relevant location but now i will use from the same location.
You can use below PowerShell snipped to Connect to Azure.
Note: Since the password is encrypted by configured Self Hosted Agent make sure the Below script is used to run on the same agent so that it will be able to decrypt the password.
#Decrypt the credential first and connect to Azure
$creds = Import-Csv -Path "C:\CredentialEncryption\credentials.txt"
$userName = $creds.UserName
$securePassword = $creds.Password | Unprotect-CmsMessage | ConvertTo-SecureString
#Creating credential object
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
Connect-AzAccount -Credential $credential | Out-Null