<?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 Alex Parra on Medium]]></title>
        <description><![CDATA[Stories by Alex Parra on Medium]]></description>
        <link>https://medium.com/@parraletz?source=rss-267510a0a8ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BO55eM85zx7RdJfOYel1Dw.jpeg</url>
            <title>Stories by Alex Parra on Medium</title>
            <link>https://medium.com/@parraletz?source=rss-267510a0a8ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:01:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parraletz/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[Get subnets by Tags in AWS CDK w/ Python]]></title>
            <link>https://parraletz.medium.com/get-subnets-by-tags-in-aws-cdk-w-python-e707ad214cc5?source=rss-267510a0a8ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e707ad214cc5</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-community]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Alex Parra]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 13:14:21 GMT</pubDate>
            <atom:updated>2023-01-22T12:45:00.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yn-qUpnqlw0TczgviL9Ksw.png" /></figure><h3>Get existing subnets by Tags in AWS CDK w/ Python</h3><p>This is a “Today I learned” style post so it is intended to be very simple and short but with valuable information or information that can help solve the same problem I faced :D</p><p>Infrastructure as code is not something new for me, I have experience with terraform and ansible , but I want to migrate to AWS CDK (the reasons will be discussed later in another post) and something typical like getting the subnets that exist in a vpc and then from them get the subnets with a certain tag can be something very easy in terraform or if you use AWS CLI, but in AWS CDK it has its challenge :D</p><p>As you read in the title I opted for python as language to write code with AWS CDK.</p><p>Here we go!</p><h4>Requirements:</h4><ul><li>boto3</li><li>cdk</li></ul><p>First of all, we need to create a function to get the subnets with tag “<strong><em>Tier</em></strong>” and filter them by <strong><em>VpcId</em></strong> :</p><pre>import logging<br>import os<br>import boto3<br>from botocore.exceptions import ClientError<br>import json<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>logger = logging.getLogger()<br>logging.basicConfig(level=logging.INFO,<br>                    format=&#39;%(asctime)s: %(levelname)s: %(message)s&#39;)<br>sess = boto3.Session(profile_name=os.getenv(&#39;AWS_PROFILE&#39;),<br>                     region_name=os.getenv(&quot;AWS_REGION&quot;))<br>vpc_client = sess.client(&quot;ec2&quot;)<br><br>def get_subnets(tag_value, vpc):<br>    try:<br>        paginator = vpc_client.get_paginator(&#39;describe_subnets&#39;)<br>        response_iterator = paginator.paginate(<br>            Filters=[{<br>                &#39;Name&#39;: &#39;tag:Tier&#39;,<br>                &#39;Values&#39;: [tag_value]<br>            }]<br>        )<br>        full_result = response_iterator.build_full_result()<br>        subnet_list = []<br>        for subnet in full_result[&#39;Subnets&#39;]:<br>            if subnet[&#39;VpcId&#39;] == vpc:<br>                subnet_list.append(subnet)<br>        logger.info(f&quot;Subnets selected: {subnet_list}&quot;)<br>    except ClientError:<br>        logger.exception(&#39;Could not describe subnets.&#39;)<br>        raise<br>    else:<br>        return subnet_list</pre><p>After that, we have to integrate it with AWS CDK, for that we will use the following snippet to get the subnets with tag <strong><em>“Tier</em></strong>” and value <strong><em>“Public”</em></strong>:</p><pre>from aws_cdk import (<br>    # Duration,<br>    Stack,<br>    CfnOutput,<br>    aws_ec2 as ec2,<br>    aws_autoscaling as autoscaling,<br>    aws_elasticloadbalancingv2 as elb,<br>    aws_iam as iam<br>)<br>from constructs import Construct<br>from cdk_app_sample.subnets import get_subnets<br>import os<br><br>class CdkAppSample(Stack):<br><br>    def __init__(self, scope: Construct, construct_id: str, **kwargs) -&gt; None:<br>        super().__init__(scope, construct_id, **kwargs)<br><br>        ... <br>        vpc = ec2.Vpc.from_lookup(<br>            self, &quot;VPC&quot;, vpc_id=vpc_id)<br><br>        public_subnets_ids = []<br><br>        for subnet in get_subnets(&quot;Public&quot;, os.getenv(&#39;VPC_ID&#39;)):<br>            public_subnets_ids.append(<br>                ec2.Subnet.from_subnet_id(self, subnet[&#39;SubnetId&#39;], subnet[&#39;SubnetId&#39;])<br>            )<br>        subnets_public = ec2.SubnetSelection(<br>            subnets = public_subnets_ids<br>        )<br><br>        alb = elb.ApplicationLoadBalancer(self, f&quot;{os.getenv(&#39;PROJECT_NAME&#39;)}-alb&quot;,<br>                                          load_balancer_name=f&quot;{os.getenv(&#39;PROJECT_NAME&#39;)}-alb&quot;,<br>                                          vpc=vpc,<br>                                          internet_facing=True,<br>                                          vpc_subnets=subnets_public<br>        )<br><br>      </pre><p>As you have seen, one of the advantages you have when using AWS CDK is that you can integrate it with other libraries like boto3 to maximize the capabilities of AWS CDK, although I know that AWS CDK should have a simpler method , but as they have their tradeoffs.</p><h4>Happy cdking!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e707ad214cc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>