Best Python code snippet using localstack_python
service_bootstrap.py
Source:service_bootstrap.py
...66 f"Subnet we just created '{subnet_id}' is not available. current state: {subnet_state}",67 )68 logging.info(f"Created VPC Subnet {subnet_id}")69 return subnet_id70def create_service_linked_role(iam) -> str:71 # TODO(jaypipes): There does not seem to be any way at all to list or72 # describe service-linked-roles in IAM. So, the only way to make this work73 # is just to check for an error when trying to create the service linked74 # role to see if one with the same name already "has been taken in this75 # account" (whatever that means).76 #77 # Once again, IAM proves why we can't have nice things.78 try:79 resp = iam.create_service_linked_role(80 AWSServiceName="es.amazonaws.com",81 Description="An SLR to allow Amazon Elasticsearch Service to work within a private VPC.",82 )83 slr_name = resp['Role']['RoleName']84 logging.info(f"Created service-linked role {slr_name}")85 except iam.exceptions.InvalidInputException as e:86 if "Service role name AWSServiceRoleForAmazonElasticsearchService has been taken in this account" in str(e):87 logging.info(f"Service-linked role AWSServiceRoleForAmazonElasticsearchService already exists")88 return "AWSServiceRoleForAmazonElasticsearchService"89 raise e90 return slr_name91def service_bootstrap() -> dict:92 logging.getLogger().setLevel(logging.INFO)93 region = identity.get_region()94 ec2 = boto3.client("ec2", region_name=region)95 iam = boto3.client("iam", region_name=region)96 # only normal zones, no localzones97 azs = map(lambda zone: zone['ZoneName'],98 filter(lambda zone: zone['OptInStatus'] == 'opt-in-not-required', ec2.describe_availability_zones()['AvailabilityZones']))99 vpc_id = create_vpc(ec2)100 subnets = [create_subnet(ec2, vpc_id, az, cidr) for (cidr,az) in zip(VPC_SUBNET_CIDR_BLOCK, azs)]101 slr_name = create_service_linked_role(iam)102 return TestBootstrapResources(103 vpc_id,104 subnets,105 slr_name,106 ).__dict__107if __name__ == "__main__":108 config = service_bootstrap()...
service_linked_roles.py
Source:service_linked_roles.py
...13logger = logging.getLogger(__name__)14iam = boto3.resource('iam')15# snippet-end:[python.example_code.iam.service_linked_roles.imports]16# snippet-start:[python.example_code.iam.CreateServiceLinkedRole]17def create_service_linked_role(service_name, description):18 """19 Creates a service-linked role.20 :param service_name: The name of the service that owns the role.21 :param description: A description to give the role.22 :return: The newly created role.23 """24 try:25 response = iam.meta.client.create_service_linked_role(26 AWSServiceName=service_name, Description=description)27 role = iam.Role(response['Role']['RoleName'])28 logger.info("Created service-linked role %s.", role.name)29 except ClientError:30 logger.exception("Couldn't create service-linked role for %s.", service_name)31 raise32 else:33 return role34# snippet-end:[python.example_code.iam.CreateServiceLinkedRole]35def usage_demo():36 print('-'*88)37 print("Welcome to the IAM service-linked role demo!")38 print('-'*88)39 logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')40 service_name = input(41 "Enter the name of a service to create a service-linked role.\n"42 "For example, 'elasticbeanstalk.amazonaws.com' or 'batch.amazonaws.com': ")43 role = create_service_linked_role(service_name, "Service-linked role demo.")44 policy = list(role.attached_policies.all())[0]45 print(f"The policy document for {role.name} is:")46 pprint(policy.default_version.document)47 if role is not None:48 answer = input(49 "Do you want to delete the role? You should only do this if you are sure "50 "it is not being used. (y/n)? ")51 if answer.lower() == 'y':52 try:53 response = iam.meta.client.delete_service_linked_role(RoleName=role.name)54 task_id = response['DeletionTaskId']55 while True:56 response = iam.meta.client.get_service_linked_role_deletion_status(57 DeletionTaskId=task_id)...
test_create_service_linked_role.py
Source:test_create_service_linked_role.py
1# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.2# SPDX-License-Identifier: Apache-2.03import pytest4import os5import boto36from moto import mock_iam7@pytest.fixture8def iam_client():9 with mock_iam():10 region = os.environ.get("AWS_REGION")11 iam = boto3.client("iam", region_name=region)12 yield13def test_lambda_function(iam_client):14 import create_service_linked_role15 # Create a service linked role in a brand new account16 result = create_service_linked_role.lambda_handler(17 {18 "RequestType": "Create",19 },20 None,21 )22 # Expect Execute successfully....
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!