A Tag is an user defined metadata or label to an AWS resource to identify and manage it efficiently. Tag consists of a Key and an optional Value. It helps us to identify resources in Cloud environment quickly. For Example, a tag for “Environment” will help us to identify all resources in a particular environment. Different automation jobs can be run based on tag values. We can use it to get billing details segregated by tag (Use Cost Allocation Tag). Refer my Amazon Resource Billing Blog to get more details on how to use it.
In today’s post I will provide a small script block to tag Amazon Elastic Load Balancer (ELB) instances. For this example, we will use Environment tag and will try to use a naming pattern to identify the tag value for Environment.
Let’s assume all my ELB instances have shorthand environment name embedded in the name. Example, “my-dev-elb001” has “dev” and that means it is a Development instance. similarly, “my-qa-elb-001” or “my-prod-elb001” suggest those are QA and Production instance respectively.
Note that above assumption is not always full-proof and there are chances of miss-tagging due to the logic I am following. This is just an example to give you some idea. We can also use a source file, like a CSV File or database table to get information and automate the tagging using Powershell.
To run this script you need to install AWS Tools for Powershell and configure AWS credentials. I am assuming you have already set up your system. If you still have any issue, refer following documents by Amazon :
- https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html
- https://aws.amazon.com/powershell/
I will run a for loop to run through each ELB instance in the account and identify the name of the ELB instance through it’s name. If the ELB name does not have any of the matching patterns, we will set Environment tag as “NA”.
Get-ELBLoadBalancer | ForEach-Object{
$elbName = ""
$Tags = @()
$elbName = $_.LoadBalancerName.ToLower()
$envTag = New-Object Amazon.EC2.Model.Tag
$envTag.Key = "Environment"
if($elbName.Contains("dev") -or $elbName.Contains("dv")){
$envTag.Value = "Development"
}
elseif($elbName.Contains("qa")){
$envTag.Value = "QA"
}
elseif($elbName.Contains("prod") -or $elbName.Contains("prd")){
$envTag.Value = "Production"
}
else{
$envTag.Value = "NA"
}
$Tags += $envTag
Add-ELBResourceTag -LoadBalancerName $elbName -Tag $Tags
}
That’s it! Once you run this script , it will set Environment tag to all ELB instances in your account. However, as I mentioned above, this automation is not full-proof.You can also use a reference file or any other source and match with it while setting the tag value.
Hope this post will help you in your tagging process!