Avatar of Kevin
Kevin
 asked on

Count indexes using "for" in Python

I am trying to write a python script to verify whether or not a proper security constraint was applied in AWS. The script seems to be working, however, it is returning a duplicate output (code is attached)

Here is a sample log output when it is run in AWS Lambda:

START RequestId: 8edc3e6d-c727-11e7-ad8e-07aa7f7d4c10 Version: $LATEST
port-7dheonjnhtxci

Listing constraints.........
Checking for valid SG template constraint....
['port-7dheonjnhtxci'] Contains a valid SG template constraint....
Listing constraints.........
Checking for valid SG template constraint....
['port-7dheonjnhtxci'] Contains a valid SG template constraint....

END RequestId: 8edc3e6d-c727-11e7-ad8e-07aa7f7d4c10

As you can see, it is returning the same information twice.  I am relatively new to Python so I am sure it is just a simple oversight on my part. Any assistance would be greatly appreciated.
Code.txt
PythonAWSSecurity

Avatar of undefined
Last Comment
aikimark

8/22/2022 - Mon
aikimark

I would use enumerate() for your iterations, starting with portids
http://book.pythontips.com/en/latest/enumerate.html
Kevin

ASKER
I tried the enumerate function as well but still got a duplicate output.
aikimark

what does your code look like now?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Kevin

ASKER
I think I may have fixed it...my only challenge now is how to properly do the "else if" in python. Currently, it is using the string find method to see if a particular substring matches an expression pattern. If it returns true, it adds it to the output. How can I add logic in the script to also report if it does not contain the expression pattern that I am searching for?
Code.txt
aikimark

I don't see any elif statements.

Please post your code in a CODE snippet tag, using the link above the comment box.
Kevin

ASKER
That is what I am trying to work on now. Here is the latest code:

from __future__ import print_function
import json
import boto3
import traceback
from boto3.session import Session
import zipfile
import botocore
import uuid


client = boto3.client('servicecatalog')

def lambda_handler(event, context):
    constraint_metadata=[]
    constraintIDs=[]
    portIds=list_portfolios()

    for index, value in enumerate(portIds):
        try:
            print (portIds[index])
            prodIds=list_products_for_portfolio(portIds[index])
            #Iterate over all products to check constraints
            constraintIDs=list_template_constraint_for_portfolio(portIds[index])
            for constraintID in constraintIDs:
                if not (constraintIDs is None):
                    print ((str(constraintID)) + " Contains a valid SG template constraint....\n")
        except Exception as e:
            print('Function failed due to exception.')
            print(e)
        else:
            print (portIds[index])
            prodIds=list_products_for_portfolio(portIds[index])
            #Iterate over all products to check constraints
            constraintIDs=list_launch_constraint_for_portfolio(portIds[index])
            for constraintID in constraintIDs:
                if not (constraintIDs is None):
                    print ((str(constraintID)) + " Contains a valid launch constraint....\n")   
        
def list_template_constraint_for_portfolio(id):
    constraintIDs=[]
    response = client.list_constraints_for_portfolio(
    AcceptLanguage='en',
    PortfolioId=id
)
    for index in range(len(response['ConstraintDetails'])):
        if response['ConstraintDetails'][index]['Type'] == 'TEMPLATE':
           if "SecurityGroup" in str(describe_constraint(response['ConstraintDetails'][index]['ConstraintId'])):
              constraintIDs.append(response['ConstraintDetails'][index]['ConstraintId'])
    return constraintIDs
    
def list_launch_constraint_for_portfolio(id):
    constraintIDs=[]
    response = client.list_constraints_for_portfolio(
    AcceptLanguage='en',
    PortfolioId=id
)
    for index in range(len(response['ConstraintDetails'])):
        if response['ConstraintDetails'][index]['Type'] == 'LAUNCH':
           if "RoleArn" in str(describe_constraint(response['ConstraintDetails'][index]['ConstraintId'])):
              constraintIDs.append(response['ConstraintDetails'][index]['ConstraintId'])
    return constraintIDs

def list_portfolios():
    nextmarker = None
    done = False
    lst_portfolio = []
    portIds=[]

    while not done:
        if nextmarker:
                portfolio_response = client.list_portfolios(PageToken=nextmarker,PageSize=20)
        else:
            portfolio_response = client.list_portfolios()

        for portfolio in portfolio_response['PortfolioDetails']:
            lst_portfolio.append(portfolio)

        if 'NextPageToken' in portfolio_response:
            nextmarker = portfolio_response['NextPageToken']
        else:
            break
    for i in range(len(lst_portfolio)):
        portId = lst_portfolio[i]['Id']
        portIds.append(portId)
    return portIds


def list_products_for_portfolio(id):
    nextmarker = None
    done = False
    lst_products = []

    while not done:
        if nextmarker:
            product_response = client.search_products_as_admin(nextmarker=nextmarker, PortfolioId=id)
        else:
            product_response = client.search_products_as_admin(PortfolioId=id)

        for product in product_response['ProductViewDetails']:
            lst_products.append(product['ProductViewSummary'])

        if 'NextPageToken' in product_response:
            nextmarker = product_response['NextPageToken']
        else:
            break
    return lst_products

def describe_constraint(constraintId):
    response = client.describe_constraint(
    AcceptLanguage='en',
    Id=constraintId
)
    obj=eval(str(response))

    return obj

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
aikimark

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question