Anup Singh
Anup Singh

Reputation: 323

AWS CloudFormation add condition in s3bucket using troposphere

Following code is working for EC2 and it is adding the condition statement in the output, but for S3 its not producing the condition statement. I can manually add this statement to make it work, but that has many disadvantages.

from __future__ import print_function
from troposphere import (Template, Parameter, Ref, Condition, Equals)
from troposphere import ec2
from troposphere import s3

parameters = {
    "One": Parameter(
        "One",
         Type="String",
    ),
}

conditions = {
    "OneEqualsFoo": Equals(
        Ref("One"),
        "Foo"
  ),
}

resources = {
    "MyS3bucket": s3.Bucket(
         "MybucketName",
         Condition="OneEqualsFoo",
   ),

   "Ec2Instance": ec2.Instance(
       "Ec2Instance",
       Condition="OneEqualsFoo",
       ImageId="ami-1234556",
       InstanceType="t1.micro",
       KeyName="mykeypair",
       SecurityGroups=["default"],
   )
}

def template():
     t = Template()
 for p in parameters.values():
    t.add_parameter(p)
 for k in conditions:
    t.add_condition(k, conditions[k])
 for r in resources.values():
    t.add_resource(r)
return t
print(template().to_json())

OUT-PUT-RESULT this result is missing condition statement in S3 template section

{
"Conditions": {
    "OneEqualsFoo": {
        "Fn::Equals": [
            {
                "Ref": "One"
            },
            "Foo"
        ]
    }
},
"Parameters": {
    "One": {
        "Type": "String"
    }
},
"Resources": {
    "Ec2Instance": {
        "Condition": "OneEqualsFoo",
        "Properties": {
            "ImageId": "ami-1234556",
            "InstanceType": "t1.micro",
            "KeyName": "mykeypair",
            "SecurityGroups": [
                "default"
            ]
        },
        "Type": "AWS::EC2::Instance"
    },
    "MybucketName": {
        "Type": "AWS::S3::Bucket"
    }
}
}

Upvotes: 1

Views: 2099

Answers (1)

Vor
Vor

Reputation: 35129

I think you need to add Properties before adding Conditions:

So something like this should work:

 "MyS3bucket": s3.Bucket(
         "MybucketName",
         Tags=s3.Tags(),
         Condition="OneEqualsFoo"
   ),

or

    "MyS3bucket": s3.Bucket(
         "MybucketName",
         AccessControl=s3.PublicRead,
         Condition="OneEqualsFoo"
   )

Upvotes: 2

Related Questions