Lam2020
Lam2020

Reputation: 47

How can I iterate over nested dictionaries and lists in boto3 to obtain particular values?

I'm trying to iterate over these values to retrieve the tags to see if any of the tag values matches AWSNetworkFirewallManaged.

I'm having problems figuring out a solution to achieve this.

response = {
    "VpcEndpoints": [
        {
            "VpcEndpointId": "vpce-123",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-test",
            "ServiceName": "com.amazonaws.com",
            "State": "available",
            "SubnetIds": [
                "subnet-random"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-123"
            ],
            "CreationTimestamp": "2022-10-28T01:23:23.924Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "true"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:us-west-2"
                }
            ],
            "OwnerId": "123"
        },
        {
            "VpcEndpointId": "vpce-123",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-<value>",
            "ServiceName": "com.amazonaws.vpce.us-west-2",
            "State": "available",
            "SubnetIds": [
                "subnet-<number>"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-<value>"
            ],
            "CreationTimestamp": "2022-10-28T01:23:42.113Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "True"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:%l"
                }
            ],
            "OwnerId": "random"
            }
        ]
    }

So far I have

for endpoint in DESCRIBE_VPC_ENDPOINTS['VpcEndpoints']:
    print(endpoint['VpcEndpointId']['Tags']

However this needs to be indice, but if it is I do not know if it will still iterate over the rest of the VPC endpoint ids.

Any suggestions or guidance on this?

Upvotes: 1

Views: 139

Answers (1)

Marcin
Marcin

Reputation: 238051

You can use double for loop:

for endpoint in response['VpcEndpoints']:
  for tags in endpoint['Tags']:
    if 'AWSNetworkFirewallManaged' in tags.values():
     print(endpoint['VpcEndpointId'], tags)

Upvotes: 1

Related Questions