Amos Shapira Amos Shapira - 3 years ago 127
Python Question

How to pass a Troposphere object attribute conditionally?

I'm using Troposphere to build CloudFormation stacks and would like to pass the Elastic Load Balancer

attribute only if it's set in my configuration, otherwise I don't want to specify it.

If I set it to default
then I get an error about the value not being of the expected type of

I'd rather try to avoid setting an explicit default in the call because it might override other settings.

Idealy, I would like to be able to add attributes to an existing object, e.g.:

lb = template.add_resource(elb.LoadBalancer(

if condition:
lb.add_attribute(ConnectionSettings = elb.ConnectionSettings(

Is there a way to achieve that?

UPDATE: I achieved it using a hidden
method, which works but I'm not happy with:

if condition:
lb.__setattr__('ConnectionSettings', elb.ConnectionSettings(

I'm still interested in a solution which doesn't involve using a private method from outside the module.

Answer Source

The main README eludes to just using the attribute names like this:

from troposphere import Template
import troposphere.elasticloadbalancing as elb

template = Template()
webelb = elb.LoadBalancer(

if True:
    webelb.ConnectionSettings = elb.ConnectionSettings(IdleTimeout=30)
elasticLB = template.add_resource(webelb)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download