Using the troposphere to form clouds, how to add "propagate at launch" to tags

I am using the troposphere python module to generate tags in a cloud formation template. The current script generates:

       "Tags": [{"Key":"Name", "Value":"MyTagName"}, 
                {"Key":"Version", "Value":"123456"}]

      

but i need to generate

       "Tags":[{"Key":"Name", "Value":"MyTagName", "PropagateAtLaunch":"true"},
               {"Key":"Version", "Value":"123456", "PropagateAtLaunch":"true"}]

      

Used script part:

    asg = autoscaling.AutoScalingGroup("MyASG")
    asg.Tags = Tags(Name = "MyTagName", Version = "123456")
    t.add_resource(asg)

      

+4


source to share


2 answers


---- UPDATE ---

This feature was added to the master branch, I just leave my previous answer for reference and in case you don't have access to the latest troposphere version (i.e. if you don't clone the repository). You can still use the short function in your code (3rd option), however it will work.

The "Tags" help class (from the troposphere module) cannot generate ASG (key / value / propagate) tag lists, only basic tag lists (key / value - for EC2, for example). Instead, you can use the troposphere.autoscaling.Tags class , which mimics the latter, with the addition of a "distribute" property.

You can use it like this:

    asg.Tags = autoscaling.Tags(Name = 'MyTagName', Version = '123456')

      

All of your tags will have a PropagateAtLaunch property set to 'true'. If you want a different PropagateAtLaunch property, just write like this:

    asg.Tags = autoscaling.Tags(Name = 'MyTagName', Version = '123456', 
      NonPropagatedTag=('fail',False))

      

The NonPropagatedTag will not propagate (unexpectedly!) And is set to "fail".




Previous answer:

You cannot use the Tags helper class (from the troposphere module) to create ASG (key / value / propagation) tag lists, only basic tag lists (key / value). A quick look at the source code will show you why ( https://github.com/cloudtools/troposphere/blob/master/troposphere/ the init .py )

This gives you three options:

  • the long and hard way: the ASG (in the troposphere) tag list is just a python dicts list with three keys: Name, Value and PropagateAtLaunch. So your code will look like this:

    asg.Tags= [{'Key':'Name','Value':'MyTagName','PropagateAtLaunch':'true'}, 
      {'Key':'Version','Value':'123456','PropagateAtLaunch':'true'}]
    
          

    yes, ugly.

  • a little shorter: instead of dicts, you can use the autoscaling.Tag helper class, which takes 3 parameters: tag-key, tag value, spreads. You will need to enter the code:

    asg.Tags= [autoscaling.Tag('Name','MyTagName','true'),
      autoscaling.Tag('Version','123456','true')]
    
          

    if you have few tags or just use it in one place, that's ok. But the tag helper class is so good ...

  • use another helper class to create a custom ASG tag list. I just made a pull request to the troposphere github repository for this little addition:

    class TagsASG(troposphere.AWSHelperFn):
        defaultPropagateAtLaunch=True
        manyType=[type([]), type(())]
    
        def __init__(self, **kwargs):
            self.tags = []
            for k, v in sorted(kwargs.iteritems()):
                if type(v) in self.manyType:
                  propagate=str(v[1]).lower()
                  v=v[0]
                else:
                  propagate=str(self.defaultPropagateAtLaunch).lower()
                self.tags.append({
                    'Key': k,
                    'Value': v,
                    'PropagateAtLaunch':propagate,
                })
    
        def JSONrepr(self):
            return self.tags
    
          

Now you can use it like this:

    asg.Tags = TagsASG(Name = 'MyTagName', Version = '123456')

      

All of your tags will have a PropagateAtLaunch property set to 'true'. If you want a different PropagateAtLaunch property, just write like this:

    asg.Tags = TagsASG(Name = 'MyTagName', Version = '123456', 
      NonPropagatedTag=('fail',False))

      

The NonPropagatedTag will not propagate (unexpectedly!) And is set to "fail".

+1


source


I have developed a project just for this. https://github.com/MacHu-GWU/troposphere_mate-project#batch-tagging

The idea is to recursively iterate over the resource object and try to find if there are properties Tags

. And tries to apply a tag key-value pair to it .

Let's say you have a VPC, subnet and security group :

from troposphere_mate import Template, ec2, Tags,
from functools import partial

tpl = Template()

my_vpc = ec2.VPC(
    "MyVPC",
    template=tpl,
    CidrBlock="10.0.0.0/16",
    Tags=Tags(
        Creator="Alice"
    )
)
my_sg = ec2.SecurityGroup(
    "MySG",
    template=tpl,
    GroupDescription="My",
    GroupName="MySG",
    VpcId=Ref(my_vpc),
)
my_subnet = ec2.Subnet(
    "MySubnet",
    template=tpl,
    CidrBlock="10.0.1.0/24",
    VpcId=Ref(my_vpc),
)

      

Then define some common tags like project name and milestone. And you can add your own logic to dynamically create tags based on the resource type and just call the method Template.update_tags()

. Of course, you can overwrite an existing hardcoded tag or not.



# custom logic to create tag if it is a SecurityGroup
def get_name(resource, project):
    if resource.resource_type == "AWS::EC2::SecurityGroup":
        return "{}/sg/{}".format(project, resource.GroupName)

common_tags = dict(
    Project="my-project",
    Name=functools.partial(get_name, project="my-project"),
    Creator="Bob",
)

# apply common tags to all aws resource
tpl.update_tags(common_tags, overwrite=False)

      

See, it works.

assert tags_list_to_dct(tpl.to_dict()["Resources"]["MyVPC"]["Properties"]["Tags"]) == dict(
    Project="my-project",
    Creator="Alice",
)
assert tags_list_to_dct(tpl.to_dict()["Resources"]["MySG"]["Properties"]["Tags"]) == dict(
    Project="my-project",
    Name="my-project/sg/MySG",
    Creator="Bob",
)

      

If you like the project, I'm glad you can check it out :) https://github.com/MacHu-GWU/troposphere_mate-project#batch-tagging

0


source







All Articles