Somewhat of a prerequisite for automating things in AWS is the ability to add tags to resources. Tags are a key/value pair that you can add to supported resources. They allow you to create an arbitrary piece of data that is attached to a resource, such as an EC2 instance, a security group, or a Lambda function. There's a long list of resources you can tag, so check the AWS documentation for further details.
The reason you would want to add a tag to a resource is that tags are returned when you request information about the resource. For example, the describe-instances operation for EC2 API returns any tags associated with an EC2 instance. You can also filter the query down to display just the tags for a given instance ID:
aws ec2 describe-instances
--instance-id i-123456780
--query "Reservations[*].Instances[*].[Tags[*]]"
A few examples of a tag could be as follows:
- owner: Scott
- cost-center: Technology
- backup: true
You can use this contextual information to drive the logic in your automation. You might want to assign an owner to a machine so you know who is responsible for it, or attribute the usage cost to a particular billing center, or flag that the instance should be added to the standard backup policy.
Tags are easy to add. Here's an example of tagging Lambda functions:
- This is how you tag using the Lambda management console:
- Now for tagging using the AWS CLI.
When creating a new function, you can use the --tags option. You can include multiple tags separated by a comma.
aws lambda create-function
--function-name hello-world
--handler index.py
--runtime python3.6
--role arn:aws:iam::123456789012:role/lambda_basic_execution
--tags "Owner=Scott,Environment=UAT"
Alternatively, you can achieve the same result by adding tags to an existing function using the tag-resource action of the Lambda CLI, as follows:
aws lambda tag-resource
--resource arn:aws:lambda:us-east-1:123456789012:function:hello-world
--tags "Business Unit=Research & Development"
- Adding tags to a CloudFormation template is also possible by specifying the Tags property in a function declaration. See the following for an example:
HelloFunction:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Code:
S3Bucket: "lambda-functions"
S3Key: "function.zip"
Runtime: "java8"
Tags:
- Key: "Owner"
Value: "Scott"
- Key: "DeployedByPipeline"
Value: "serverless-hello-world-pipeline"
- When adding tags to your resources in the Serverless Framework, you can add tags just to the functions that you create:
functions:
hello:
handler: handler.hello
tags:
DeployedBy: Serverless
- Or—and this is extremely useful—you can add tags that attach to every resource that gets created by deploying the CloudFormation stack as part of a serverless deployment. This declaration is made at the provider level:
provider:
name: aws
runtime: nodejs10.x
stackTags:
DeployedBy: Serverless
Okay; let's move on to a reason where we may be able to leverage tags, and then move on to an example.