Utilizing AWS AppConfig Function Flags

[ad_1]

AWS not too long ago launched AWS AppConfig Function Flags. Function flagging is a strong device that enables engineers to securely push out new options to clients, however doing so in a measured and normally gradual method. On this weblog put up, you’ll find out about what function flags are, what are the advantages to utilizing them, and what are some use-cases for function flags.

The “earlier” strategy to launch a function is to first construct the code, then take a look at 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 needs it launched. As soon as that’s all able to go, on launch day, you push out your new code to Manufacturing, and hope the whole lot goes easily. So long as timing goes effectively, your clients can entry the function abruptly. Engineers feverishly monitor efficiency metrics to make it possible for the brand new function didn’t introduce instability. That is typically generally known as “a push-and-pray deployment” because you don’t know the way your code will behave on Manufacturing till all people already has it.

Fashionable software program practices use function flags when releasing new performance. Utilizing this system, engineers separate code from configuration knowledge. 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, clients 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 take a look at out the function on Manufacturing. The engineer can then progressively open entry to an increasing number of 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 totally different use-cases for and forms 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 knowledge about variations of performance. As an alternative of arguing which variation is likely to be higher, an A/B take a look at provides you with actual knowledge 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 circumstances on manufacturing.

AWS AppConfig Function flags permit you to confidently deploy modifications to manufacturing by including security guard rails to your function flags. First, AWS AppConfig permit you to set validators and constraints for every flag. If a flag knowledge 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. Moreover, you may launch your flags rapidly or progressively by setting a Deployment Technique 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. Lastly, AWS AppConfig will mechanically roll again any function flag replace if a CloudWatch alarm is triggered.

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

Learn how to create a function flag

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

After you’ve given your software a reputation, you then will create a Configuration Profile that’s of sort Function Flags. Let’s identify this one CheckoutFlags. This Configuration Profile might be regarded as a set of associated flags. You’ll be able to 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 might be planning on including help 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 regulate entry to that function primarily based on the worth of the flag and take a look at it with each the function enabled and disabled. Whenever you push to manufacturing you may set the flag to disabled to forestall clients 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 clients can now use Bitcoin at checkout.

Subsequent, let’s create a extra complicated 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, help 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 may add three Attributes: default-currencybitcoin-discount-percent, and bitcoin-discount-end-date. Discover that for every Attribute, we’ve got 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 knowledge is what is anticipated. They validate the flag knowledge 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 means that you can handle three configurations in a single flag. After all, these may be damaged out into three separate flags as effectively. Relying in your software code, use-case, and workflows, that will make extra sense. Nevertheless, conserving these grouped right into a single flag means that you can keep organized and preserve your flags tidy.

Another factor about conserving issues tidy. Did you see the verify field labeled Quick time period flag within the screenshot? With AWS AppConfig Function flags, you may preserve your flags organized by figuring out some flags as short-term. Quick-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 are now not used. Figuring out a flag as short-term will enable you to preserve monitor of flags that you’ll deprecate sooner or later. Should you determine a flag as short-term, you may filter on this attribute within the console. You aren’t required to determine any flags as short-term. This identifier is barely meant that will help you filter on non permanent flags and clear up unused flags in your software configuration and code.

Within the instance above, the Bitcoin promotion is a restricted time supply. Thus, it is a short-term function flag. As soon as the promotion is accomplished, this flag and naturally its corresponding code, must be cleaned up. Utilizing the AWS AppConfig console, you may 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 be certain your allow-bitcoin-at-checkout flag is disabled through the use of the slider toggle on the appropriate. Then click on “Save a brand new model” should 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 knowledge utilizing the GetLastestConfiguration API. To do that click on Begin deployment. Throughout the deployment display you’ll need to create an Setting to proceed. Environments are logical deployment teams, such Beta vs Manufacturing, with the intention to isolate the rollout of configuration modifications to totally different levels or parts of your software. Let’s name this new surroundings Beta.

There may be one other security guard rail that’s price highlighting throughout Setting creation. Word how there’s a “Displays” part that permits you to optionally specify a CloudWatch alarm. AWS AppConfig will mechanically roll again any function flag replace if that alarm is triggered throughout a deployment. By configuring computerized rollback primarily based on CloudWatch alarms, you’ve one other strategy 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 you have to be taken again to the Start deployment display the place your new Setting 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 attempt operating a small software that can present function flags in motion. The python script beneath will begin a neighborhood 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 may have no reference to bitcoin being a forex 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 indicate bitcoin as an choice with out requiring any code modifications.

Utilizing a textual content editor, save the next file regionally as flagdemo.py and run it utilizing python3. You will want to have the AWS SDK for Python put in which you are able to do by operating 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

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.consumer("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 recent 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 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 GetLatestConfiguration 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 most recent
    # 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 knowledge:", 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 recent 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", "")
    else:
        default_currency = "USD"
        dropdown_display_css = "none"
        bitcoinDiscountPercentage = 0
        bitcoinDiscountEndDate = ""

    if bitcoinDiscountEndDate:
        discountEndDatetime = datetime.strptime(bitcoinDiscountEndDate, “%m/%d/%Y”)
        if datetime.right this moment() > 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 material-Sort">
    <meta content material="utf-8" http-equiv="encoding">
    <hyperlink href="https://fonts.googleapis.com/css2?household=Bebas+Neue&show=swap" rel="stylesheet">
    <model>
        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;
        }
    </model>
    <title>AppConfig Function Flag Demo Checkout Web page</title>
</head>
<physique onload="dropdownChanged()">
    <h1>FooBar Premium Plan Checkout</h1>
    <div class="cart">
        <h4>Buying Cart</h4>
        FooBar Premium <span class="proper worth"></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>Whole:</b>
            <span class="proper">
                <choose identify="forex" id="forex" onchange="dropdownChanged()" autocomplete="off">
                    <choice worth="USD" $usdSelected>USD</choice>
                    <choice worth="BTC" $btcSelected>BTC</choice>
                </choose>
                <span class="whole"></span>
            </span>
    </div>
</physique>
<script>
    perform dropdownChanged() {
        forex = "USD"
        if ('$dropdownDisplayCSS' !== 'none') {
            forex = doc.getElementById("forex").worth;
        }
        if (forex === "USD") {
            currencySymbol="$$";
            worth = 450; 
        } else {
            currencySymbol="₿";
            worth = 0.000026;  
        }
        {discount}=$bitcoinDiscountPercentage;
        if ({discount} && forex === "BTC") {
            whole = worth - (worth*{discount}/100);
            whole = whole.toFixed(6);
            doc.getElementById("btc-discount").model.show = 'inherit';
        } else {
            whole = worth;
            doc.getElementById("btc-discount").model.show = 'none';
        }
        doc.querySelectorAll(".worth").forEach(txt => { txt.textContent = currencySymbol+worth; })
        doc.querySelectorAll(".whole").forEach(txt => { txt.textContent = 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 SimpleCheckoutPageWebServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content material-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), SimpleCheckoutPageWebServer)
    url = f"http://{hostname}:{WEBSERVER_PORT}"
    print(f"Native webserver began. To view, navigate your browser to: {url}")
    webbrowser.open(url, new=2)
    attempt:
        webServer.serve_forever()
    besides KeyboardInterrupt:
        cross
    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 choice but as a result of we haven’t enabled that function so let’s achieve this. Depart the checkout web page open in a tab and return to AppConfig. Allow your flag utilizing the slider on the appropriate and be sure you’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 may 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 not too long ago launched a neater strategy to name function flags in Lambda, Utilizing the AWS AppConfig Lambda extension, you may simply name a single flag or a number of flags to have the ability of function flagging in a Lambda perform. The arrange course of for function flags utilized in Lambda is identical as above, however you need to use the extension to get flag knowledge. Seek the advice of this documentation to see find out how to name function flags in Lambda.

About CloudWatch Evidently

If you’re interested by A/B testing for function optimization, it’s possible you’ll think about Amazon CloudWatch Evidently. Whereas AWS AppConfig Function Flags are extra suited to function releases with out optimization, CloudWatch Evidently offers you intensive knowledge about two variations of your software program and the way they evaluate when it comes to efficiency. You’ll be able to learn extra right here.

Conclusion

Utilizing function flags might be transformative in the way you develop and launch software program. As an alternative of the danger of pushing new code to 100% of your customers on launch day, you need to 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 ensure unintended flag values don’t get launched. Flags might be rolled out progressively to restrict blast radius; if one thing goes fallacious, AWS AppConfig can mechanically roll again your function flags instantly. Moreover, after you might be completed 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 expertise 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 enables engineering groups to maneuver quicker and extra safely utilizing steady configuration and have flags. Steve has been a speaker at many conferences, together with re:Invent and the Atlassian Workforce convention. He’s primarily based within the Washington DC space and has a super-smart spouse, 3 beautiful youngsters, and a pair of incontinent canines.

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

[ad_2]

Leave a Reply