Count indexes using "for" in Python

Kevin
Kevin used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

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

Author

Commented:
I tried the enumerate function as well but still got a duplicate output.
Top Expert 2014

Commented:
what does your code look like now?
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Author

Commented:
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
Top Expert 2014

Commented:
I don't see any elif statements.

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

Author

Commented:
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

Top Expert 2014
Commented:
Thanks for using the code snippet feature.

When using enumerate, you don't need to use index value if you only want the value of the iterable object during that iteration.  For instance, your code can look more like this.
    for index, value in enumerate(portIds):
        try:
            print (value)
            prodIds=list_products_for_portfolio(value)
            #Iterate over all products to check constraints
            constraintIDs=list_template_constraint_for_portfolio(value)

Open in new window


If you don't need the index value, you can skip the enumerate() function.
    for value in portIds:
        try:
            print (value)
            prodIds=list_products_for_portfolio(value)
            #Iterate over all products to check constraints
            constraintIDs=list_template_constraint_for_portfolio(value)

Open in new window

If portids is not natively iterable, you might simplify this using the iter() function.
    for value in iter(portIds):
        try:
            print (value)
            prodIds=list_products_for_portfolio(value)
            #Iterate over all products to check constraints
            constraintIDs=list_template_constraint_for_portfolio(value)

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial