Showing posts with label Automation. Show all posts
Showing posts with label Automation. Show all posts

May 29, 2025

Streamline SPFx Builds with Azure DevOps CI/CD Pipeline – Part 2: Automating Deployment (CD)

Introduction

In the First Part, we built a Continuous Integration (CI) pipeline to automatically package our SharePoint Framework (SPFx) solution. Now it’s time to automate deployment across multiple SharePoint sites using Continuous Deployment (CD).

This blog covers setting up a CD pipeline in Azure DevOps, triggered automatically after your CI pipeline finishes, to deploy your .sppkg file to all the required sites. 


Step 1: Prepare Your PowerShell Deployment Script

We’ll use PowerShell with PnP.PowerShell to handle the deployment. This script connects to SharePoint Online, uploads the .sppkg package, and publishes it on each target site.

Here's the script:

  Param (  
   [string] $RootPath = $(Throw "Root Path is required."),  
   [string] $ClientId = $(Throw "ClientId is required."),  
   [string] $TenantId = $(Throw "TenantId is required."),  
   [string] $TenantURL = $(Throw "Tenant URL is required."),  
   [string] $ClientSecret = $(Throw "Client Secret is required."),  
   [string] $packagename = $(Throw "Package name is required.")  
 )  
 $SiteURL = "$($TenantURL)/sites/TestSite"  
 $ModernPOPAppPath = "$RootPath\drop\$packagename"  
 $currentPOPSite = ""  
 function ReconnectPNPConnection {  
   Write-Host "Reconnecting to site $($currentPOPSite)"  
   Disconnect-PnPOnline  
   Connect-PnPOnline -Url $currentPOPSite -ClientId $ClientId -ClientSecret $ClientSecret -Tenant $TenantId  
 }  
 function addCustomSPFxApps {  
   $appCatalog = Get-PnPSiteCollectionAppCatalog -CurrentSite -ErrorAction SilentlyContinue  
   while ($null -eq $appCatalog) {  
     Write-Host "Waiting for app catalog creation..."  
     Start-Sleep -Seconds 30  
     $appCatalog = Get-PnPSiteCollectionAppCatalog -CurrentSite -ErrorAction SilentlyContinue  
   }  
   $uploadApp = $false  
   while ($uploadApp -eq $false) {  
     try {  
       Write-Host "Uploading SPFx app..."  
       $App = Add-PnPApp -Path $ModernPOPAppPath -Scope Site -Overwrite -Timeout 900  
       Write-Host "Publishing SPFx app..."  
       Publish-PnPApp -Identity $App.ID -Scope Site -SkipFeatureDeployment -ErrorAction SilentlyContinue  
       Write-Host "SPFx app deployed successfully."  
       Start-Sleep -Seconds 60  
       $uploadApp = $true  
     } catch {  
       Write-Host $_.Exception.Message  
       Write-Host "Retrying after 30 seconds..."  
       Start-Sleep -Seconds 30  
       ReconnectPNPConnection  
     }  
   }  
 }  
 Write-Host -f Cyan "Installing PnP.PowerShell module..."  
 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12  
 Install-Module PnP.PowerShell -RequiredVersion 2.4.0 -Force -Scope CurrentUser  
 Import-Module -Name "PnP.PowerShell"  
 Write-Host "Connecting to $($SiteURL)..."  
 Connect-PnPOnline -Url $SiteURL -ClientId $ClientId -ClientSecret $ClientSecret -Tenant $TenantId  
 $currentPOPSite = $SiteURL  
 addCustomSPFxApps  
 Write-Host "Disconnecting from $($SiteURL)..."  
 Disconnect-PnPOnline  

We need to upload this PowerShell script to a document folder as shown below and add a step in the CI (Continuous Integration) pipeline to copy this file into the artifacts.


Step 2: Set Up the CD Pipeline in Azure DevOps

1. Create the Release Pipeline:

  • Navigate to the Release section in Azure DevOps.
  • Click New Pipeline.

2. Add Artifacts:

  • Link your CI pipeline’s artifacts (the .sppkg file and related files).test

3. Enable Continuous Deployment Trigger:

  • Click the lightning bolt icon next to the artifact and enable the trigger to deploy automatically after CI.

4. Add a Stage:

  • Click Add a stage and choose Empty Job.

5. Add PowerShell Task:

  • In the stage, click to add a task.
  • Choose PowerShell.
  • Set the script path to point to your deployment script (e.g., Documents/CDScript.ps1).
  • Set the necessary parameters (RootPath, ClientId, TenantId, etc.).

6. Save and Deploy:

  • Save the pipeline and test it by running the full CI/CD process.

Conclusion

By integrating both CI and CD pipelines in Azure DevOps, you’ve established a fully automated and reliable deployment process for your SPFx solutions:

  • CI Pipeline: Automatically builds and packages your SPFx solution on every code push.
  • CD Pipeline: Seamlessly deploys the package to all required SharePoint sites immediately after a successful build.

This setup not only saves time but also ensures consistency and reduces the risk of manual deployment errors across environments.

If you have any questions you can reach out our SharePoint Consulting team here.

February 21, 2025

Automate SharePoint Site Creation with PowerShell and Power Automate

Introduction:

Creating and managing SharePoint sites quickly and easily is important for any organization. By using PowerShell and Power Automate, you can automate site creation and include useful workflows in your site templates. This guide will show you how to create a custom SharePoint site template that makes settings up new sites simple and consistent.


Key Features of This Approach:

  • Power Automate Integration: Automatically run workflows whenever a new site is created.

  • Custom Site Scripts: Use simple scripts to define how your sites look and work.

  • Easy site Management: Set up themes, time zones, and site logos with just a script.

  • Workflow Automation: Automatically send notifications or track site creation details using workflows.


Benefits:

  • Save Times: Automates repetitive work.
  • Keeps Things Consistent: Make sure every new site follows the same setup and rules.
  • Scalable: Handles creating lots of sites without manual work.
  • Easy to Customize: You can change templates anytime to match your needs.

Steps to Implement

1. Setup a Power Automate Flow:

     Power Automate will handle workflows triggered during the site creation process.

     Steps to create the flow: 

        1. Go to Power Automate.

        2. Click "New Flow" > "Automated Cloud Flow".
         

        3. Name the flow (e.g., "PowerShell through calling a Power Automate") and click "Skip".
        

        4. Add the "When an HTTP request is received" trigger.
        

        5. Configure the trigger settings.

                a. Under "Who can trigger the flow?" select "Anyone".
                

                b. Add the following Request Body JSON Schema.

    {
      "type": "object",
      "properties": {
           "type": {
                "type": "string"
            },
            "properties": {
                "type": "object",
                "properties": {
                    "webUrl": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string"
                            }
                        }
                    },
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string"
                            },
                            "properties": {
                                "type": "object",
                                "properties": {
                                    "siteName": {
                                        "type": "object",
                                        "properties": {
                                            "type": {
                                                "type": "string"
                                            }
                                        }
                                    },
                                    "product": {
                                        "type": "object",
                                        "properties": {
                                            "type": {
                                                "type": "string"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "webDescription": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string"
                                }
                            }
                        },
                        "creatorName": {
                            "type": "object",
                            "properties": {
                                "type": {
                                    "type": "string"
                                }
                            }
                        },
                        "creatorEmail": {
                            "type": "object",
                            "properties": {
                                "type": {
                                    "type": "array",
                                    "items": {
                                        "type": "string"
                                    }
                                }
                            }
                        },
                        "createdTimeUTC": {
                            "type": "object",
                            "properties": {
                                "type": {
                                    "type": "string"
                                }
                            }
                        }
                    }
                }
            }
        }

        6. Add any additional actions, such as sending an email, creating a list or library, or creating a log.

        7. Save the flow to automatically generate the HTTP POST URL. Copy this URL for use later.
         

2. Write a Site Script:

      A site script defines the actions SharePoint will execute when the template is applied.

      Steps to create the script:

            1. Open a text editor (e.g. Notepad++ or Visual Studio Code).

            2. Copy and customize the following JSON structure.

       $JSONScript = @"
                   {
                          "$schema": "schema.json",
                           "actions": [
                              {
                                  "verb": "applyTheme",
                                  "themeName": "Custom Theme"
                               },
                              {
                                  "verb": "setRegionalSettings",
                                  "timeZone": 24,
                                  "sortOrder": 25,
                                  "hourFormat": "12"
                              },
                             {
                                  "verb": "setSiteLogo",
                                  "url": "/Style Library/logo.jpg"
                              },
                             {
                                  "verb": "createSPList",
                                  "listName": "Work",
                                  "templateType": 101,
                                  "subactions": [
                                        {
                                              "verb": "setTitle",
                                              "title": "Work"
                                        }
                                    ]
                              },
                             {
                                  "verb": "triggerFlow",
                                  "url": "PASTE_YOUR_FLOW_URL_HERE",
                                  "name": "PowerShell through calling Flow",
                                  "parameters": {
                                          "siteName": "Demo site",
                                          "product": "SharePoint Online"
                                   }
                             }
                         ],
                    "bindata": {},
                   "version": 1
                  }
                "@

            3. Replace PAST_YOUR_FLOW_URL_HERE with the URL copied from your Power Automate flow.      


3. Create a Site Template using PowerShell:

    PowerShell allows you to upload and apply the site script to create a template.

    Steps to run the script:

        1. Open PowerShell as an administrator.

        2. Connect to SharePoint Online.

        Connect-SPOService –Url https://your-tenant-name-admin.sharepoint.com

        3. Add the site script

        $JSONScript = Get-Content -Raw -Path “PathTo\SiteScript.json”

        $SiteScript = $JSONScript | Add-SPOSiteScript -Title “Demo Site Script”

        4. Create the site design.

        Add-SPOSiteDesign -Title “Site Template1” -WebTemplate 68 -SiteScripts $SiteScript.ID -Description “Site Template1”

        5. Web Template: User 68 for Communication Sites, 64 for Team Sites, or 1 for Team Site without
             Group
.
        

        6. Disconnect from SharePoint Online   

                    Disconnect-SPOService

4. Create a New Site:

        Use the SharePoint Admin Center to create a new site with the custom template.

        Steps to create the site:

            1. Navigation to "https://your-tenant-name-admin.sharepoint.com"

            2. Select Active Sites > Create.
              

            3. Choose the site type (e.g. Communication site).
              

            4. Under Template, select Your Organization > Your custom template and click on  "Use Template".
               

               

            5. Enter the required site details.
                    a. Site Name: Provide a site name (e.g. "Demo Communication Site").
                    b. Site Description: Add a brief description.
                    c. Site Owner: Specify the owner.
               

            6. Click Create Site and wait for provisioning to complete.


5. Test the Automation:

        1. Open the newly created site.

        2. Verify the following:

                a. The applied theme and regional settings.
                b. The uploaded site logo.
                c. The created SharePoint list.
                d. The triggered Power Automate workflow.          


6. Manage Templates:

    To remove an existing template:

        1. Reconnect to SharePoint Online in PowerShell.                
        Connect-SPOService -Url https://your-tenant-name-admin.sharepoint.com

        2. Get the list of site designs.              
        Get-SPOSiteDesign
        

        3. Delete the template by ID.     
        Remove-SPOSiteDesign -Identity “TemplateID
                  


Additional Tips for Beginners:

      1. Test Before Deployment: Always test in a development environment.

      2. Error Handling: Enable logging in Power Automate for debugging issues.

      3. Template Naming: Use meaningful full names for scripts and templates to avoid confusion.

      4. Keep Scripts Modular: Break down complex actions into smaller scripts for easier management.


Advantages:

    1. Automates complex workflows during site creation.

    2. Centralizes configurations, making maintenance easier.

    3. Enhances productivity by reducing administrative overhead.


Pros and Cons

Pros

    1. Consistent site creation process.

    2. Fully customizable based on organization needs.

    3. Supports integration with other services.


Cons

    1. Initial setup requires scripting expertise.

    2. Debugging errors may require deeper knowledge.

    3. Depends on Power Automate flow reliability.


Additional Tips

    a. Test the JSON Schema and PowerShell Scripts in a development environment before deploying.

    b. Use descriptive names for site templates to avoid confusion.

    c. Regularly review and update site scripts to align with organizational changes.


Conclusion

Automating SharePoint site creation using PowerShell and Power Automate transforms how you manage site provisioning. This approach enhances efficiency, consistency, and scalability, allowing IT administrators o focus on strategic initiatives. By following this guide, you can create Powerful site templates integrated with workflows that meet your organization's needs.

If you have any questions you can reach out our SharePoint Consulting team here.