Utilizing AWS AppConfig Function Flags


AWS just lately launched AWS AppConfig Function Flags. Function flagging is a strong instrument that permits engineers to soundly push out new options to prospects, however doing so in a measured and normally gradual manner. On this weblog submit, you’ll study what function flags are, what are the advantages to utilizing them, and what are some use-cases for function flags.

The “earlier” approach to launch a function is to first construct the code, then check it in QA, and prepare to deploy to Manufacturing. Engineers have to align the code merge and deployment with the date and time when advertising desires it launched. As soon as that’s all able to go, on launch day, you push out your new code to Manufacturing, and hope every part goes easily. So long as timing goes properly, your prospects can entry the function unexpectedly. Engineers feverishly monitor efficiency metrics to make it possible for the brand new function didn’t introduce instability. That is generally referred to as “a push-and-pray deployment” because you don’t know the way your code will behave on Manufacturing till everyone already has it.

Trendy software program practices use function flags when releasing new performance. Utilizing this method, engineers separate code from configuration information. One can conceal their function behind a configuration toggle (a function flag) and deploy the code to Manufacturing. Nevertheless, for the reason that code is hidden behind their flag, prospects can’t entry the function. The engineer can flip the flag for a really restricted group of customers (for instance, simply themselves, or simply inner customers) and check out the function on Manufacturing. The engineer can then progressively open entry to increasingly more customers. Assuming no alarms are going off throughout the gradual launch of the function, and different metrics are the place you anticipate them, the deployment continues safely till 100% of customers have the brand new function.

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

AWS AppConfig Function flags mean you can confidently deploy modifications to manufacturing by including security guard rails to your function flags. First, AWS AppConfig mean you can set validators and constraints for every flag. If a flag information is non-boolean (for instance, a quantity), prospects can set an elective 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. Moreover, you’ll be able to launch your flags rapidly or progressively by setting a Deployment Technique on your flag updates. Flag updates will be rolled out immediately, or higher but, over the course of hours, thus limiting the blast radius of any surprising change. Lastly, AWS AppConfig will routinely roll again any function flag replace if a CloudWatch alarm is triggered.

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

The right way to create a function flag

Signal into the AWS Administration Console, and go to AWS AppConfig. Word: within the Python instance under, we’re utilizing us-east-1 as our AWS_REGION; you should use any AWS Area, however simply ensure that to replace AWS_REGION appropriately on your Area. You’ll then be prompted to outline an Utility for which the function flags can be used. An software is a namespace for organizing function flags or different configuration information. For the sake of the demo under, name your new Utility FlagsDemo.

After you will have given your software a reputation, you then will create a Configuration Profile that’s of kind Function Flags. Let’s identify this one CheckoutFlags. This Configuration Profile will be regarded as a set of associated flags. You possibly 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 might be an engineer at an organization does ecommerce. You’re planning on including assist for Bitcoin funds at checkout. So, you create a flag in AWS AppConfig referred to 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 function primarily based on the worth of the flag and check it with each the function enabled and disabled. While you push to manufacturing you’ll be able to set the flag to disabled to forestall prospects from accessing the function. As soon as you might be prepared, you replace the toggle in AppConfig, flipping the flag to enabled and deploying it to Manufacturing progressively utilizing AppConfig’s Deployment Methods over the course of an hour. After validating your metrics throughout that hour, 100% of your prospects can now use Bitcoin at checkout.

Subsequent, let’s create a extra advanced flag. On this case, you’ll specify a number of checkout choices utilizing a single flag. Let’s say your crew is launching a brand new function, assist for Bitcoin buying. You wish to give a reduction (for a restricted time) in case your customers select Bitcoin at checkout. On this case, you’ll use flag Attributes, in addition to Attribute constraints. Inside your allow-bitcoin-at-checkout flag you’ll be able to add three Attributes: default-currencybitcoin-discount-percent, and bitcoin-discount-end-date. Discover that for every Attribute, we’ve got additionally added an elective Constraint. These constraints, which will be regex, enums, or quantity ranges, are a further 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 advanced flag means that you can handle three configurations in a single flag. In fact, these may be damaged out into three separate flags as properly. Relying in your software code, use-case, and workflows, that will make extra sense. Nevertheless, preserving these grouped right into a single flag means that you can keep organized and preserve your flags tidy.

Another factor about preserving issues tidy. Did you see the verify field labeled Brief time period flag within the screenshot? With AWS AppConfig Function flags, you’ll be able to preserve your flags organized by figuring out some flags as short-term. Brief-term flags are sometimes used to launch a brand new function. After the function is launched, it would be best to clear up the code and the flags which can be not used. Figuring out a flag as short-term will aid you preserve observe of flags that you’ll deprecate sooner or later. If you happen to establish a flag as short-term, you’ll be able to filter on this attribute within the console. You aren’t required to establish any flags as short-term. This identifier is just meant that will help you filter on momentary flags and clear up unused flags in your software configuration and code.

Within the instance above, the Bitcoin promotion is a restricted time provide. Thus, it is a short-term function flag. As soon as the promotion is accomplished, this flag and naturally its corresponding code, ought to be cleaned up. Utilizing the AWS AppConfig console, you’ll be able to simply discover which flags are short-term flags.

Demo of function flags in motion

Let’s put this all along with a brief demo. First ensure that your allow-bitcoin-at-checkout flag is disabled through the use of the slider toggle on the fitting. Then click on “Save a brand new model” in case you 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 shoppers after they ballot for configuration information utilizing the GetLastestConfiguration API. To do that click on Begin deployment. Throughout the deployment display screen you will want to create an Atmosphere to proceed. Environments are logical deployment teams, such Beta vs Manufacturing, as a way to isolate the rollout of configuration modifications to completely different phases or parts of your software. Let’s name this new surroundings Beta.

There may be one other security guard rail that’s value highlighting throughout Atmosphere creation. Word how there’s a “Screens” part that allows you to optionally specify a CloudWatch alarm. AWS AppConfig will routinely roll again any function flag replace if that alarm is triggered throughout a deployment. By configuring computerized rollback primarily based on CloudWatch alarms, you will have one other approach to safely replace flags.

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

Click on Create surroundings and try to be taken again to the Start deployment display screen the place your new Atmosphere can be pre-selected. Right here, for the sake of the demo, change Deployment technique to AppConfig.AllAtOnce (Fast).

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

Click on Begin deployment to proceed.

Now let’s strive working a small software that may present function flags in motion. The python script under will begin an area webserver and can open up a mock checkout web page in your internet browser. Initially the function flag can be turned off so the web page can have no reference to bitcoin being a foreign money choice. We are going to 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 choice with out requiring any code modifications.

Utilizing a textual content editor, save the next file domestically as flagdemo.py and run it utilizing python3. You’ll need to have the AWS SDK for Python put in which you are able to do by working pip set up boto3. Additionally, you will have to configure environmental AWS credentials which you are able to do with the AWS CLI through aws configure. The IAM person or function tied to the credentials you configure might want to have permissions for "appconfig:GetLatestConfiguration" and "appconfig:StartConfigurationSession".

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

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(
        cached_config_token = start_session_response["InitialConfigurationToken"]

    get_config_response = appconfigdata.get_latest_configuration(
    # Response at all times 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 preserve observe 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 GetLatestConfiguration or if the config contents have modified since
    # the final time we referred to as. So if it is empty we all know we have already got the most recent
    # config, in any other case we have to replace our cache.
    content material = get_config_response["Configuration"].learn()
    if content material:
            cached_config_data = json.masses(content material.decode("utf-8"))
            print("obtained new config information:", cached_config_data)
        besides json.JSONDecodeError as error:
            elevate 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 software generally you'll wish 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", "")
        default_currency = "USD"
        dropdown_display_css = "none"
        bitcoinDiscountPercentage = 0
        bitcoinDiscountEndDate = ""

    if bitcoinDiscountEndDate:
        discountEndDatetime = datetime.strptime(bitcoinDiscountEndDate, “%m/%d/%Y”)
        if datetime.at this time() > discountEndDatetime:
            bitcoinDiscountPercentage = 0

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

    html_template = """
    <meta content material="textual content/html;charset=utf-8" http-equiv="Content material-Sort">
    <meta content material="utf-8" http-equiv="encoding">
    <hyperlink href="https://fonts.googleapis.com/css2?household=Bebas+Neue&show=swap" rel="stylesheet">
        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;
        #foreign money {
            margin-right: 5px;
            show: $dropdownDisplayCSS;
    <title>AppConfig Function Flag Demo Checkout Web page</title>
<physique onload="dropdownChanged()">
    <h1>FooBar Premium Plan Checkout</h1>
    <div class="cart">
        <h4>Procuring Cart</h4>
        FooBar Premium <span class="proper value"></span>
        <p id="btc-discount">
                <small>Early adopter {discount}, order utilizing BTC by $bitcoinDiscountEndDate</small>
                <span class="proper">$bitcoinDiscountPercentage%</span>
            <span class="proper">
                <choose identify="foreign money" id="foreign money" onchange="dropdownChanged()" autocomplete="off">
                    <choice worth="USD" $usdSelected>USD</choice>
                    <choice worth="BTC" $btcSelected>BTC</choice>
                <span class="whole"></span>
    operate dropdownChanged() {
        foreign money = "USD"
        if ('$dropdownDisplayCSS' !== 'none') {
            foreign money = doc.getElementById("foreign money").worth;
        if (foreign money === "USD") {
            value = 450; 
        } else {
            value = 0.000026;  
        if ({discount} && foreign money === "BTC") {
            whole = value - (value*{discount}/100);
            whole = whole.toFixed(6);
            doc.getElementById("btc-discount").type.show = 'inherit';
        } else {
            whole = value;
            doc.getElementById("btc-discount").type.show = 'none';
        doc.querySelectorAll(".value").forEach(txt => { txt.textContent = currencySymbol+value; })
        doc.querySelectorAll(".whole").forEach(txt => { txt.textContent = currencySymbol+whole; })
    html = Template(html_template).substitute(
    return html

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

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

Run the script utilizing Python flagdemo.py and it ought to begin an area 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 choice but as a result of we haven’t enabled that function so let’s accomplish that. Go away the checkout web page open in a tab and return to AppConfig. Allow your flag utilizing the slider on the fitting 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. Earlier than each web page load our little webserver will get the most recent 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 choice purely by means 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.

Utilizing function flags in Lambda

We just lately launched a neater approach to name function flags in Lambda, Utilizing 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 function flagging in a Lambda operate. The arrange course of for function flags utilized in Lambda is similar as above, however you should use the extension to get flag information. Seek the advice of this documentation to see easy methods to name function flags in Lambda.

About CloudWatch Evidently

If you’re considering A/B testing for function optimization, you might contemplate Amazon CloudWatch Evidently. Whereas AWS AppConfig Function Flags are extra suited to function releases with out optimization, CloudWatch Evidently provides you intensive information about two variations of your software program and the way they evaluate by way of efficiency. You possibly can learn extra right here.


Utilizing function flags will be transformative in the way you develop and launch software program. As an alternative of the chance of pushing new code to 100% of your customers on launch day, you should use function flags to deploy code early, however have it hidden behind a function flag configuration. On launch day, simply flip the function flag with out pushing out new code. AWS AppConfig Function Flags allow you to roll out options safely utilizing flag constraints to verify unintended flag values don’t get launched. Flags will be rolled out progressively to restrict blast radius; if one thing goes improper, AWS AppConfig can routinely roll again your function flags instantly. Moreover, after you might be carried out with a brief flag, AWS AppConfig helps you clear them up and deprecate these flags.

Get began with AWS AppConfig Function Flags and study 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, straightforward to make use of, and guarded in opposition to human error. He’s a former member of AWS’s safety crew the place he helped develop know-how round automated safety testing of the AuthN/AuthZ implementations of AWS companies. Earlier than becoming a member of AWS Ivan labored for 10 years at CGI Federal, partnering carefully with Medicare’s Half 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 College 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, LivingSocial, and AOL.  At AWS, Steve leads AWS AppConfig, which is a service that permits 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 Staff convention. He’s primarily based within the Washington DC space and has a super-smart spouse, 3 pretty youngsters, and a pair of incontinent canine.

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


Leave a Reply

Your email address will not be published. Required fields are marked *