Deploy Flagsmith on AWS using CloudFormation

Deploy Flagsmith on AWS using CloudFormation

In this post, we'll deploy Flagsmith on AWS using CloudFormation. Flagsmith is an open-source feature flag and remote configuration service. It allows you to manage feature flags and remote configuration for your applications.

What are feature flags?

Feature flags, also known as feature toggles, are a software development practice that allows teams to modify system behavior without changing code. They act as switches that can turn features on or off in a live environment, providing a high level of control over a software's functionality.

Imagine a light switch in your home; you can easily turn the lights on or off without rewiring the electrical system. Similarly, feature flags enable developers to toggle features for users without deploying new code. This approach is especially useful for testing new features, performing A/B testing, or enabling a gradual rollout to users.

At their core, feature flags are implemented through conditional statements in the code that check the status of a flag. If the flag is active, the new feature is presented to the user; if not, the system defaults to the existing functionality. The status of these flags is typically controlled through a feature management system that can be updated in real-time.

Example use cases for feature flags include:

  • Testing in Production: Feature flags allow developers to test new features in the production environment with a subset of users. This is known as canary releasing. By exposing the feature to a small group, you can gather valuable feedback and ensure stability before a wider release.
  • Gradual Rollouts: Instead of launching a feature to all users at once, feature flags enable a gradual rollout. This helps in monitoring the feature's impact on system performance and user experience, and quickly rolling it back if issues arise.
  • User Segmentation: Feature flags can be used to enable features for specific user segments. For example, you might roll out a new feature only to premium users or to users in a particular geographic location.
  • A/B Testing: By employing feature flags, teams can perform A/B testing to compare different user experiences and determine which version performs better in terms of user engagement, conversion rates, and other metrics.
  • Emergency Kill Switch: If a newly released feature causes unexpected issues, feature flags serve as an emergency kill switch. Developers can quickly disable the problematic feature, mitigating any negative impact on the user experience.

Architecture

We'll deploy Flagsmith on AWS using a CloudFormation. The architecture consists of the following components:

  • Amazon Certificate Manager: We'll use ACM to provision SSL/TLS certificates for securing the application's traffic.
  • Amazon Route 53: We'll use Route 53 to manage the DNS records for the application's domain name.
  • Amazon RDS (Relational Database Service): We'll use RDS to host the PostgreSQL database for storing feature flags and configuration data. We are using RDS PostgreSQL Cluster with Multi-AZ deployment for high availability and fault tolerance, deployed in private subnets.
  • Amazon Application Load Balancer: We'll use an ALB to route incoming traffic to the ECS service. The ALB will be configured with a listener for HTTPS traffic, deployed in a public subnet.
  • Flagsmith API: The Flagsmith API is a RESTful service that provides endpoints for managing feature flags and configurations. This service is deployed as a Docker container on ECS in a private subnet.
  • Flagsmith Processor: The Flagsmith Processor is a background worker that processes feature flag evaluations and updates the database. This service is also deployed as a Docker container on ECS in a private subnet, subscribing to events from the RDS database.
  • Auto-scaling: Both the API and Processor services are deployed as ECS tasks behind an Application Load Balancer. The ECS service is configured to auto-scale based on CPU utilization.



Now, let's deploy Flagsmith on AWS using CloudFormation.


Prerequisites

Before we begin, make sure you have the following prerequisites:

  • An AWS account with the necessary permissions to create resources using CloudFormation.
  • The AWS CLI is installed and configured with your AWS account credentials.

Deployment Steps

Elastic Container Registry (ECR)

We must begin by creating an ECR repository for the Flagsmith Docker image. We need to do this in order to avoid throttling issues when pulling the image from Docker Hub.

Type the following command in your terminal to create the ECR repository:

aws ecr create-repository --repository-name flagsmith        

Note: The following build command must be run on an X86 system. If you are using an M1 Mac, you can use a virtual machine to run the command.


Let's pull the flagsmith image from Docker Hub:

docker pull flagsmith/flagsmith:latest        

Tag the image with the ECR repository URI:

docker push {account-id}.dkr.ecr.us-east-1.amazonaws.com/flagsmith:latest        

Login to ECR:

aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin {account-id}.dkr.ecr.us-east-1.amazonaws.com        

And finally, push the image to ECR:

docker push {account-id}.dkr.ecr.us-east-1.amazonaws.com/flagsmith:latest        

Great! We have successfully mirrored the flagsmith image on ECR. Now, let's deploy the CloudFormation template.


CloudFormation

Create a new file named stack-params.json with the following content:

[
    {
        "ParameterKey": "AllowedHosts",
        "ParameterValue": "*"
    },
    {
        "ParameterKey": "DatabasePassword",
        "ParameterValue": "{password}"
    },
    {
        "ParameterKey": "DatabasePort",
        "ParameterValue": "5432"
    },
    {
        "ParameterKey": "FlagsmithImage",
        "ParameterValue": "{account-id}.dkr.ecr.us-east-1.amazonaws.com/flagsmith:latest"
    },
    {
        "ParameterKey": "FlagsmithServiceSize",
        "ParameterValue": "1"
    },
    {
        "ParameterKey": "ServiceName",
        "ParameterValue": "flagsmith"
    },
    {
        "ParameterKey": "StageName",
        "ParameterValue": "prod"
    },
    {
        "ParameterKey": "ApexDomain",
        "ParameterValue": "{domain.tld}"
    },
    {
        "ParameterKey": "SendgridApiKey",
        "ParameterValue": "{api-key}"
    }
]        

Replace the placeholders with the appropriate values:

  • {password}: A strong password for the RDS database.
  • {account-id}: Your AWS account ID.
  • {domain.tld}: Your domain name.
  • {api-key}: Your SendGrid API key.


The CloudFormation template

Create a new file named cloudformation.yml with the following content:

https://gist.github.com/r0yfire/2f404d3159ae9c1cab62e8602794a9a9

This CloudFormation template creates the necessary resources for deploying Flagsmith on AWS, including the RDS database, ECS services, ALB, Route 53 records, etc.

Warning: This template uses the autohost CloudFormation stack outputs that define the VPC, subnets, and security groups. You must replace these references with your own VPC and subnet IDs. You can use tools such as ChatGPT to replace imported values with your VPC and subnet IDs or create the missing resources.


Now, deploy the CloudFormation stack using the following command:

aws cloudformation create-stack \
    --stack-name flagsmith \
    --capabilities CAPABILITY_NAMED_IAM \
    --tags Key=service,Value=flagsmith Key=environment,Value=dev \
    --parameters file://$(pwd)/stack-params.json \
    --template-body file://$(pwd)/cloudformation.yml \
    --profile default        

After the stack is created, you can access the Flagsmith service using the URL provided in the CloudFormation stack outputs.

Retrieve the API URL:

aws cloudformation describe-stacks \
    --stack-name flagsmith \
    --query "Stacks[].Outputs[?OutputKey=='ServiceUrl'][] | [0].OutputValue"        

You can now access the Flagsmith service using the URL provided.

When you access the URL, you should see the Flagsmith login page.

Usage

To start using Flagsmith, you need to create an account and log in. Once logged in, you can create feature flags, manage user segments, and more.

You can use this sample code to create an API client for Flagsmith:

import Flagsmith from 'flagsmith-nodejs';

/**
 * Export the Flagsmith client
 */

let flagsmithInstance = null;
export const client = () => {
    if (flagsmithInstance) {
        return flagsmithInstance;
    }

    if (!process.env.FLAGSMITH_ENVIRONMENT_KEY || !process.env.FLAGSMITH_API_URL) {
        console.log('WARNING: Flagsmith environment key or API URL is missing');
        return null;
    } else {
        // initialize Flagsmith client
        flagsmithInstance = new Flagsmith({
            environmentKey: process.env.FLAGSMITH_ENVIRONMENT_KEY,
            apiUrl: process.env.FLAGSMITH_API_URL,
        });

        return flagsmithInstance;
    }
};

export const isKeyConfigured = () => {
    return !!process.env.FLAGSMITH_ENVIRONMENT_KEY || !!process.env.FLAGSMITH_API_URL;
};        

The expected environment variables are:

  • FLAGSMITH_ENVIRONMENT_KEY: The environment key for Flagsmith.
  • FLAGSMITH_API_URL: The API URL for the Flagsmith service (e.g., https://flagsmith.example.com/api/v1/).

Conclusion

In this tutorial, we deployed Flagsmith on AWS using CloudFormation. We created an ECR repository for the Flagsmith Docker image, and then deployed the CloudFormation stack to create the necessary resources for running the Flagsmith service. We also retrieved the API URL to access the Flagsmith service. You can now start using Flagsmith to manage feature flags and configurations for your applications.




This post was originally published on:

https://royfirestein.com/blog/deploy-open-source-feature-flags-on-aws


Thanks so much for writing this, Roy! Finding things like this makes our day and I've already shared it with the team. Really happy Flagsmith's working for your setup. Also, love this line "Imagine a light switch in your home; you can easily turn the lights on or off without rewiring the electrical system." ??

Ela Mezhiborsky

Mother | Explorer | Co-Founder & President at Autohost

10 个月

Love the education piece ???? This has been a game changer and a huge part of our customer success strategy! You never appreciate stability as much as when you don't have it ??

要查看或添加评论,请登录

Roy Firestein的更多文章

社区洞察

其他会员也浏览了