Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if IAM role already exists and then skip creating new one. #2

Open
san089 opened this issue Jan 30, 2020 · 1 comment
Open

Check if IAM role already exists and then skip creating new one. #2

san089 opened this issue Jan 30, 2020 · 1 comment
Assignees

Comments

@san089
Copy link
Owner

san089 commented Jan 30, 2020

Check if IAM role already exists and then skip creating a new one.

try:
        create_response = iam_client.create_role(
                    Path='/',
                    RoleName=role_name,
                    Description=role_description,
                    AssumeRolePolicyDocument = role_policy_document
        )
        logger.debug(f"Got response from IAM client for creating role : {create_response}")
        logger.info(f"Role create response code : {create_response['ResponseMetadata']['HTTPStatusCode']}")
    except Exception as e:
        logger.error(f"Error occured while creating role : {e}")
        return False
@san089 san089 self-assigned this Jan 30, 2020
@BestuSingh
Copy link

In order to check it, you can use 'get_role' method of the 'boto3' IAM client. here is the code:

`import boto3
import logging

Initialize logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

Initialize IAM client

iam_client = boto3.client('iam')

def ensure_iam_role(role_name, role_description, role_policy_document):
try:
# Check if the role already exists
logger.info(f"Checking if IAM role '{role_name}' exists...")
response = iam_client.get_role(RoleName=role_name)
logger.info(f"Role '{role_name}' already exists. Skipping creation.")
return True # Role exists
except iam_client.exceptions.NoSuchEntityException:
# Role does not exist, proceed to create it
try:
logger.info(f"Role '{role_name}' does not exist. Creating a new one...")
create_response = iam_client.create_role(
Path='/',
RoleName=role_name,
Description=role_description,
AssumeRolePolicyDocument=role_policy_document
)
logger.debug(f"Got response from IAM client for creating role: {create_response}")
logger.info(f"Role create response code: {create_response['ResponseMetadata']['HTTPStatusCode']}")
return True # Role created successfully
except Exception as e:
logger.error(f"Error occurred while creating role: {e}")
return False # Role creation failed
except Exception as e:
# Handle other exceptions from get_role
logger.error(f"Unexpected error occurred while checking role: {e}")
return False
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants