We help IT Professionals succeed at work.

Count indexes using "for" in Python

Kevin
Kevin asked
on
260 Views
Last Modified: 2017-11-11
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

aikimarkSocial distance; Wear a mask; Don't touch your face; Wash your hands for 20 seconds
CERTIFIED EXPERT
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.
aikimarkSocial distance; Wear a mask; Don't touch your face; Wash your hands for 20 seconds
CERTIFIED EXPERT
Top Expert 2014

Commented:
what does your code look like now?

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
aikimarkSocial distance; Wear a mask; Don't touch your face; Wash your hands for 20 seconds
CERTIFIED EXPERT
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

Social distance; Wear a mask; Don't touch your face; Wash your hands for 20 seconds
CERTIFIED EXPERT
Top Expert 2014
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION