CFN template: can I add default tags to my stack using a template?

0

Every time I create a specific stack, I enter the same name, manually, each type, as a tag, with 'stackName' as key and a name as value, so every single resource inherit this tag

Is there a way to hardcode a default tag for the stack in the template?

asked 17 days ago90 views
2 Answers
1

Hi realtebo

Yes, you can define default tags for your CloudFormation stack directly within the template using the Tags property at the root level of your CloudFormation template. This way, every resource created as part of the stack will inherit these tags automatically.

Here's an example of how you can define default tags in your CloudFormation template:

AWSTemplateFormatVersion: "2010-09-09"
Description: Your CloudFormation Stack Description
Parameters:
  StackName:
    Type: String
    Description: Name of the stack

Resources:
  MyEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-12345678
      InstanceType: t2.micro
      # Other properties...

# Define default tags for the stack
Tags:
  - Key: stackName
    Value: !Ref "AWS::StackName"
  - Key: environment
    Value: production
  # Add more default tags as needed

In this example, Tags is defined at the root level of the template, and it contains a list of key-value pairs representing the tags you want to apply. The stackName tag is set to the value of the AWS::StackName pseudo parameter, which resolves to the name of the stack. You can add additional default tags as needed.

answered 17 days ago
  • Actually, using this syntax, CFN reject my file

    "Invalid template property or properties [Tags]"

0

Are you saying that now, when you create a stack, you tag it with the stack option, but you want to do it in a template?

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-add-tags.html

I think you can get the stack's name with AWS::StackName to set the tags. (I haven't tested it) This is tedious because you have to set it for each resource.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html

Or you can assign Tags when using AWS::CloudFormation::Stack to nest stacks. This one should be assigned to all resources in a single definition, just like the stack options.(I haven't tested it)

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-stack.html

profile picture
EXPERT
shibata
answered 17 days ago
  • I don't want to read the stack name, but to set the default

  • Unfortunately, I am only familiar with the above three methods.

    If you prefer Terraform, it has the features you are looking for.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions