Using AWS AppConfig Feature Flags

0
87
Using AWS AppConfig Feature Flags


AWS just lately launched AWS AppConfig Feature Flags. Feature flagging is a strong device that enables engineers to securely push out new options to clients, however doing so in a measured and often gradual method. In this weblog put up, you’ll study what characteristic flags are, what are the advantages to utilizing them, and what are some use-cases for characteristic flags.

The “earlier” solution to launch a characteristic is to first construct the code, then take a look at it in QA, and prepare to deploy to Production. Engineers have to align the code merge and deployment with the date and time when advertising and marketing desires it launched. Once that’s all able to go, on launch day, you push out your new code to Production, and hope all the pieces goes easily. As lengthy as timing goes nicely, your clients can entry the characteristic unexpectedly. Engineers feverishly monitor efficiency metrics to guarantee that the brand new characteristic didn’t introduce instability. This is usually often known as “a push-and-pray deployment” because you don’t understand how your code will behave on Production till everyone already has it.

Modern software program practices use characteristic flags when releasing new performance. Using this method, engineers separate code from configuration information. One can cover their characteristic behind a configuration toggle (a characteristic flag) and deploy the code to Production. However, for the reason that code is hidden behind their flag, clients can’t entry the characteristic. The engineer can flip the flag for a really restricted group of customers (for instance, simply themselves, or simply inner customers) and take a look at out the characteristic on Production. The engineer can then regularly open entry to an increasing number of customers. Assuming no alarms are going off throughout the gradual launch of the characteristic, and different metrics are the place you anticipate them, the deployment continues safely till 100% of customers have the brand new characteristic.

There are totally different use-cases for and sorts of characteristic flags, relying on the necessity. As famous above, a launch flag can be utilized to develop a brand new characteristic in your utility. Engineers code the characteristic, deploy it whereas the characteristic is hidden behind a characteristic flag, and regularly make the characteristic out there for customers, all whereas monitoring your utility’s well being. Experimentation flags, used for A/B testing, are very helpful for gathering information about variations of performance. Instead of arguing which variation could be higher, an A/B take a look at gives you actual information to show out which experiment is most profitable. CloudWatch Evidently is a strong answer for experimentation characteristic flags. Operations flags are used for tuning your utility. Engineers would possibly put values just like the variety of simultaneous background duties right into a characteristic flag, to allow them to flip that up and down, relying on the situations on manufacturing.

AWS AppConfig Feature flags permit you to confidently deploy modifications to manufacturing by including security guard rails to your characteristic flags. First, AWS AppConfig permit you to set validators and constraints for every flag. If a flag information is non-boolean (for instance, a quantity), clients can set an non-compulsory minimal and most worth for that quantity to make sure some unintended flag worth doesn’t trigger an issue and even an outage in manufacturing. Furthermore, you’ll be able to launch your flags shortly or regularly by setting a Deployment Strategy on your flag updates. Flag updates might be rolled out immediately, or higher but, over the course of hours, thus limiting the blast radius of any surprising change. Finally, AWS AppConfig will robotically roll again any characteristic flag replace if a CloudWatch alarm is triggered.

Now let’s arrange some characteristic flags in AWS AppConfig so you’ll be able to see the way it actually works.

How to create a characteristic flag

Sign into the AWS Management Console, and go to AWS AppConfig. Note: within the Python instance beneath, we’re utilizing us-east-1 as our AWS_REGION; you should use any AWS Region, however simply be sure that to replace AWS_REGION appropriately on your Region. You will then be prompted to outline an Application for which the characteristic flags might be used. An utility is a namespace for organizing characteristic flags or different configuration information. For the sake of the demo beneath, name your new Application FlagsDemo.

After you will have given your utility a reputation, you then will create a Configuration Profile that’s of kind Feature Flags. Let’s identify this one CheckoutFlags. This Configuration Profile might be considered a set of associated flags. You can have one flag in every Configuration Profile, or dozens of flags.

Now let’s create a easy Boolean flag. For this instance, let’s say you’re an engineer at an organization does ecommerce. You are planning on including assist for Bitcoin funds at checkout. So, you create a flag in AWS AppConfig known as allow-bitcoin-at-checkout, and default it to disabled. You write code that code has conditional logic in it to manage entry to that characteristic primarily based on the worth of the flag and take a look at it with each the characteristic enabled and disabled. When you push to manufacturing you’ll be able to set the flag to disabled to forestall clients from accessing the characteristic. Once you’re prepared, you replace the toggle in AppConfig, flipping the flag to enabled and deploying it to Production regularly utilizing AppConfig’s Deployment Strategies over the course of an hour. After validating your metrics throughout that hour, 100% of your clients can now use Bitcoin at checkout.

Next, let’s create a extra complicated flag. In this case, you’ll specify a number of checkout choices utilizing a single flag. Let’s say your workforce is launching a brand new characteristic, assist for Bitcoin buying. You need to give a reduction (for a restricted time) in case your customers select Bitcoin at checkout. In this case, you’ll use flag Attributes, in addition to Attribute constraints. Within your allow-bitcoin-at-checkout flag you’ll be able to add three Attributes: default-currencybitcoin-discount-percent, and bitcoin-discount-end-date. Notice that for every Attribute, we’ve additionally added an non-compulsory Constraint. These constraints, which might be regex, enums, or quantity ranges, are an extra security guard rails to make sure that your flag information is what is anticipated. They validate the flag information previous to it being deployed.

The AWS AppConfig Console. Shows a single feature flag with three attributes: default-currency, bitcoin-discount-percent, and bitcoin-discount-end-date.

This extra complicated flag lets you handle three configurations in a single flag. Of course, these may be damaged out into three separate flags as nicely. Depending in your utility code, use-case, and workflows, which will make extra sense. However, conserving these grouped right into a single flag lets you keep organized and maintain your flags tidy.

One other thing about conserving issues tidy. Did you see the verify field labeled Short time period flag within the screenshot? With AWS AppConfig Feature flags, you’ll be able to maintain your flags organized by figuring out some flags as short-term. Short-term flags are sometimes used to launch a brand new characteristic. After the characteristic is launched, you’ll want to clear up the code and the flags which can be not used. Identifying a flag as short-term will assist you maintain monitor of flags that you’ll deprecate sooner or later. If you determine a flag as short-term, you’ll be able to filter on this attribute within the console. You aren’t required to determine any flags as short-term. This identifier is simply meant that can assist you filter on momentary flags and clear up unused flags in your utility configuration and code.

In the instance above, the Bitcoin promotion is a restricted time provide. Thus, this can be a short-term characteristic flag. Once the promotion is accomplished, this flag and naturally its corresponding code, ought to be cleaned up. Using the AWS AppConfig console, you’ll be able to simply discover which flags are short-term flags.

Demo of characteristic flags in motion

Let’s put this all along with a brief demo. First be sure that your allow-bitcoin-at-checkout flag is disabled by utilizing the slider toggle on the suitable. Then click on “Save a new version” for those who haven’t already.

AWS AppConfig Console. Shows a single feature flag that is ready to be deployed.

Now let’s deploy this preliminary model with the flag disabled. Deployments in AppConfig make your configuration modifications seen to purchasers after they ballot for configuration information utilizing the GetLastestConfiguration API. To do that click on Start deployment. Within the deployment display you will want to create an Environment to proceed. Environments are logical deployment teams, such Beta vs Production, so to isolate the rollout of configuration modifications to totally different levels or parts of your utility. Let’s name this new atmosphere Beta.

There is one other security guard rail that’s price highlighting throughout Environment creation. Note how there’s a “Monitors” part that permits you to optionally specify a CloudWatch alarm. AWS AppConfig will robotically roll again any characteristic flag replace if that alarm is triggered throughout a deployment. By configuring computerized rollback primarily based on CloudWatch alarms, you will have one other solution to safely replace flags.

the AWS AppConfig console. Shows how to set up an Environment to which you would deploy configuration.

Click Create atmosphere and you ought to be taken again to the Start deployment display the place your new Environment might be pre-selected. Here, for the sake of the demo, change Deployment technique to AppConfig.AllAtOnce (Quick).

AWS AppConfig console. Shows how to deploy configuration using the AllAtOnce deployment strategy.

Click Start deployment to proceed.

Now let’s attempt operating a small utility that can present characteristic flags in motion. The python script beneath will begin a neighborhood webserver and can open up a mock checkout web page in your net browser. Initially the characteristic flag might be turned off so the web page could have no reference to bitcoin being a forex possibility. We will then allow and re-deploy our allow-bitcoin-at-checkout flag and see how the web page can reconfigure itself to point out bitcoin as an possibility with out requiring any code modifications.

Using a textual content editor, save the next file regionally as flagdemo.py and run it utilizing python3. You might want to have the AWS SDK for Python put in which you are able to do by operating pip set up boto3. You may even have to configure environmental AWS credentials which you are able to do with the AWS CLI by way of aws configure. The IAM person or position tied to the credentials you configure might want to have permissions for "appconfig:GetNewestConfiguration" and "appconfig:StartConfigurationSession".

from datetime import datetime, timedelta
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from string import Template
import webbrowser
import boto3

WEBSERVER_PORT = 8080
APPCONFIG_APPLICATION_NAME = "FlagsDemo"
APPCONFIG_CONFIG_PROFILE_NAME = "CheckoutFlags"
APPCONFIG_ENVIRONMENT_NAME = "Beta"
AWS_REGION = "us-east-1"

cached_config_data = {}
cached_config_token = None
cached_token_expiration_time = None


def get_config():
    international cached_config_token
    international cached_config_data
    international cached_token_expiration_time
    appconfigdata = boto3.shopper("appconfigdata", region_name=AWS_REGION)

    # If we do not have a token but, name start_configuration_session to get one
    if not cached_config_token or datetime.now() >= cached_token_expiration_time:
        start_session_response = appconfigdata.start_configuration_session(
            ApplicationIdentifier=APPCONFIG_APPLICATION_NAME,
            EnvironmentIdentifier=APPCONFIG_ENVIRONMENT_NAME,
            ConfigurationProfileIdentifier=APPCONFIG_CONFIG_PROFILE_NAME,
        )
        cached_config_token = start_session_response["InitialConfigurationToken"]

    get_config_response = appconfigdata.get_latest_configuration(
        ConfigurationToken=cached_config_token
    )
    # Response all the time features a contemporary token to make use of in subsequent name
    cached_config_token = get_config_response["NextPollConfigurationToken"]
    # Token will expire if not refreshed inside 24 hours, so maintain monitor of
    # the anticipated expiration time minus a little bit of padding
    cached_token_expiration_time = datetime.now() + timedelta(hours=23, minutes=59)
    # 'Configuration' within the response will solely be populated the primary time we
    # name GetNewestConfiguration or if the config contents have modified since
    # the final time we known as. So if it is empty we all know we have already got the newest
    # config, in any other case we have to replace our cache.
    content material = get_config_response["Configuration"].learn()
    if content material:
        attempt:
            cached_config_data = json.masses(content material.decode("utf-8"))
            print("obtained new config information:", cached_config_data)
        besides json.JSONDecodeError as error:
            increase ValueError(error.msg) from error

    return cached_config_data


def get_html():
    # For simplicity this code fetches a contemporary config from AppConfig each time a web page is served.
    # In an precise utility usually you'll need to ballot AppConfig within the background
    # and cache the outcomes.
    config = get_config()
    allow_bitcoin_flag = config["allow-bitcoin-at-checkout"]

    if allow_bitcoin_flag["enabled"]:
        dropdown_display_css = "preliminary"
        default_currency = allow_bitcoin_flag["default-currency"]
        bitcoinDiscountPercentage = allow_bitcoin_flag["bitcoin-discount-percentage"]
        bitcoinDiscountEndDate = allow_bitcoin_flag.get("bitcoin-discount-end-date", "")
    else:
        default_currency = "USD"
        dropdown_display_css = "none"
        bitcoinDiscountPercentage = 0
        bitcoinDiscountEndDate = ""

    if bitcoinDiscountEndDate:
        discountEndDatetime = datetime.strptime(bitcoinDiscountEndDate, “%m/%d/%Y”)
        if datetime.in the present day() > discountEndDatetime:
            bitcoinDiscountPercentage = 0

    usd_selected = "chosen='chosen'" if default_currency == "USD" else ""
    btc_selected = "chosen='chosen'" if default_currency == "BTC" else ""

    html_template = """
<html>
<head>
    <meta content material="textual content/html;charset=utf-8" http-equiv="Content-Type">
    <meta content material="utf-8" http-equiv="encoding">
    <hyperlink href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap" rel="stylesheet">
    <fashion>
        h1 {
            font-family: 'Bebas Neue', cursive;
        }
        .cart {
            width: 350px;
            background-color: rgb(210, 221, 231);
            border-radius: 10px;
            padding: 0px 10px 10px 10px;
            border: 1px stable lightgrey;
        }
        .proper {
            float: proper;
        }
        #forex {
            margin-right: 5px;
            show: $dropdownDisplayCSS;
        }
    </fashion>
    <title>AppConfig Feature Flag Demo Checkout Page</title>
</head>
<physique onload="dropdownChanged()">
    <h1>FooBar Premium Plan Checkout</h1>
    <div class="cart">
        <h4>Shopping Cart</h4>
        FooBar Premium <span class="proper value"></span>
        <hr>
        <p id="btc-discount">
            <i>
                <small>Early adopter {discount}, order utilizing BTC by $bitcoinDiscountEndDate</small>
                <span class="proper">$bitcoinDiscountPercentage%</span>
            </i>
        </p>
        <b>Total:</b>
            <span class="proper">
                <choose identify="forex" id="forex" onchange="dropdownChanged()" autocomplete="off">
                    <possibility worth="USD" $usdSelected>USD</possibility>
                    <possibility worth="BTC" $btcSelected>BTC</possibility>
                </choose>
                <span class="whole"></span>
            </span>
    </div>
</physique>
<script>
    operate dropdownChanged() {
        forex = "USD"
        if ('$dropdownDisplayCSS' !== 'none') {
            forex = doc.getElementById("forex").worth;
        }
        if (forex === "USD") {
            currencySymbol="$$";
            value = 450; 
        } else {
            currencySymbol="₿";
            value = 0.000026;  
        }
        {discount}=$bitcoinDiscountPercentage;
        if ({discount} && forex === "BTC") {
            whole = value - (value*{discount}/100);
            whole = whole.toFixed(6);
            doc.getElementById("btc-discount").fashion.show = 'inherit';
        } else {
            whole = value;
            doc.getElementById("btc-discount").fashion.show = 'none';
        }
        doc.querySelectorAll(".value").forEach(txt => { txt.textual contentContent = currencySymbol+value; })
        doc.querySelectorAll(".whole").forEach(txt => { txt.textual contentContent = currencySymbol+whole; })
    }
</script>
</html>
    """
    html = Template(html_template).substitute(
        dropdownDisplayCSS=dropdown_display_css,
        usdSelected=usd_selected,
        btcSelected=btc_selected,
        bitcoinDiscountPercentage=bitcoinDiscountPercentage,
        bitcoinDiscountEndDate=bitcoinDiscountEndDate,
    )
    return html


class EasyCheckoutPageWebServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "textual content/html")
        self.end_headers()
        self.wfile.write(bytes(get_html(), "utf-8"))


if __name__ == "__main__":
    hostname = "localhost"
    webServer = HTTPServer((hostname, WEBSERVER_PORT), EasyCheckoutPageWebServer)
    url = f"http://{hostname}:{WEBSERVER_PORT}"
    print(f"Local webserver began. To view, navigate your browser to: {url}")
    webbrowser.open(url, new=2)
    attempt:
        webServer.serve_forever()
    besides KeyboardInterrupt:
        move
    webServer.server_close()

Run the script utilizing Python flagdemo.py and it ought to begin a neighborhood webserver, question AppConfig on your configuration, and open a web page in your browser that reveals a mock checkout web page.

The sample Python app. It shows a demo checkout screen in US dollars.

There’s no reference to bitcoin being an possibility but as a result of we haven’t enabled that characteristic so let’s accomplish that. Leave the checkout web page open in a tab and return to AppConfig. Enable your flag utilizing the slider on the suitable and be sure to’ve created the three attributes proven within the screenshot. Then save and deploy identical to you probably did final time.

The AWS AppConfig console sample feature flag with additional attributes.

AWS AppConfig console. This image shows how to deploy configuration.

Now return to your tab with the checkout web page and reload the browser. Before each web page load our little webserver will get the newest configuration from AppConfig and render the web page accordingly. When the web page reloads, you’ll be able to see that we’ve now enabled Bitcoin as an possibility purely by way of a configuration change with no need to deploy new code.

The sample Python app. After deploying the feature flag, this image now shows a demo checkout screen using Bitcoin.

Using characteristic flags in Lambda

We just lately launched a better solution to name characteristic flags in Lambda, Using the AWS AppConfig Lambda extension, you’ll be able to simply name a single flag or a number of flags to have the ability of characteristic flagging in a Lambda operate. The arrange course of for characteristic flags utilized in Lambda is identical as above, however you should use the extension to get flag information. Consult this documentation to see easy methods to name characteristic flags in Lambda.

About CloudWatch Evidently

If you have an interest in A/B testing for characteristic optimization, you might think about Amazon CloudWatch Evidently. While AWS AppConfig Feature Flags are extra suited to characteristic releases with out optimization, CloudWatch Evidently offers you intensive information about two variations of your software program and the way they evaluate by way of efficiency. You can learn extra right here.

Conclusion

Using characteristic flags might be transformative in the way you develop and launch software program. Instead of the chance of pushing new code to 100% of your customers on launch day, you should use characteristic flags to deploy code early, however have it hidden behind a characteristic flag configuration. On launch day, simply flip the characteristic flag with out pushing out new code. AWS AppConfig Feature Flags allow you to roll out options safely utilizing flag constraints to verify unintended flag values don’t get launched. Flags might be rolled out regularly to restrict blast radius; if one thing goes flawed, AWS AppConfig can robotically roll again your characteristic flags instantly. Furthermore, after you’re accomplished with a brief flag, AWS AppConfig helps you clear them up and deprecate these flags.

Get began with AWS AppConfig Feature Flags and be taught extra about AWS AppConfig.

Ivan Garcia: Ivan is a software program engineer at AWS AppConfig the place he enjoys making software program that’s safe, simple to make use of, and guarded towards human error. He is a former member of AWS’s safety workforce the place he helped develop know-how round automated safety testing of the AuthN/AuthZ implementations of AWS providers. Before becoming a member of AWS Ivan labored for 10 years at CGI Federal, partnering intently with Medicare’s Part A auditors to assist streamline and automate the Medicare Audit and Reimbursement course of for American hospitals. Ivan has a B.S from Carnegie Mellon University and because the father of a toddler his hobbies embody peek-a-boo, being chased, and never getting sufficient sleep.

Linkedin: www.linkedin.com/in/ivan-garcia-softwaredev

Steve Rice: Steve has a profession that spans each Product and Engineering management. He has led modern merchandise at firms like Amazon, Coca-Cola, DwellingSocial, and AOL.  At AWS, Steve leads AWS AppConfig, which is a service that enables engineering groups to maneuver sooner and extra safely utilizing steady configuration and have flags. Steve has been a speaker at many conferences, together with re:Invent and the Atlassian Team convention. He relies within the Washington DC space and has a super-smart spouse, 3 pretty children, and a pair of incontinent canine.

LinkedIn: https://www.linkedin.com/in/stevejrice/

LEAVE A REPLY

Please enter your comment!
Please enter your name here