Best Python code snippet using localstack_python
ecs_setup.py
Source:ecs_setup.py  
...111		print(e)112	else:113		print('Instance profile %s created'%instance_profile_name)114# Add role to instance profile115def add_role_to_instance_profile(instance_profile_name, role_name):116	try:117		iam_client.add_role_to_instance_profile(118			InstanceProfileName= instance_profile_name,119			RoleName= role_name120		)121	except botocore.exceptions.ClientError as e:122		print(e)123	else:124		print('Role added to instance profile')125def add_to_config(keypairName, sgID, role1ARN, role2ARN, role3ARN, role4ARN):126	data = {'ecs_information': {'keypair_name': str(keypairName), 'security_group_ID': str(sgID), 'ecsInstanceRole_arn' : str(role1ARN), 'ecsTaskExecutionRole_arn' : str(role2ARN), 'ecsS3InputBucketAccess_arn' : str(role3ARN), 'ecsS3OutputBucketAccess_arn' : str(role4ARN)}}127	config_file = open('ecs_config.yml', 'w')128	yaml.dump(data, config_file)129	print('ecs_config file created')130# Create key pair 131key_name = create_keypair('ecs_key')132# Create ECS security group133security_group_id = create_security_group('Security group for ECS Scenario 2', 'ECS group')134# Defining a security group rule - this allows SSH access to the instance 135ipPermissions =[136		{137			'FromPort': 22,138			'IpProtocol': 'tcp',139			'IpRanges': [140				{141					'CidrIp': '0.0.0.0/0',142					'Description': 'SSH access',143				},144			],145			'ToPort': 22,146		}147	]148# Adding rule to the security group 149create_sg_rule(security_group_id, ipPermissions)150# Creating an IAM role for EC2 to access S3 151# Create a trust permission for both EC2 and ECS-Tasks (giving EC2 and ecs-tasks ability to take on the role created)152ecs_task_role_access = {153  "Version": "2012-10-17",154  "Statement": [155	{156	  "Sid": "",157	  "Effect": "Allow",158	  "Principal": {159		"Service": "ecs-tasks.amazonaws.com"160	  },161	  "Action": "sts:AssumeRole"162	}163  ]164}165ec2_role_access = {166  "Version": "2012-10-17",167  "Statement": [168	{169	  "Sid": "",170	  "Effect": "Allow",171	  "Principal": {172		"Service": "ec2.amazonaws.com"173	  },174	  "Action": "sts:AssumeRole"175	}176  ]177}178# Creating the four required roles:179ecsInstanceRole = {180'RoleName':'ecsInstanceRole',181'AssumeRolePolicyDocument' : json.dumps(ec2_role_access),182'Description':'Role to give EC2 access to Amazon EC2 Container Service.',183'MaxSessionDuration' : 43200}184ecsTaskExecutionRole = {185'RoleName':'ecsTaskExecutionRole',186'AssumeRolePolicyDocument' : json.dumps(ecs_task_role_access),187'Description':'Role to provide access to other AWS service resources that are required to run Amazon ECS tasks',188'MaxSessionDuration' : 43200}189ecsS3InputBucketAccess = {190'RoleName':'ecsS3InputBucketAccess',191'AssumeRolePolicyDocument' : json.dumps(ecs_task_role_access),192'Description':'Role to provide access to input bucket to ecs tasks',193'MaxSessionDuration' : 43200}194ecsS3OutputBucketAccess = {195'RoleName':'ecsS3OutputBucketAccess',196'AssumeRolePolicyDocument' : json.dumps(ecs_task_role_access),197'Description':'Role to provide access to output bucket to ecs tasks',198'MaxSessionDuration' : 43200}199# Creating the roles200ecsInstanceRole_arn, ecsInstanceRole_name = create_iam_role(**ecsInstanceRole)201ecsTaskExecutionRole_arn, ecsTaskExecutionRole_name = create_iam_role(**ecsTaskExecutionRole)202ecsS3InputBucketAccess_arn, ecsS3InputBucketAccess_name = create_iam_role(**ecsS3InputBucketAccess)203ecsS3OutputBucketAccess_arn, ecsS3OutputBucketAccess_name = create_iam_role(**ecsS3OutputBucketAccess)204# Adding the aws managed policies to ecsInstanceRole and ecsTaskExecutionRole205add_policy('arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role', ecsInstanceRole_name)206add_policy('arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy', ecsTaskExecutionRole_name)207# Create policies for ecsS3InputBucketAccess and ecsS3OutputBucketAccess roles208input_bucket_access = {209  "Version": "2012-10-17",210  "Statement": [211    {212      "Effect": "Allow",213      "Action": ["s3:ListBucket"],214      "Resource": [input_bucket]215    },216    {217      "Effect": "Allow",218      "Action": [219        "s3:GetObject"220      ],221      "Resource": [input_bucket_files]222    }223  ]224}225output_bucket_access = {226   "Version":"2012-10-17",227   "Statement":[228	  {229		 "Effect":"Allow",230		 "Action":[231			"s3:ListBucket"232		 ],233		 "Resource": [output_bucket]234	  },235	  {236		 "Effect":"Allow",237		 "Action":[238			"s3:PutObject"239		 ],240		 "Resource": [output_bucket_files]241	  }242   ]243}244input_policy = create_policy('ecsS3InputBucketAccess_policy', input_bucket_access)245output_policy = create_policy('ecsS3OutputBucketAccess_policy', output_bucket_access)246# Adding the created policies to ecsS3InputBucketAccess and ecsS3OutputBucketAccess roles247add_policy(input_policy, ecsS3InputBucketAccess_name)248add_policy(output_policy , ecsS3OutputBucketAccess_name)249# Create instance profiles and add roles -> Name of instance profile == same as role name (makes it easier and is how this occurs if done through the console)250# ecsInstanceRole 251create_instance_profile(ecsInstanceRole_name)252add_role_to_instance_profile(ecsInstanceRole_name, ecsInstanceRole_name)253# ecsTaskExecutionRole254create_instance_profile(ecsTaskExecutionRole_name)255add_role_to_instance_profile(ecsTaskExecutionRole_name, ecsTaskExecutionRole_name)256# ecsS3InputBucketAccess257create_instance_profile(ecsS3InputBucketAccess_name)258add_role_to_instance_profile(ecsS3InputBucketAccess_name, ecsS3InputBucketAccess_name)259# ecsS3OutputBucketAccess260create_instance_profile(ecsS3OutputBucketAccess_name)261add_role_to_instance_profile(ecsS3OutputBucketAccess_name, ecsS3OutputBucketAccess_name)262# Load information into config file: ...instance_profile.py
Source:instance_profile.py  
...60        '''61        self.logger.debug('Deleting %s with parameters: %s'62                          % (self.type_name, params))63        self.client.delete_instance_profile(**params)64    def add_role_to_instance_profile(self, params=None):65        '''66            Adds a role to an AWS IAM Profile.67        '''68        self.logger.debug('Add role to %s with parameters: %s'69                          % (self.type_name, params))70        self.client.add_role_to_instance_profile(**params)71    def remove_role_from_instance_profile(self, params=None):72        '''73            Remove a role from an AWS IAM Profile.74        '''75        self.logger.debug('Remove role from %s with parameters: %s'76                          % (self.type_name, params))77        self.client.remove_role_from_instance_profile(**params)78@decorators.aws_resource(IAMInstanceProfile,79                         RESOURCE_TYPE,80                         waits_for_status=False)81def create(ctx, iface, resource_config, **_):82    '''Creates an AWS IAM Profile'''83    resource_id = \84        utils.get_resource_id(85            ctx.node,86            ctx.instance,87            resource_config.get(RESOURCE_NAME),88            use_instance_id=True89        ) or iface.resource_id90    resource_config[RESOURCE_NAME] = resource_id91    utils.update_resource_id(ctx.instance, resource_id)92    role_name = resource_config.pop('RoleName', None)93    create_response = iface.create(resource_config)94    resource_id = create_response['InstanceProfile'][RESOURCE_NAME]95    iface.update_resource_id(resource_id)96    utils.update_resource_id(ctx.instance, resource_id)97    utils.update_resource_arn(98        ctx.instance, create_response['InstanceProfile']['Arn'])99    role_name = role_name or \100        utils.find_resource_id_by_type(ctx.instance,101                                       IAM_ROLE_TYPE)102    if role_name:103        add_role_params = {104            RESOURCE_NAME: iface.resource_id,105            'RoleName': role_name106        }107        iface.add_role_to_instance_profile(add_role_params)108        ctx.instance.runtime_properties['RoleName'] = role_name109@decorators.aws_resource(IAMInstanceProfile,110                         RESOURCE_TYPE,111                         waits_for_status=False)112def delete(ctx, iface, resource_config, **_):113    '''Deletes an AWS IAM Profile'''114    instance_profile_name = resource_config.get(RESOURCE_NAME)115    if not instance_profile_name:116        instance_profile_name = iface.resource_id117    resource_config[RESOURCE_NAME] = instance_profile_name118    # Path parameter is not accepted by delete_instance_profile.119    try:120        del resource_config['Path']121    except KeyError:...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!!
