Use macro inside CloudFormation Conditions - amazon-web-services

I've written a macro (called BucketChecker) that takes in an s3 bucket name and checks if it already exists.
The fragment will return true or false accordingly.
I would like to use this macro in a Conditions section as described in this article: https://cloudnineapps.com/blogs/cloud-computing/how-to-create-dynamic-condition-expressions-in-aws-cloudformation-using-macros/.
The idea is to use this as a condition in my template like this:
Conditions:
CreateBucket:
Fn::Equals: ['false', 'Fn::Transform': {
Name: BucketChecker,
Parameters: {
Operation: 'bucketExists',
BucketName: 'my-bucket'
}}]
Resources:
MyBucket:
Type: "AWS::S3::Bucket"
Condition: CreateBucket # -> only create it if doesn't yet exist
Properties:
BucketName: 'my-bucket'
But cfn-linter gives me the error: E8003 Fn::Equals element must be a supported function (Ref, Fn::FindInMap, Fn::Sub, Fn::Join, Fn::Select, Fn::Split)
My main question is: is it even possible to achieve this using CloudFormation? If yes, what's wrong with my template?
The linked article seems to be doing exactly the same, but mine doesn't work.

Based on the comments.
The cfn-linter was incorrectly classifying the Fn::Transform as malformed.
Deploying the stack confirmed that there are no issues with the Fn::Transform.

Related

Terraform / Cloudformation - Pass parameter as YAML

I use Terraform to launch a Cloudformation stack to create Glue Databrew resources that don't exist yet on Terraform.
The thing is that I've a variable in Terraform that corresponds to the list of my data sources and in order to create the databrew resources associated to this data, I loop over my list to create one instance of my Cloudformation template for each data source.
Inside this template, I've a resource that I want to be different per data source. It correspond to the AWS::DataBrew::Ruleset resource.
It looks like this :
DataBrewDataQualityRuleset:
Type: AWS::DataBrew::Ruleset
Properties:
Name: !Ref RuleSetName
Description: Data Quality ruleset
Rules:
- Name: Check columns for missing values
Disabled: false
CheckExpression: AGG(MISSING_VALUES_PERCENTAGE) == :val1
SubstitutionMap:
- ValueReference: ":val1"
Value: '0'
ColumnSelectors:
- Regex: ".*"
- Name: Check two
Disabled: false
CheckExpression: :col IN :list
SubstitutionMap:
- ValueReference: ":col"
Value: "`group`"
- ValueReference: ":list"
Value: "[\"Value1\", \"Value2\"]"
TargetArn: !Sub SomeArn
What I want to do is, extract the Rules part of the component and create one file where I will put all my rules per data sources. In fact having something like below :
DataBrewDataQualityRuleset:
Type: AWS::DataBrew::Ruleset
Properties:
Name: !Ref RuleSetName
Description: Data Quality ruleset
Rules: !Ref Rules
TargetArn: !Sub SomeArn
And in my terraform, my Rules parameter would be my actual set of rules for one particular data source.
I've thought about having one YAML file from which I would loop on terraform but I'm not sure it's doable and if cloudformation would accept YAML as parameter type.
Below you'll also find my terraform component :
resource "aws_cloudformation_stack" "databrew_jobs" {
for_each = var.data_sources
name = "datachecks-${each.value.stack_name}"
parameters = {
Bucket = "test_bucket"
DataSetKey = "raw/${each.value.job_name}"
DataSetName = "dataset-${each.value.stack_name}"
RuleSetName = "ruleset-${each.value.stack_name}"
JobName = "profile-job-${each.value.stack_name}"
DataSourceName = "${each.value.stack_name}"
JobResultKey = "databrew-results/${each.value.job_name}"
RoleArn = iam_role_test.arn
}
template_body = file("${path.module}/databrew-job.yaml")
}
Do you have any idea how could I achieve this ?
Thanks in advance !

Passing CloudFormation parameters to AppSync Resolver

So I have my CloudFormation template defined to include a Parameters section with several parameters including
Parameters:
DefaultLimit:
Type: Number
I also have a GraphQL API defined in which I am using AppSync PIPELINE resolvers to run multiple operations in sequence.
QueryResolver:
Type: AWS::AppSync::Resolver
DependsOn: AppSyncSchema
Properties:
ApiId: !GetAtt [AppSyncAPI, ApiId]
TypeName: Query
FieldName: getData
Kind: PIPELINE
PipelineConfig:
Functions:
- !GetAtt AuthFunction.FunctionId
- !GetAtt ScanDataFunction.FunctionId
RequestMappingTemplate: |
{
# Inject value of DefaultLimit in $context object
}
ResponseMappingTemplate: "$util.toJson($context.result)"
That all works as expected, except for injecting CFN parameter values in mapping templates.
The issue I am having is this -- I would like to pass the value of DefaultLimit to the before RequestMappingTemplate so that the value is available to the ScanDataFunction. The goal is for that value be used as the default limit value when the second function does, say a DynamoDB scan operation, and returns paginated results.
My current approach is to hardcode a default value of 20 for limit in the request mapping template of the ScanDataFunction. I am using a DynamoDB resolver for this operation. Instead, I would like to inject the parameter value because it would give me the flexibility to set different default values for different deployment environments.
Any help with this would be appreciated.
The | character in YAML starts a block and what you enter indented after that is all treated as text.
CloudFormation isn't going to process any of that. The solution I have generally seen is to use the Join intrinsic function. It ends up looking pretty bad can be difficult to maintain so I recommend using it sparingly. Below is a rough possible example:
Parameters:
DefaultLimit:
Type: Number
Resourece:
QueryResolver:
Type: AWS::AppSync::Resolver
DependsOn: AppSyncSchema
Properties:
ApiId: !GetAtt [AppSyncAPI, ApiId]
TypeName: Query
FieldName: getData
Kind: PIPELINE
PipelineConfig:
Functions:
- !GetAtt AuthFunction.FunctionId
- !GetAtt ScanDataFunction.FunctionId
RequestMappingTemplate:
Fn::Join:
- ""
- - "Line 1 of the template\n"
- "Line 2 of the template, DefaultList="
- Ref: DefaultLimit
- "\nLine 3 of the template"
ResponseMappingTemplate: "$util.toJson($context.result)"
Untested code warning

Dynamically attach event names in cloudwatch event rule cloudformation

Here is my cloud formation template which passes event patter to the sub stack which in fact creates the rule depending on the event data.
cloudwatchRule:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: !Sub "${s3Path}/cw-rule.yml"
Parameters:
eventPattern: !Join
- ' '
- - '{"source":["aws.iam"],"detail-type":["AWS API Call via CloudTrail"],"detail":{"eventSource":["iam.amazonaws.com"],"eventName":['
- Fn::Split:
- ','
- !Sub ${ssmParamWhichContainsEventNames}
- ']}}'
ruleState: "ENABLED"
#The value of ssmParamWhichContainsEventNames is of format #"CreateServiceSpecificCredential,DeactivateMFADevice"
When I run this I get the following error
Template error: every Fn::Join object requires two parameters, (1) a string delimiter and (2) a list of strings to be joined or a function that returns a list of strings (such as Fn::GetAZs) to be joined.. Rollback requested by user.
I have tried various techniques to format the order of !Join !Split !Sub
I have also tried using Fn::Join (full function format) but it keeps failing.
eventName in the eventPattern parameter expects the input in following format.
"eventName":["event1","event2","event3","event4"]
My SSM variable has event names in the format "event1,event2,event3..." To make it compatible with eventName and make the cloudwatch rule run, I'll have to transform "event1,event2,event3..." to '"event1","event2","event3"...'
One option is that I convert the SSM to my acceptable format but this is the thing I want to avoid for some reason.
Can anyone help me figure out the way to transform the "CreateServiceSpecificCredential,DeactivateMFADevice" to ' "CreateServiceSpecificCredential","DeactivateMFADevice" ' (each value enclosed within double quotes and whole string enclosed within single quotes
I keep feeling that I'm not correctly writing the intrinsic functions in the above code in the correct order.
In case somebody is still looking for how to make it happen. Here is the cloudformation template piece that split comma separated string and make it into an array of individual elements to be injected into the "eventName" attribute:
cloudwatchRule:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: !Sub "${s3Path}/cw-rule.yml"
Parameters:
eventPattern: !Sub
- |
{"source":["aws.iam"],"detail-type":["AWS API Call via CloudTrail"],"detail":{"eventSource":["iam.amazonaws.com"],"eventName":[
"${eventNames}"
]}}
- eventNames: !Join
- '","'
- !Split
- ','
- !Ref ssmParamWhichContainsEventNames
ruleState: "ENABLED"

AWS CloudFormation & Service Catalog - Can I require tags with user values?

Our problem seems very basic and I would expect common.
We have tags that must always be applied (for billing). However, the tag values are only known at the time the stack is deployed... We don't know what the tag values will be when developing the stack, or when creating the product in the Service Catalog...
We don't want to wait until AFTER the resource is deployed to discover the tag is missing, so as cool as AWS config may be, we don't want to rely on its rules if we don't have to.
So things like Tag Options don't work, because it appears that they expect we know the tag value months prior to some deployment (which isn't the case.)
Is there any way to mandate tags be used for a cloudformation template when it is deployed? Better yet, can we have service catalog query for a tag value when deploying? Tags like "system" or "project", for instance, come and go over time and are not known up-front for many types of cloudformation templates we develop.
Isn't this a common scenario?
I am worried that I am missing something very, very simple and basic which mandates tags be used up-front, but I can't seem to figure out what. Thank you in advance. I really did Google a lot before asking, without finding a satisfying answer.
I don't know anything about service catalog but you can create Conditions and then use it to conditionally create (or even fail) your resource creation. Conditional Resource Creation e.g.
Parameters:
ResourceTag:
Type: String
Default: ''
Conditions:
isTagEmpty:
!Equals [!Ref ResourceTag, '']
Resources:
DBInstance:
Type: AWS::RDS::DBInstance
Condition: isTagEmpty
Properties:
DBInstanceClass: <DB Instance Type>
Here RDS DB instance will only be created if tag is non-empty. But cloudformation will still return success.
Alternatively, you can try & fail the resource creation.
Resources:
DBInstance:
Type: AWS::RDS::DBInstance
Properties:
DBInstanceClass: !If [isTagEmpty, !Ref "AWS::NoValue", <DB instance type>]
I haven't tried this but it should fail as DB instance type will be invalid if tag is null.
Edit: You can also create your stack using the createStack CFN API. Write some code to read & validate the input (e.g. read from service catalog) & call the createStack API. I am doing the same from Lambda (nodejs) reading some input from Parameter Store. Sample code -
module.exports.create = async (event, context, callback) => {
let request = JSON.parse(event.body);
let subnetids = await ssm.getParameter({
Name: '/vpc/public-subnets'
}).promise();
let securitygroups = await ssm.getParameter({
Name: '/vpc/lambda-security-group'
}).promise();
let params = {
StackName: request.customerName, /* required */
Capabilities: [
'CAPABILITY_IAM',
'CAPABILITY_NAMED_IAM',
'CAPABILITY_AUTO_EXPAND',
/* more items */
],
ClientRequestToken: 'qwdfghjk3912',
EnableTerminationProtection: false,
OnFailure: request.onfailure,
Parameters: [
{
ParameterKey: "SubnetIds",
ParameterValue: subnetids.Parameter.Value,
},
{
ParameterKey: 'SecurityGroupIds',
ParameterValue: securitygroups.Parameter.Value,
},
{
ParameterKey: 'OpsPoolArnList',
ParameterValue: request.userPoolList,
},
/* more items */
],
TemplateURL: request.templateUrl,
};
cfn.config.region = request.region;
let result = await cfn.createStack(params).promise();
console.log(result);
}
Another option: add a AWS Custom Resource backed by Lambda. Check for tags in this section & return failure if it doesn't satisfy the constraints. Make all other resource creation depend on this resource (so that they all create if your checks pass). Link also contains example. You will also have to add handling for stack update & deletion (like a default success). I think this is your best bet as of now.

List of CloudFormation CognitoEvents for Cognito Identity Pool creation

The AWS Documentation is not helpful it simply says the property for CognitoEvents is String: String. I found a topic on GitHub suggesting it was Event: Lambda ARN, but with no specifics of what the events could be (I would guess something along the lines of syncTrigger).
Any idea what the events are to populate the CognitoEvents property of the AWS::Cognito::IdentityPool template?
Ended up guessing SyncTrigger and it was correct (capital "S"). Here is an example of the full configuration:
Type: "AWS::Cognito::IdentityPool"
Properties:
IdentityPoolName: YourPoolName
AllowUnauthenticatedIdentities: true | false
DeveloperProviderName: accounts.example.com
SupportedLoginProviders:
graph.facebook.com: xxxx
accounts.google.com: xxxx-xxxx.apps.googleusercontent.com
api.twitter.com: xxxx;xxxx
CognitoEvents:
SyncTrigger: Lambda Function ARN
Hope this helps someone else!