def create_conditions(self): self.template.add_condition( "UseSSL", Not(Equals(Ref("ControllerELBCertName"), ""))) self.template.add_condition("UseDNS", Not(Equals(Ref("ExternalDomain"), ""))) self.template.add_condition("EnableStreamingLogs", Equals(Ref("DisableStreamingLogs"), ""))
def condition_bucket_name_provided(self) -> str: """Condition BucketNameProvided.""" return self.template.add_condition( "BucketNameProvided", And( Not(Equals(self.variables["BucketName"].ref, "undefined")), Not(Equals(self.variables["BucketName"].ref, "")), ), )
def add_conditions(self): """ Create Conditions """ template = self.template variables = self.get_variables() template.add_condition('UseCidrIp', Not(Equals(variables['CidrIp'].ref, ''))) template.add_condition( 'UseSourceSecurityGroupId', Not(Equals(variables['SourceSecurityGroupId'].ref, '')))
def add_conditions(self): """Add conditions to template.""" template = self.template variables = self.get_variables() template.add_condition('CidrDefined', Not(Equals(variables['FromCidr'].ref, ''))) template.add_condition('SrcSgDefined', Not(Equals(variables['FromSgId'].ref, '')))
def add_conditions(self): """Set up template conditions.""" template = self.template variables = self.get_variables() for i in ['ChefBucketName', 'ChefDataBucketName']: template.add_condition( "%sOmitted" % i, Or(Equals(variables[i].ref, ''), Equals(variables[i].ref, 'undefined')))
def create_conditions(self): self.template.add_condition("HasInternalDomain", Not(Equals(Ref("InternalDomain"), ""))) self.template.add_condition("HasExternalDomain", Not(Equals(Ref("BaseDomain"), ""))) self.template.add_condition( "HasHostedZones", Or(Condition("HasInternalDomain"), Condition("HasExternalDomain"))) self.template.add_condition("NoHostedZones", Not(Condition("HasHostedZones")))
def create_conditions(self): self.template.add_condition("HasInternalZone", Not(Equals(Ref("InternalZoneId"), ""))) self.template.add_condition("HasInternalZoneName", Not(Equals(Ref("InternalZoneName"), ""))) self.template.add_condition("HasInternalHostname", Not(Equals(Ref("InternalHostname"), ""))) self.template.add_condition( "CreateInternalHostname", And(Condition("HasInternalZone"), Condition("HasInternalZoneName"), Condition("HasInternalHostname")))
def create_conditions(self): self.template.add_condition("CreateELB", Not(Equals(Ref("ELBHostName"), ""))) self.template.add_condition("SetupDNS", Not(Equals(Ref("BaseDomain"), ""))) self.template.add_condition("UseSSL", Not(Equals(Ref("ELBCertName"), ""))) self.template.add_condition( "CreateSSLELB", And(Condition("CreateELB"), Condition("UseSSL"))) self.template.add_condition( "SetupELBDNS", And(Condition("CreateELB"), Condition("SetupDNS")))
def create_policy(self): ns = self.context.namespace name_prefix = "%s-%s" % (ns, self.name) t = self.template t.add_condition( 'ExternalRoles', Not(Equals(Join(",", Ref('RoleNames')), '')), ) t.add_condition( 'ExternalGroups', Not(Equals(Join(",", Ref('GroupNames')), '')), ) t.add_condition( 'ExternalUsers', Not(Equals(Join(",", Ref('UserNames')), '')), ) t.add_condition( 'CreatePolicy', Or( TropoCondition("ExternalRoles"), TropoCondition("ExternalGroups"), TropoCondition("ExternalUsers"), )) t.add_resource( iam.PolicyType( FIREHOSE_WRITE_POLICY, PolicyName='{}-firehose'.format(name_prefix), PolicyDocument=firehose_write_policy(), Roles=If("ExternalRoles", Ref("RoleNames"), Ref("AWS::NoValue")), Groups=If("ExternalGroups", Ref("GroupNames"), Ref("AWS::NoValue")), Users=If("ExternalUsers", Ref("UserNames"), Ref("AWS::NoValue")), Condition='CreatePolicy', ), ) t.add_resource( iam.PolicyType( LOGS_POLICY, PolicyName='{}-logs'.format(name_prefix), PolicyDocument=logs_policy(), Roles=If("ExternalRoles", Ref("RoleNames"), Ref("AWS::NoValue")), Groups=If("ExternalGroups", Ref("GroupNames"), Ref("AWS::NoValue")), Users=If("ExternalUsers", Ref("UserNames"), Ref("AWS::NoValue")), Condition='CreatePolicy', ), )
def create_conditions(self): self.template.add_condition("HasInternalDomain", Not(Equals(Ref("InternalDomain"), ""))) self.template.add_condition("HasExternalDomain", Not(Equals(Ref("BaseDomain"), ""))) self.template.add_condition( "HasHostedZones", Or(Condition("HasInternalDomain"), Condition("HasExternalDomain"))) self.template.add_condition("NoHostedZones", Not(Condition("HasHostedZones"))) self.template.add_condition("UseNatGateway", Equals(Ref("UseNatGateway"), "true")) self.template.add_condition("UseNatInstances", Not(Condition("UseNatGateway")))
def create_conditions(self): t = self.template ssl_condition = Not(Equals(Ref("ELBCertName"), "")) t.add_condition("UseHTTPS", ssl_condition) t.add_condition("UseHTTP", Not(ssl_condition)) self.template.add_condition( "UseIAMCert", Not(Equals(Ref("ELBCertType"), "acm"))) t.add_condition( "EnableSNSEvents", Equals(Ref("EventsBackend"), "sns")) t.add_condition( "CreateSNSTopic", And(Equals(Ref("EventsSNSTopicName"), ""), Condition("EnableSNSEvents"))) t.add_condition( "EnableCloudwatchLogs", Equals(Ref("RunLogsBackend"), "cloudwatch")) t.add_condition( "CreateRunLogsGroup", And(Equals(Ref("RunLogsCloudwatchGroup"), ""), Condition("EnableCloudwatchLogs"))) t.add_condition( "EnableAppEventStream", Equals(Ref("LogsStreamer"), "kinesis")) t.add_condition( "RequireCommitMessages", Equals(Ref("RequireCommitMessages"), "true"))
def add_conditions(self): """Add conditions to template.""" template = self.template variables = self.get_variables() template.add_condition('KmsKeyEnabled', Not(Equals(variables['KmsKey'].ref, ''))) template.add_condition( 'CustomParameterGroup', Not(Equals(variables['ParameterGroupName'].ref, ''))) template.add_condition( 'VpnAccessEnabled', Not(Equals(variables['VPNSecurityGroup'].ref, ''))) template.add_condition( 'SnsTopicSpecified', Not(Equals(Join('', variables['SNSTopic'].ref), ''))) template.add_condition( 'IdentifierSpecified', Not( Or(Equals(variables['RdsInstanceIdentifier'].ref, 'undefined'), Equals(variables['RdsInstanceIdentifier'].ref, '')))) template.add_condition( 'SnapshotSpecified', Not( Or(Equals(variables['RdsSnapshotIdentifier'].ref, 'undefined'), Equals(variables['RdsSnapshotIdentifier'].ref, ''))))
def add_conditions(self): """Set up AZ conditions.""" template = self.template for i in range(AZS): template.add_condition( 'PublicAZ%i' % (i + 1), Not(Equals(Ref('PublicSubnet%i' % (i + 1)), ''))) template.add_condition( 'PrivateAZ%i' % (i + 1), Not(Equals(Ref('PrivateSubnet%i' % (i + 1)), ''))) template.add_condition( 'CreateNATGateway%i' % (i + 1), And(Condition('PublicAZ%i' % (i + 1)), Condition('PrivateAZ%i' % (i + 1))))
def create_conditions(self): t = self.template t.add_condition("DefinedNotificationArn", Not(Equals(Ref("NotificationTopicArn"), ""))) t.add_condition("DefinedPort", Not(Equals(Ref("Port"), "0"))) t.add_condition( "DefinedAvailabilityZones", Not(Equals(Join(",", Ref("PreferredCacheClusterAZs")), ""))) t.add_condition("DefinedSnapshotArns", Not(Equals(Join(",", Ref("SnapshotArns")), ""))) t.add_condition("DefinedSnapshotWindow", Not(Equals(Ref("SnapshotWindow"), ""))) # DNS Conditions t.add_condition("HasInternalZone", Not(Equals(Ref("InternalZoneId"), ""))) t.add_condition("HasInternalZoneName", Not(Equals(Ref("InternalZoneName"), ""))) t.add_condition("HasInternalHostname", Not(Equals(Ref("InternalHostname"), ""))) t.add_condition( "CreateInternalHostname", And(Condition("HasInternalZone"), Condition("HasInternalZoneName"), Condition("HasInternalHostname")))
def build_tags_list(t): has_conditions = [] tags_list = [] for x in range(1, 11): name = t.add_parameter( Parameter( "Tag%sName" % x, Type="String", Default="-NONE-", )) value = t.add_parameter( Parameter( "Tag%sValue" % x, Type="String", Default="-NONE-", )) t.add_condition( "HasTag%s" % x, Not( Or( Equals(Ref(name), "-NONE-"), Equals(Ref(value), "-NONE-"), ), ), ) has_conditions.append({"Fn::Condition": "HasTag%s" % x}) tags_list.append( If( "HasTag%s" % x, { "Key": Ref(name), "Value": Ref(value), }, NoValue, ), ) t.add_condition( "HasTags", Or(*has_conditions), ) return If( "HasTags", TagsList(*tags_list), NoValue, )
def create_conditions(): condition_counter = 4 base_condition = Equals(Ref(NumSRRHostsParam), 4) t.add_condition(CONDITION_COUNTER_PREFIX + str(condition_counter), base_condition) last_condition = CONDITION_COUNTER_PREFIX + str(condition_counter) for i in range(condition_counter + 1, MAX_INSTANCES + 1): t.add_condition( CONDITION_COUNTER_PREFIX + str(i), Or(Equals(Ref(NumSRRHostsParam), i), Condition(last_condition))) last_condition = CONDITION_COUNTER_PREFIX + str(i) t.add_condition("GovCloudCondition", Equals(Ref("AWS::Region"), "us-gov-west-1"))
def template(**kwargs): """ Args: Returns: template Template() """ template = Template() release = template.add_parameter( Parameter('ReleaseNewAlias', Type="String", AllowedValues=['Yes', 'No'], Default='No')) release_condition = template.add_condition( 'ReleaseAlias', {'ReleaseAlias': Equals(Ref(release), 'Yes')}) function = template.add_resource(lambda_function(**kwargs)) version = template.add_resource( Version('LambdaVersion', FunctionName=GetAtt(function, 'Arn'))) alias = template.add_resource( Alias('LambdaAlias', Name='prod', DependsOn=[release_condition], Description=Sub(f'Alias to version ${{{version.title}.Arn}}'), FunctionName=Ref(function), FunctionVersion=Ref(version))) template.add_output(object_outputs(function, True)) template.add_output(object_outputs(version, True)) return template
def emit_configuration(): create_bucket = template.add_parameter( Parameter( "CreateDeployerBucket", Type="String", Description="Wheter or not to create the deployer bucket", Default='no', AllowedValues=['yes', 'no'] ) ) condition_name = "DeployerBucketCondition" conditions = { condition_name: Equals( Ref(create_bucket), "yes" ) } for c in conditions: template.add_condition(c, conditions[c]), bucket_name = Join('.', ['deployer', CLOUDNAME, Ref("AWS::Region"), CLOUDENV, 'leafme']) bucket = template.add_resource( Bucket( "DeployerBucket", BucketName=bucket_name, DeletionPolicy="Retain", Condition=condition_name ) )
def create_conditions(self): t = self.template t.add_condition( 'HasInternalZone', Not(Equals(Ref('InternalZoneId'), ''))) t.add_condition( 'HasInternalZoneName', Not(Equals(Ref('InternalZoneName'), ''))) t.add_condition( 'HasInternalHostname', Not(Equals(Ref('InternalHostname'), ''))) t.add_condition( 'CreateInternalHostname', And(Condition('HasInternalZone'), Condition('HasInternalZoneName'), Condition('HasInternalHostname')))
def create_log_group_template(): template = Template( Description="Child stack to maintain Lambda@Edge log groups") log_group_name = template.add_parameter( Parameter("LogGroupName", Type="String")) log_retention_days = template.add_parameter( Parameter( "LogRetentionDays", Type="Number", Description= "Days to keep Lambda@Edge logs. 0 means indefinite retention.", AllowedValues=[0] + CLOUDWATCH_LOGS_RETENTION_OPTIONS, )) retention_defined = add_condition(template, "RetentionDefined", Not(Equals(Ref(log_retention_days), 0))) template.add_resource( LogGroup( "EdgeLambdaLogGroup", LogGroupName=Ref(log_group_name), RetentionInDays=If(retention_defined, Ref(log_retention_days), NoValue), )) return template
def add_resources(self): """Add resources to template.""" template = self.template variables = self.get_variables() template.add_condition( 'ProtoIsHttps', Equals(variables['ListeningProtocol'].ref, 'HTTPS')) listener = template.add_resource( elasticloadbalancingv2.Listener( 'AlbListener', Certificates=If('ProtoIsHttps', [ elasticloadbalancingv2.Certificate( CertificateArn=variables['AcmCertArn'].ref) ], Ref('AWS::NoValue')), DefaultActions=[ elasticloadbalancingv2.Action( TargetGroupArn=variables['DefaultTargetGroupArn'].ref, Type='forward') ], LoadBalancerArn=variables['AlbArn'].ref, Port=variables['ListeningPort'].ref, Protocol=variables['ListeningProtocol'].ref, SslPolicy=If('ProtoIsHttps', variables['SslPolicy'].ref, Ref('AWS::NoValue')))) template.add_output( Output("{}Arn".format(listener.title), Description="ARN of the Listener", Value=Ref(listener), Export=Export( Sub('${AWS::StackName}-%sArn' % listener.title))))
def create_kms_key(self): t = self.template t.add_condition("EncryptS3Bucket", Not(Equals(Ref("EncryptS3Bucket"), "false"))) key_description = Join( "", ["S3 Bucket kms encryption key for stack ", Ref("AWS::StackName")]) key_use_arns = self.local_parameters["KeyUseArns"] # auto add the created IAM Role key_use_arns.append(GetAtt(IAM_ROLE, "Arn")) key_admin_arns = self.local_parameters["KeyAdminArns"] t.add_resource( kms.Key(KMS_KEY, Description=key_description, Enabled=True, EnableKeyRotation=Ref("EnableKeyRotation"), KeyPolicy=kms_key_policy(key_use_arns, key_admin_arns), Condition="EncryptS3Bucket")) key_arn = Join("", [ "arn:aws:kms:", Ref("AWS::Region"), ":", Ref("AWS::AccountId"), ":key/", Ref(KMS_KEY) ]) t.add_output(Output("KmsKeyArn", Value=key_arn))
def main(argv): # Set up a blank template t = Template() # Add description t.add_description("RDS Database") # Add all defined input parameters to template for p in parameters.values(): t.add_parameter(p) t.add_condition("InstallPostgis", Not(Equals(Ref("ProvisionStackName"), ""))) t.add_resource(gen_postgis_provisioner()) # Create instance and security group add to template t.add_resource(gen_sg()) for resource in gen_rds_db(service_name): t.add_resource(resource) t.add_output( Output("ConnectionString", Description="Connection string for database", Value=Join("", [GetAtt("DB", "Endpoint.Address"), Ref("DB")]))) # Convert template to json template = (t.to_json()) # Print template to console (for debugging) and write to file print(template) write_to_file(template)
def __init__( self, vpc_configuration: VPCConfig, existing_vpc: bool = False, availability_zone: str = None, description="Network build by NetworkTemplateBuilder", ): self.__template = Template() self.__template.set_version("2010-09-09") self.__template.set_description(description) self.__availability_zone = self.__get_availability_zone(availability_zone) self.__vpc_config = vpc_configuration self.__vpc, self.__additional_vpc_cidr_blocks = self.__get_vpc(existing_vpc) self.__vpc_subnets = vpc_configuration.subnets self.__gateway_id = self.__get_gateway_id() self.__create_ig = self.__template.add_condition("CreateInternetGateway", Equals(self.__gateway_id, "")) self.__existing_ig = self.__template.add_condition( # can't negate above condition with Not() "ExistingInternetGateway", Not(Equals(self.__gateway_id, "")) )
def create_dns_records(self, tile_server_lb): self.add_condition('BlueCondition', Equals('Blue', Ref(self.color))) self.add_condition('GreenCondition', Equals('Green', Ref(self.color))) self.add_resource(r53.RecordSetGroup( 'dnsPublicRecordsBlue', Condition='BlueCondition', HostedZoneName=Join('', [Ref(self.public_hosted_zone_name), '.']), RecordSets=[ r53.RecordSet( 'dnsTileServersBlue', AliasTarget=r53.AliasTarget( GetAtt(tile_server_lb, 'CanonicalHostedZoneNameID'), GetAtt(tile_server_lb, 'DNSName'), True ), Name=Join('', ['blue-tiles.', Ref(self.public_hosted_zone_name), '.']), Type='A' ) ] )) self.add_resource(r53.RecordSetGroup( 'dnsPublicRecordsGreen', Condition='GreenCondition', HostedZoneName=Join('', [Ref(self.public_hosted_zone_name), '.']), RecordSets=[ r53.RecordSet( 'dnsTileServersGreen', AliasTarget=r53.AliasTarget( GetAtt(tile_server_lb, 'CanonicalHostedZoneNameID'), GetAtt(tile_server_lb, 'DNSName'), True ), Name=Join('', ['green-tiles.', Ref(self.public_hosted_zone_name), '.']), Type='A' ) ] ))
def create_conditions(self): t = self.template t.add_condition( "HasInternalZone", Not(Equals(Ref("InternalZoneId"), ""))) t.add_condition( "HasInternalZoneName", Not(Equals(Ref("InternalZoneName"), ""))) t.add_condition( "HasInternalHostname", Not(Equals(Ref("InternalHostname"), ""))) t.add_condition( "CreateInternalHostname", And(Condition("HasInternalZone"), Condition("HasInternalZoneName"), Condition("HasInternalHostname"))) t.add_condition( "HasProvisionedIOPS", Not(Equals(Ref("IOPS"), "0"))) t.add_condition( "HasStorageType", Not(Equals(Ref("StorageType"), "default"))) t.add_condition( "HasDBSnapshotIdentifier", Not(Equals(Ref("DBSnapshotIdentifier"), "")))
def add_conditions(self): """Set up template conditions.""" template = self.template variables = self.get_variables() template.add_condition( 'AlarmDescriptionSpecified', Not(Equals(variables['AlarmDescription'].ref, '')) ) template.add_condition( 'AlarmNameSpecified', Not(Equals(variables['AlarmName'].ref, '')) ) template.add_condition( 'MetricDimensionSpecified', Not(Equals(variables['DimensionName'].ref, '')) ) template.add_condition( 'TreatMissingDataSpecified', Not(Equals(variables['TreatMissingData'].ref, '')) )
def add_versioned_lambda( template, deployment_id, function, ): environment = function.properties.setdefault("Environment", Environment(Variables={})) environment.Variables["X__DO_NOT_USE__DEPLOYMENT_ID"] = deployment_id function = template.add_resource(function) (is_odd_deployment, is_even_deployment) = add_double_sided_condition( template, f"{function.title}DeploymentIdParityOdd", Equals(determine_parity(deployment_id), "ODD"), ) version_a = template.add_resource( Version( f"{function.title}VersionA", FunctionName=GetAtt(function, "Arn"), Condition=is_odd_deployment, )) version_b = template.add_resource( Version( f"{function.title}VersionB", FunctionName=GetAtt(function, "Arn"), Condition=is_even_deployment, )) version_number = If( is_odd_deployment, GetAtt(version_a, "Version"), GetAtt(version_b, "Version"), ) alias = template.add_resource( Alias( f"{function.title}Alias", FunctionName=GetAtt(function, "Arn"), FunctionVersion=version_number, Name="latest", )) return function, alias
def create_conditions(self): self.template.add_condition( "UseSSL", Not(Equals(Ref("ControllerELBCertName"), ""))) self.template.add_condition("UseDNS", Not(Equals(Ref("ExternalDomain"), ""))) self.template.add_condition("EnableStreamingLogs", Equals(Ref("DisableStreamingLogs"), "")) self.template.add_condition( "HasGithubWebhooksSecret", Not(Equals(Ref("EmpireGithubWebhooksSecret"), ""))) self.template.add_condition( "HasGithubDeploymentEnvironment", Not(Equals(Ref("EmpireGithubDeploymentsEnvironment"), ""))) self.template.add_condition( "EnableSNSEvents", Not(Equals(Ref("EnableSNSEvents"), "false"))) self.template.add_condition( "UseIAMCert", Not(Equals(Ref("ControllerELBCertType"), "acm")))
def test_stackset(stack: Stack) -> None: """test Cloudformation stack set creation.""" stack.s3_bucket = "cfn_bucket" stack.s3_key = "templates/" stack_set = StackSet( name="stack-set-test", description="this is a test", regions=["eu-west-1"], ous=["test-ou"], ) stack_set.add( Role( name="TestRole", description="TestRole description", trust={"Service": "test"}, ) ) stack_set.add_condition("", Equals(AccountId, "test_account_id")) stack.add(stack_set) assert stack.export()["Resources"] == EXPECTED_TEMPLATE