<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chastina Li on Medium]]></title>
        <description><![CDATA[Stories by Chastina Li on Medium]]></description>
        <link>https://medium.com/@li.chastina?source=rss-339a6bb13a82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ux-fmXgRxZ5nX2LHrBBRAg.jpeg</url>
            <title>Stories by Chastina Li on Medium</title>
            <link>https://medium.com/@li.chastina?source=rss-339a6bb13a82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:28:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@li.chastina/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Auto-refresh AWS Tokens Using IAM Role and boto3]]></title>
            <link>https://medium.com/@li.chastina/auto-refresh-aws-tokens-using-iam-role-and-boto3-afd3c52fd8c7?source=rss-339a6bb13a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd3c52fd8c7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[credentials]]></category>
            <dc:creator><![CDATA[Chastina Li]]></dc:creator>
            <pubDate>Wed, 17 Oct 2018 22:33:51 GMT</pubDate>
            <atom:updated>2018-10-17T22:33:51.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Session management in AWS is complicated, especially when authenticating with IAM roles. A common way to obtain AWS credentials is to assume an IAM role and be given a set of temporary session keys that are only good for a certain period of time. The maximum session duration is a setting on the IAM role itself, and it is one hour by default. So if users don’t specify a value for theDurationSeconds parameter, their security credentials are valid for one hour.</p><p>A typical boto3 request to assume IAM role looks like:</p><pre>response <strong>=</strong> client<strong>.</strong>assume_role(<br>    RoleArn<strong>=</strong>&#39;string&#39;,<br>    RoleSessionName<strong>=</strong>&#39;string&#39;,<br>    Policy<strong>=</strong>&#39;string&#39;,<br>    DurationSeconds<strong>=</strong>123,<br>    ExternalId<strong>=</strong>&#39;string&#39;,<br>    SerialNumber<strong>=</strong>&#39;string&#39;,<br>    TokenCode<strong>=</strong>&#39;string&#39;<br>)</pre><p>where DurationSeconds is the duration of the role session. It can go up to the maximum session duration setting for the role. So if your IAM role is only setup to go up to an hour, you wouldn’t be able to extend the duration of your sessions unless you update the settings on the IAM role itself, a time consuming step in a lot of places.</p><p>So an alternative must be introduced to extend IAM role sessions. This is when I found RefreshableCredentials , a <a href="https://www.pydoc.io/pypi/botocore-1.7.0/autoapi/credentials/index.html#credentials.RefreshableCredentials">botocoreclass</a> acting like a container for credentials needed to authenticate requests. Moreover, it can automatically refresh the credentials! This is exactly what I need. But it’s usage is poorly documented. Looking at its source code:</p><pre>def __init__(self, access_key, secret_key, token, expiry_time, refresh_using, method, time_fetcher=_local_now):</pre><p>The __init__ function takes several arguments, half of which I don’t recognize. But there’s a class method that can be used to initialize an object:</p><pre>@classmethod<br>def create_from_metadata(cls, metadata, refresh_using, method):<br>    instance = cls(<br>         access_key=metadata[&#39;access_key&#39;],<br>         secret_key=metadata[&#39;secret_key&#39;],<br>         token=metadata[&#39;token&#39;],<br>         expiry_time=cls._expiry_datetime(metadata[&#39;expiry_time&#39;]),<br>         method=method,<br>         refresh_using=refresh_using)<br>    return instance</pre><p>where metadata is a dictionary containing information abound the <strong>current session</strong>, ie. access_key , secret_key, token, and expiry_time , all are things we can get from boto3’s STS client’s <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role">assume_role()</a> request:</p><pre>{<br>    &#39;Credentials&#39;: {<br>        &#39;AccessKeyId&#39;: &#39;string&#39;,<br>        &#39;SecretAccessKey&#39;: &#39;string&#39;,<br>        &#39;SessionToken&#39;: &#39;string&#39;,<br>        &#39;Expiration&#39;: datetime(2015, 1, 1)<br>    },<br>    &#39;AssumedRoleUser&#39;: {<br>        &#39;AssumedRoleId&#39;: &#39;string&#39;,<br>        &#39;Arn&#39;: &#39;string&#39;<br>    },<br>    &#39;PackedPolicySize&#39;: 123<br>}</pre><p>To construct the metadata response, we make a simple boto3 API call:</p><pre>import boto3</pre><pre>sts_client = boto3.client(&quot;sts&quot;, region_name=aws_region)<br>params = {<br>    &quot;RoleArn&quot;: self.role_name,<br>    &quot;RoleSessionName&quot;: self.session_name,<br>    &quot;DurationSeconds&quot;: 3600,<br>}<br>response = sts_client.assume_role(**params).get(&quot;Credentials&quot;)<br>metadata = {<br>    &quot;access_key&quot;: response.get(&quot;AccessKeyId&quot;),<br>    &quot;secret_key&quot;: response.get(&quot;SecretAccessKey&quot;),<br>    &quot;token&quot;: response.get(&quot;SessionToken&quot;),<br>    &quot;expiry_time&quot;: response.get(&quot;Expiration&quot;).isoformat(),<br>}</pre><p>refresh_using is a callable that returns a set of new credentials, taking the format of metadata. Remember that in Python, functions are first-class citizens. You can assign them to variables, store them in data structures, pass them as arguments to other functions, and even return them as values from other functions. So I just need a function that generates and returns metadata.</p><pre>def _refresh(self):<br>    &quot; Refresh tokens by calling assume_role again &quot;<br>    params = {<br>        &quot;RoleArn&quot;: self.role_name,<br>        &quot;RoleSessionName&quot;: self.session_name,<br>        &quot;DurationSeconds&quot;: 3600,<br>    }<br><br>    response = self.sts_client.assume_role(**params).get(&quot;Credentials&quot;)<br>    credentials = {<br>        &quot;access_key&quot;: response.get(&quot;AccessKeyId&quot;),<br>        &quot;secret_key&quot;: response.get(&quot;SecretAccessKey&quot;),<br>        &quot;token&quot;: response.get(&quot;SessionToken&quot;),<br>        &quot;expiry_time&quot;: response.get(&quot;Expiration&quot;).isoformat(),<br>    }<br>    return credentials</pre><p>Now we’re ready to create a RefreshableCredentials object:</p><pre>from botocore.credentials import RefreshableCredentials</pre><pre>session_credentials = RefreshableCredentials.create_from_metadata(<br>    metadata=self._refresh(),<br>    refresh_using=self._refresh,<br>    method=&quot;sts-assume-role&quot;,<br>)</pre><p>and we can use the credentials to <strong>generate a IAM role session</strong> that lasts for as long as we need:</p><pre>from boto3 import Session<br>from botocore.session import get_session</pre><pre>session = get_session()<br>session._credentials = session_credentials<br>session.set_config_variable(&quot;region&quot;, aws_region)</pre><pre>autorefresh_session = Session(botocore_session=session)</pre><p>And of course we can generate a boto client within that session, ie.:</p><pre>db_client = autorefresh_session.client(&quot;rds&quot;, region_name=&#39;us-east-1&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd3c52fd8c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>