AWS - Add Tags to EC2 Instance

Octopus.Script exported 2018-01-30 by tclydesdale belongs to ‘AWS’ category.

This step will Add or Remove Tags from an EC2 instance.

Works well with the “AWS - Launch EC2 Instance” Community Step Template.

AWS Tools for Windows PowerShell must be installed on the Server/Target you plan on running this step template on.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Instance ID

odInstanceId = i-xxxxxxxxxxxxxxxxx

The EC2 Instance ID of the Instance you would like to add Tags to.

Action

odAction = New

The action you would like to perform - Add or Remove Tags from an EC2 Instance.

Tags

odTags = Name=#{Octopus.Project.Name} Environment=#{Octopus.Environment.Name} Version=#{Octopus.Release.Number}

The Tags you would like to Add or Remove from an EC2 Instance, for example:

  • Name=MyProject
  • Environment=Prod
  • Version=1.3.3.7

Access Key (Kind-of Optional)

odAccessKey =

An Access Key with permissions to create the desired EC2 instance. Note: If empty, this step will attempt to use the value contained in the Machine Environment Variable “AWS_ACCESS_KEY”.

Further Reading: https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html

Secret Key (Kind-of Optional)

odSecretKey =

The Secret Key associated with the above Access Key. Note: If empty, this step will attempt to use the value contained in the Machine Environment Variable “AWS_SECRET_KEY”.

Further Reading: https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html

Script body

Steps based on this template will execute the following PowerShell script.

# Running outside octopus
param(
    [string]$odInstanceId,
    [string]$odAction,
    [string]$odTags,
    [string]$odAccessKey,
    [string]$odSecretKey,
    [switch]$whatIf
) 

$ErrorActionPreference = "Stop" 

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($OctopusParameters -ne $null) {
        $result = $OctopusParameters[$Name]
    }

    if ($result -eq $null) {
        $variable = Get-Variable $Name -EA SilentlyContinue   
        if ($variable -ne $null) {
            $result = $variable.Value
        }
    }

    if (!$result -or $result -eq $null) {
        if ($Default) {
            $result = $Default
        } elseif ($Required) {
            throw "Missing parameter value $Name"
        }
    }

    return $result
}


& {
    param(
        [string]$odInstanceId,
        [string]$odAction,
        [string]$odTags,
        [string]$odAccessKey,
        [string]$odSecretKey
    ) 
    
    # If AWS key's are not provided as params, attempt to retrieve them from Environment Variables
    if ($odAccessKey -or $odSecretKey) {
        Set-AWSCredentials -AccessKey $odAccessKey -SecretKey $odSecretKey -StoreAs default
    } elseif (([Environment]::GetEnvironmentVariable("AWS_ACCESS_KEY", "Machine")) -or ([Environment]::GetEnvironmentVariable("AWS_SECRET_KEY", "Machine"))) {
        Set-AWSCredentials -AccessKey ([Environment]::GetEnvironmentVariable("AWS_ACCESS_KEY", "Machine")) -SecretKey ([Environment]::GetEnvironmentVariable("AWS_SECRET_KEY", "Machine")) -StoreAs default
    } else {
        throw "AWS API credentials were not available/provided."
    }



    Write-Output ("------------------------------")
    Write-Output ("Add/Remove Instance Tags:")
    Write-Output ("------------------------------")
    
    $filterArray = @()
    $tagsHash = (ConvertFrom-StringData $odTags).GetEnumerator()
    Foreach ($tag in $tagsHash) {
        $tagObj = $(Get-EC2Instance -InstanceId $odInstanceId).Instances.Tags | ? {$_.Key -eq $tag.Key -and $_.Value -eq $tag.Value}
        $tagObjCount = ($tagObj | measure).Count
        if ($tagObjCount -gt 0) {
            if ($odAction -eq "New") {
                Write-Output ("Cannot Add: The tag '$($tag.Key)=$($tag.Value)' already exists, skipping...")
            } elseif ($odAction -eq "Remove") {
                Write-Output ("The tag '$($tag.Key)=$($tag.Value)' exists, deleting...")

                try {
                    Remove-EC2Tag -Tags @{key=$tag.Key} -resourceId $odInstanceId -Force
                }
                catch [Amazon.EC2.AmazonEC2Exception] {
                    throw $_.Exception.errorcode + '-' + $_.Exception.Message
                }
            }
        } else {
            if ($odAction -eq "New") {
                Write-Output ("The combination of tag and value '$($tag.Key)=$($tag.Value)' does not exist, Creating/Updating tag...")

                try {
                    New-EC2Tag -Tags @{key=$tag.Key;value=$tag.Value} -resourceId $odInstanceId
                }
                catch [Amazon.EC2.AmazonEC2Exception] {
                    throw $_.Exception.errorcode + '-' + $_.Exception.Message
                }
            } elseif ($odAction -eq "Remove") {
                Write-Output ("Cannot Remove: The tag '$($tag.Key)=$($tag.Value)' does not exist, skipping...")
            }
        }
    }
 } `
 (Get-Param 'odInstanceId' -Required) `
 (Get-Param 'odAction' -Required) `
 (Get-Param 'odTags' -Required) `
 (Get-Param 'odAccessKey') `
 (Get-Param 'odSecretKey')

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "82500bb2-f442-44f3-a5a5-7ecb4165ee1f",
  "Name": "AWS - Add Tags to EC2 Instance",
  "Description": "This step will Add or Remove Tags from an EC2 instance.\n\nWorks well with the \"_AWS - Launch EC2 Instance_\" Community Step Template.\n\n[AWS Tools for Windows PowerShell](http://aws.amazon.com/powershell/) must be installed on the Server/Target you plan on running this step template on.",
  "Version": 1,
  "ExportedAt": "2018-01-30T12:44:07.356Z",
  "ActionType": "Octopus.Script",
  "Author": "tclydesdale",
  "Parameters": [
    {
      "Id": "3670adeb-3e4f-4c55-829b-b39bb709d841",
      "Name": "odInstanceId",
      "Label": "Instance ID",
      "HelpText": "The EC2 Instance ID of the Instance you would like to add Tags to.",
      "DefaultValue": "i-xxxxxxxxxxxxxxxxx",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "918acd83-39ae-47d1-9682-12333e723cff",
      "Name": "odAction",
      "Label": "Action",
      "HelpText": "The action you would like to perform - Add or Remove Tags from an EC2 Instance.",
      "DefaultValue": "New",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "New|Add tag to an instance\nRemove|Remove tag from an instance"
      },
      "Links": {}
    },
    {
      "Id": "9b4d592a-712d-459e-af73-1db757a769d8",
      "Name": "odTags",
      "Label": "Tags",
      "HelpText": "The Tags you would like to Add or Remove from an EC2 Instance, for example:\n\n- Name=MyProject\n- Environment=Prod\n- Version=1.3.3.7",
      "DefaultValue": "Name=#{Octopus.Project.Name}\nEnvironment=#{Octopus.Environment.Name}\nVersion=#{Octopus.Release.Number}",
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      },
      "Links": {}
    },
    {
      "Id": "ccd17285-bbb4-4dcb-84a8-330f45199afd",
      "Name": "odAccessKey",
      "Label": "Access Key (Kind-of Optional)",
      "HelpText": "An Access Key with permissions to create the desired EC2 instance.\nNote: If empty, this step will attempt to use the value contained in the Machine Environment Variable \"AWS\\_ACCESS\\_KEY\".\n\nFurther Reading:\n[https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html](https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "6f058614-92a0-4696-bb56-b6342a8d5466",
      "Name": "odSecretKey",
      "Label": "Secret Key (Kind-of Optional)",
      "HelpText": "The Secret Key associated with the above Access Key.\nNote: If empty, this step will attempt to use the value contained in the Machine Environment Variable \"AWS\\_SECRET\\_KEY\".\n\nFurther Reading:\n[https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html](https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    }
  ],
  "Properties": {
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nparam(\n    [string]$odInstanceId,\n    [string]$odAction,\n    [string]$odTags,\n    [string]$odAccessKey,\n    [string]$odSecretKey,\n    [switch]$whatIf\n) \n\n$ErrorActionPreference = \"Stop\" \n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($OctopusParameters -ne $null) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($result -eq $null) {\n        $variable = Get-Variable $Name -EA SilentlyContinue   \n        if ($variable -ne $null) {\n            $result = $variable.Value\n        }\n    }\n\n    if (!$result -or $result -eq $null) {\n        if ($Default) {\n            $result = $Default\n        } elseif ($Required) {\n            throw \"Missing parameter value $Name\"\n        }\n    }\n\n    return $result\n}\n\n\n& {\n    param(\n        [string]$odInstanceId,\n        [string]$odAction,\n        [string]$odTags,\n        [string]$odAccessKey,\n        [string]$odSecretKey\n    ) \n    \n    # If AWS key's are not provided as params, attempt to retrieve them from Environment Variables\n    if ($odAccessKey -or $odSecretKey) {\n        Set-AWSCredentials -AccessKey $odAccessKey -SecretKey $odSecretKey -StoreAs default\n    } elseif (([Environment]::GetEnvironmentVariable(\"AWS_ACCESS_KEY\", \"Machine\")) -or ([Environment]::GetEnvironmentVariable(\"AWS_SECRET_KEY\", \"Machine\"))) {\n        Set-AWSCredentials -AccessKey ([Environment]::GetEnvironmentVariable(\"AWS_ACCESS_KEY\", \"Machine\")) -SecretKey ([Environment]::GetEnvironmentVariable(\"AWS_SECRET_KEY\", \"Machine\")) -StoreAs default\n    } else {\n        throw \"AWS API credentials were not available/provided.\"\n    }\n\n\n\n    Write-Output (\"------------------------------\")\n    Write-Output (\"Add/Remove Instance Tags:\")\n    Write-Output (\"------------------------------\")\n    \n    $filterArray = @()\n    $tagsHash = (ConvertFrom-StringData $odTags).GetEnumerator()\n    Foreach ($tag in $tagsHash) {\n        $tagObj = $(Get-EC2Instance -InstanceId $odInstanceId).Instances.Tags | ? {$_.Key -eq $tag.Key -and $_.Value -eq $tag.Value}\n        $tagObjCount = ($tagObj | measure).Count\n        if ($tagObjCount -gt 0) {\n            if ($odAction -eq \"New\") {\n                Write-Output (\"Cannot Add: The tag '$($tag.Key)=$($tag.Value)' already exists, skipping...\")\n            } elseif ($odAction -eq \"Remove\") {\n                Write-Output (\"The tag '$($tag.Key)=$($tag.Value)' exists, deleting...\")\n\n                try {\n                    Remove-EC2Tag -Tags @{key=$tag.Key} -resourceId $odInstanceId -Force\n                }\n                catch [Amazon.EC2.AmazonEC2Exception] {\n                    throw $_.Exception.errorcode + '-' + $_.Exception.Message\n                }\n            }\n        } else {\n            if ($odAction -eq \"New\") {\n                Write-Output (\"The combination of tag and value '$($tag.Key)=$($tag.Value)' does not exist, Creating/Updating tag...\")\n\n                try {\n                    New-EC2Tag -Tags @{key=$tag.Key;value=$tag.Value} -resourceId $odInstanceId\n                }\n                catch [Amazon.EC2.AmazonEC2Exception] {\n                    throw $_.Exception.errorcode + '-' + $_.Exception.Message\n                }\n            } elseif ($odAction -eq \"Remove\") {\n                Write-Output (\"Cannot Remove: The tag '$($tag.Key)=$($tag.Value)' does not exist, skipping...\")\n            }\n        }\n    }\n } `\n (Get-Param 'odInstanceId' -Required) `\n (Get-Param 'odAction' -Required) `\n (Get-Param 'odTags' -Required) `\n (Get-Param 'odAccessKey') `\n (Get-Param 'odSecretKey')",
    "Octopus.Action.RunOnServer": "false"
  },
  "Category": "AWS",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/aws-add-tags-to-ec2-instance.json",
  "Website": "/step-templates/82500bb2-f442-44f3-a5a5-7ecb4165ee1f",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////9o0R/eLD/Nu0/erS95Qg+bhr95sv/vHh+r96/vjw+bFc/NSl+KI++82W+saI+KpNeDqM1wAAA41JREFUeNrsnG2XazAURiuo0Cr//9feliIvR3DvXJFZe3+a6XpW5+xWEpyY2w0AAAAAAAAAAAAAAAAAAADgf1J0bda/9N70q83a3enzUHWVjbR1sW0xp6sd6fPI72VmUt3zA+kymD6N5vnIBMrHsxHTjsUXOX0e+iVaTNU5Q0A/Q+k+4oAp+ixMbw6A4rGVVjGHR92ulNXWuTAlBNJN/FFyr5yy3qN9rawmF9IxR4hqX4U1WMplmGtruVBDuiuswbKkzaGhX+cfXsqbZlXXv0dsYR13nw9fLenGXD7f6U5Ony4yTpzyZLNMUcpMr0xNzfwdRRMR1/LP2cqMctNqKx1LZFydm2U022ueEtLL6HbHfmSRYRn4HDXaXyzU4XRkkZWK/+JlRBBBBBFEEEEEEUQQQQQRRBBB5B9uYJc7SyuLw+nI7R2ptKWJcywd18Utza0rnM4iN66M6qzS5E93Lf1zLaviUL/ISs/Nt6W00DEyuRgiP2Yxvrd15z/Y26ncG76jy1Ta5jEy/L0p/VMWy33woVm8UYN1Y9fqKrzfZ5iedtaV34+kNxHak2Wg2SSkY7djx/bQWkNP6nkE0lH3Lyx7D1aak1Z1erWJ+U130Vz0Sude7mZqv995nW7mZxJd27Sg5XQppuMdWY3xl1XXOge8MasWjZfund0KbvrkE9fK7OPNne+2U9YEWX3nemtSbvLv6LJ7gZ9X45yBl9ZxrZ9d3vjT8rz62tOsny7jXkpYPX9jQmvF8yF55TdaslGviZy1vAmfoTobsZztGNEv7qZZSr/6HRc/0yzlb3HiKhURRBBBBBFEEEEEEUQQQQQRRBD5XSLav38tllbVzeH02Ww/UWA+6XgsHdXFKc2vK5Quoz/duVRnlrb26crpizzXOVU3l2Zb5Pfe+d1OX8ViqW7qH9gt51K44bukr2XxrW54vMaoy7mxa/cgvPRVKcQG7uOCD58HLQLt3r17Iy6AqjYeDG7TUenWW+p9Ot/IOF/lwuHV1nk6o8M469PWXhtr+0BeX/x7Ue40W3xacfb2gXFxUZcX8TYB3Kyfp+GThsjKti2zgZuMiLshxW3gpiQyrn/DXhR/i1NqIte5pkUEEUQQQQQRRBBBBBFEEEEEEUR+g4jQUZBEqjqFO9mOiyeShoXvYoukZOG4GCLpWZgu83/vTNRidhlE0rYAAAAAAAAAAAAAAAAAAACAZPkjwAAMDi+bsnPP/wAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Tuesday, January 30, 2018