Search code examples
pythonamazon-web-servicestroposphere

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 ConnectionSettings attribute only if it's set in my configuration, otherwise I don't want to specify it.

If I set it to default None then I get an error about the value not being of the expected type of troposphere.elasticloadbalancing.ConnectionSettings.

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 Troposphere 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.


Solution

  • 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(
        'ElasticLoadBalancer',
        Listeners=[
            elb.Listener(
                LoadBalancerPort="80",
                InstancePort="80",
                Protocol="HTTP",
            ),
        ],
    )
    
    if True:
        webelb.ConnectionSettings = elb.ConnectionSettings(IdleTimeout=30)
    elasticLB = template.add_resource(webelb)
    print(template.to_json())