How to create a Lambda Validator for AppConfig?

  • Last Modified: 20 Mar, 2022


Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


Main Article: You must read it first, if you haven’t already


I hope you have already gone through the previous lessons from the above tutorial. So you already have an application setup with AppConfig without any validator.

Step 01: Create a Lambda function with permission to access the appconfig.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:us-east-1:<account-id>:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:<account-id>:log-group:/aws/lambda/test:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "appconfig:*",
            "Resource": "*"
        }
    ]
}

To use Lambda as a Validator you also need to have a permission-based policy added to the Lambda.

aws lambda add-permission –function-name lambda_app_config_validator –action lambda:InvokeFunction –statement-id appconfig –principal appconfig.amazonaws.com –output json –region us-east-1

╭─kdhaliwal at C02ZH1LHLVCH in ~using ‹ruby-3.0.0› 22-03-20 - 17:46:13
╰─○ aws lambda add-permission --function-name lambda_app_config_validator --action lambda:InvokeFunction --statement-id appconfig --principal appconfig.amazonaws.com --output json --region us-east-1
{
    "Statement": "{\"Sid\":\"appconfig\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"appconfig.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-1:570411717331:function:lambda_app_config_validator\"}"
}

Step 02: Choose Any ConfigProfile from your App.

I will choose the CloudNativeFreeForm-AppConfigHosted one, so I can update the JSON Document easily.

Step 03: Open the ConfigProfile and Click on the Actions

We need to Update the Configuration Profile to add a Validator

Step 04: Click on the Add Validator

Step 05: Choose the AWS Lambda as Validator and select the Lambda Function which needs to be used as Validator

Step 06: Now let’s add the code to validate the JSON values we added in the config.

exports.handler = async (event, context) => {
  try {
    console.log('Received event:', JSON.stringify(event, null, 2));
    const data = JSON.parse(Buffer.from(event.content, 'base64').toString('ascii'));
    console.log('Configuration Data: ', data);
Object.keys(data).forEach(function (item) {
      console.log('key: ',item); // key
      console.log('value: ', data[item]); // value
      const dataType = typeof data[item];
      console.log('Data type: ', dataType);
         
      if (item === 'social_logins' && (dataType !== 'object' || data[item]['facebook_css_style'] !== 'dark'))
        throw new TypeError(`Configuration property ${item} configured as type ${dataType}; expecting type string`);
        
    });
  } catch(err) {
    throw err;
  }
};

If you notice, I did put the check to `facebook_css_style` to always fail if it’s not dark. It was intentional for the purpose of this course.

Step 07: Now let’s modify our JSON config and change its value

Step 08: Let’s run the Deployment again


Because Lambda’s validation failed due to the wrong value, which Lambda wasn’t expecting.

Step 09: Let’s correct our Lambda code and Run the Deployment again

exports.handler = async (event, context) => {
  try {
    console.log('Received event:', JSON.stringify(event, null, 2));
    const data = JSON.parse(Buffer.from(event.content, 'base64').toString('ascii'));
    console.log('Configuration Data: ', data);
Object.keys(data).forEach(function (item) {
      console.log('key: ',item); // key
      console.log('value: ', data[item]); // value
      const dataType = typeof data[item];
      console.log('Data type: ', dataType);
         
      if (item === 'social_logins' && dataType !== 'object')
        throw new TypeError(`Configuration property ${item} configured as type ${dataType}; expecting type string`);
        
    });
  } catch(err) {
    throw err;
  }
};
...
Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


See Also

comments powered by Disqus