Microsoft Azure – Creating JSON Snippet For Policy Initiative Creation using CSV File
Here in this article, we are going to create a custom JSON script by using the data filled in the CSV file for automation.
What we are going to do is first we’ll convert a list of given Policy IDs from CSV to JSON Code Snippet as a prerequisite for creating a custom policy initiative definition for automation.
Implementation:
Follow the below steps to create a JSON snippet for policy initiative creation using a CSV file:
Step 1: Create a new with .csv extension and policies id’s to it and format should look like this. ‘PolicyID’ as Header and Add required Policy Definition Id(s) as Values one after the other.
Step 2: After creating the csv, Login to Azure Portal
Step 3: From Azure Portal Access the cloud shell and select PowerShell
Step 4: Now Upload the created CSV File to cloud shell storage
Open Cloud Shell and Click on Upload/Download files >> Select Upload >> Choose your created CSV file from your local disk and select.
Step 5: Now, create a new PowerShell file with .ps1 extension.
Syntax:
touch <filename>.ps1
code <filename>.ps1
Example:
touch policygen.ps1
Code policygen.ps1
Open the <filename>.ps1 and Copy paste the following code and save the file
$PolicyIDs = Import-CSV .\PolicyID.csv Write-Output "[" foreach ($PolicyID in $PolicyIDs) { Write-Output " {" Write-Output (" " + " ""policyDefinitionId""" + " : " + """/providers/Microsoft.Authorization/policyDefinitions/" + $Policy.PolicyID + """,") Write-Output " }," } Write-Output "]"
Step 6: Run the <filename>.ps1 file
./<filename>.ps1
Example:
./policygen.ps1
Output:
Step 7: Save console output to a file with .json extension.
./<filename>.ps1 | Out-File ./<filename>.json
Example:
./policygen.ps1 | Out-File ./sample.json
Output:
Now, this sample.json script can be used in CI/CD Pipelines Automation for Created or Updating the Custom Initiative Definitions and Policy Definitions or it can also be used with Azure PowerShell Cmdlets.