Public/Add-DuneTag.ps1

<#
.SYNOPSIS
Add or replace a tag on a Dune object.
 
.DESCRIPTION
Adds a tag (name/value pair) to a tenant, deployment, resource group, or resource. If a tag with the same name already exists, it is replaced. The full tag set is sent as a PATCH request to the API.
 
.PARAMETER Name
The tag name.
 
.PARAMETER Value
The tag value.
 
.PARAMETER Tenant
A DuneTenant object to tag. Accepts pipeline input.
 
.PARAMETER Deployment
A DuneDeployment object to tag. Accepts pipeline input.
 
.PARAMETER ResourceGroup
A DuneResourceGroup object to tag. Accepts pipeline input.
 
.PARAMETER Resource
A DuneResource object to tag. Accepts pipeline input.
 
.EXAMPLE
PS> Get-DuneDeployment -Name "app" | Add-DuneTag -Name "Environment" -Value "Production"
Adds an Environment tag to the deployment.
#>

function Add-DuneTag {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [String]$Name,

        [Parameter(Mandatory, Position = 1)]
        [PSCustomObject]$Value,

        [Parameter(ValueFromPipeline, ParameterSetName = "Tenant")]
        [DuneTenant]$Tenant,

        [Parameter(ValueFromPipeline, ParameterSetName = "Deployment")]
        [DuneDeployment]$Deployment,

        [Parameter(ValueFromPipeline, ParameterSetName = "ResourceGroup")]
        [DuneResourceGroup]$ResourceGroup,

        [Parameter(ValueFromPipeline, ParameterSetName = "Resource")]
        [DuneResource]$Resource
    )

    begin {}

    process {
        Write-Debug "$($MyInvocation.MyCommand)|process|$($PSCmdlet.ParameterSetName)"
        switch ($PSCmdlet.ParameterSetName) {
            'Tenant' {
                $Uri = 'tenants/tags' -f $Tenant.Id
                $Tenant = Get-DuneTenant
                $Tags = $Tenant.tags
            }
            'Deployment' {
                $Uri = 'deployments/{0}/tags' -f $Deployment.Id
                $Deployment = Get-DuneDeployment -Id $Deployment.Id
                $Tags = $Deployment.tags
            }
            'ResourceGroup' {
                $Uri = 'resourcegroups/{0}/tags' -f $ResourceGroup.Id
                $ResourceGroup = Get-DuneResourceGroup -Id $ResourceGroup.Id
                $Tags = $ResourceGroup.tags
            }
            'Resource' {
                $Uri = 'resources/{0}/tags' -f $Resource.Id
                $Resource = Get-DuneResource -Id $Resource.Id
                $Tags = $Resource.tags
            }
            Default {
                return 'Type has no tags.'
            }
        }
        $Body = @{tags = @() }
        if ($Tags | Where-Object Name -NE $Name) { $Body.tags += ($Tags | Where-Object Name -NE $Name).ToPropertiesHashtable() }
        $Body.tags += @{name = $Name; value = $Value }
        $Null = Invoke-DuneApiRequest -Uri $Uri -Method PATCH -Body $Body
    }

    end {}
}