How to use sts_client method in localstack

Best Python code snippet using localstack_python

update_role.py

Source:update_role.py Github

copy

Full Screen

1import os2import boto33import botocore4import logging5import json6role_name="KB-AuditFramework-TaskExecutionRole"7role_name_1="KB-AuditFramework-ContainerScan-Role"8role_name_2="KB-AuditFramework-TaskRole"9aws_service = "iam"10account_num = ""11target_region="us-east-1"12logger = logging.getLogger()13policy_name_1='KB-AuditFramework-CloudWatch-Access'14policy_name_2="KB-AuditFramework-ContainerScan-AssumeRole-Policy"15policy_name_3="KB-AuditFramework-ContainerScan-Logging-Policy"16policy_name_4="KB-AuditFramework-ServiceCatalog-Access"17policy_name_5="KB-AuditFramework-ECS-Access"18policy_name_6="KB-AuditFramework-S3-Access"19policy_name_7="KB-AuditFramework-SSM-Access"20policy_name_8="KB-AuditFramework-SecurityHub-Access"21policy_name_9="KB-AuditFramework-AssumeRole-To-SecretsManager-ReadRole"22policy_name_10="KB-AuditFramework-Publish-To-SNSTopic"23def lambda_handler(event, context):24 try:25 sts = boto3.client("sts") 26 logger.info(f"Starting scan of new account {account_num}")27 logger.info(f"account_num: {account_num}")28 role_arn = f"arn:aws:iam::{account_num}:role/KB_assumed_role"29 sts_auth = sts.assume_role(RoleArn=role_arn, RoleSessionName="acquired_account_role")30 credentials = sts_auth["Credentials"]31 32 # ----------------------------- #33 # Place all service code below34 # ----------------------------- #35 # Section for boto3 connection with aws service36 sts_client = boto3.client(aws_service,37 region_name=target_region,38 aws_access_key_id=credentials["AccessKeyId"],39 aws_secret_access_key=credentials["SecretAccessKey"],40 aws_session_token=credentials["SessionToken"], )41 try:42 response = sts_client.get_role(43 RoleName=role_name44 ) 45 if len(response["Role"]) > 0:46 policy_document_1={47 "Version": "2012-10-17",48 "Statement": [49 {50 "Effect": "Allow",51 "Action": [52 "logs:CreateLogGroup"53 ],54 "Resource": "*"55 }]}56 57 template_policy =json.dumps(policy_document_1)58 template_policy = str(template_policy)59 try:60 response = sts_client.create_policy(61 PolicyName=policy_name_1,62 PolicyDocument=template_policy,63 Description='string'64 )65 response =sts_client.attach_role_policy(66 RoleName=role_name,67 PolicyArn="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy") 68 response2 =sts_client.attach_role_policy(69 RoleName=role_name,70 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_1}")71 72 except botocore.exceptions.ClientError as error:73 response =sts_client.attach_role_policy(74 RoleName=role_name,75 PolicyArn="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy") 76 77 response2 =sts_client.attach_role_policy(78 RoleName=role_name,79 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_1}")80 81 82 except botocore.exceptions.ClientError as error:83 json_file= {84 "Version": "2012-10-17",85 "Statement": [86 {87 "Effect": "Allow",88 "Principal": {89 "Service": "ecs-tasks.amazonaws.com"90 },91 "Action": "sts:AssumeRole",92 "Condition": {}93 }94 ]95 }96 97 template = json.dumps(json_file)98 template = str(template)99 100 policy_document_1={101 "Version": "2012-10-17",102 "Statement": [103 {104 "Effect": "Allow",105 "Action": [106 "logs:CreateLogGroup"107 ],108 "Resource": "*"109 }]}110 111 template_policy =json.dumps(policy_document_1)112 template_policy = str(template_policy)113 114 try:115 response = sts_client.create_policy(116 PolicyName=policy_name_1,117 PolicyDocument=template_policy,118 Description='string'119 )120 role = sts_client.create_role(121 RoleName =role_name,122 AssumeRolePolicyDocument = template123 )124 response =sts_client.attach_role_policy(125 RoleName=role_name,126 PolicyArn="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy") 127 response2 =sts_client.attach_role_policy(128 RoleName=role_name,129 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_1}") 130 131 except botocore.exceptions.ClientError as error:132 role = sts_client.create_role(133 RoleName =role_name,134 AssumeRolePolicyDocument = template135 )136 response =sts_client.attach_role_policy(137 RoleName=role_name,138 PolicyArn="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy")139 response2 =sts_client.attach_role_policy(140 RoleName=role_name,141 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_1}") 142 try:143 response = sts_client.get_role(144 RoleName=role_name_1145 ) 146 if len(response["Role"]) > 0:147 policy_document_2={148 "Version": "2012-10-17",149 "Statement": [150 {151 "Effect": "Allow",152 "Action": [153 "sts:AssumeRole"154 ],155 "Resource": "arn:aws:iam::*:role/KB-AuditFramework-ContainerScan-AssumeRole"156 }157 ]158 }159 160 template_policy_2 =json.dumps(policy_document_2)161 template_policy_2 = str(template_policy_2)162 policy_document_3={163 "Version": "2012-10-17",164 "Statement": [165 {166 "Effect": "Allow",167 "Action": [168 "kinesis:PutRecord"169 ],170 "Resource": f"arn:aws:kinesis:*:{account_num}:stream/kb-*"171 }172 ]173 }174 175 template_policy_3 =json.dumps(policy_document_3)176 template_policy_3 = str(template_policy_3) 177 try:178 response = sts_client.create_policy(179 PolicyName=policy_name_2,180 PolicyDocument=template_policy_2,181 Description='string'182 )183 response = sts_client.create_policy(184 PolicyName=policy_name_3,185 PolicyDocument=template_policy_3,186 Description='string'187 ) 188 response =sts_client.attach_role_policy(189 RoleName=role_name_1,190 PolicyArn="arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess")191 192 response2 =sts_client.attach_role_policy(193 RoleName=role_name_1,194 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_2}")195 response3 =sts_client.attach_role_policy(196 RoleName=role_name_1,197 PolicyArn="arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly")198 response4 =sts_client.attach_role_policy(199 RoleName=role_name_1,200 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_3}")201 202 203 except botocore.exceptions.ClientError as error:204 response =sts_client.attach_role_policy(205 RoleName=role_name_1,206 PolicyArn="arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess")207 208 response2 =sts_client.attach_role_policy(209 RoleName=role_name_1,210 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_2}")211 response3 =sts_client.attach_role_policy(212 RoleName=role_name_1,213 PolicyArn="arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly") 214 response4 =sts_client.attach_role_policy(215 RoleName=role_name_1,216 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_3}") 217 218 except botocore.exceptions.ClientError as error:219 json_file_1= {220 "Version": "2012-10-17",221 "Statement": [222 {223 "Effect": "Allow",224 "Principal": {225 "Service": "ec2.amazonaws.com"226 },227 "Action": "sts:AssumeRole",228 "Condition": {}229 }230 ]231 }232 233 template_1 = json.dumps(json_file_1)234 template_1 = str(template_1)235 236 policy_document_2={237 "Version": "2012-10-17",238 "Statement": [239 {240 "Effect": "Allow",241 "Action": [242 "sts:AssumeRole"243 ],244 "Resource": "arn:aws:iam::*:role/KB-AuditFramework-ContainerScan-AssumeRole"245 }246 ]247 }248 249 template_policy_2 =json.dumps(policy_document_2)250 template_policy_2 = str(template_policy_2)251 policy_document_3={252 "Version": "2012-10-17",253 "Statement": [254 {255 "Effect": "Allow",256 "Action": [257 "kinesis:PutRecord"258 ],259 "Resource": f"arn:aws:kinesis:*:{account_num}:stream/kb-*"260 }261 ]262 }263 264 template_policy_3 =json.dumps(policy_document_3)265 template_policy_3 = str(template_policy_3) 266 try:267 response = sts_client.create_policy(268 PolicyName=policy_name_2,269 PolicyDocument=template_policy_2,270 Description='string'271 )272 response = sts_client.create_policy(273 PolicyName=policy_name_3,274 PolicyDocument=template_policy_3,275 Description='string'276 ) 277 role = sts_client.create_role(278 RoleName =role_name_1,279 AssumeRolePolicyDocument = template_1 280 ) 281 response =sts_client.attach_role_policy(282 RoleName=role_name_1,283 PolicyArn="arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess")284 285 response2 =sts_client.attach_role_policy(286 RoleName=role_name_1,287 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_2}")288 response3 =sts_client.attach_role_policy(289 RoleName=role_name_1,290 PolicyArn="arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly")291 response4 =sts_client.attach_role_policy(292 RoleName=role_name_1,293 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_3}") 294 295 296 except botocore.exceptions.ClientError as error:297 role = sts_client.create_role(298 RoleName =role_name_1,299 AssumeRolePolicyDocument = template_1 300 ) 301 response =sts_client.attach_role_policy(302 RoleName=role_name_1,303 PolicyArn="arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess")304 305 response2 =sts_client.attach_role_policy(306 RoleName=role_name_1,307 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_2}")308 response3 =sts_client.attach_role_policy(309 RoleName=role_name_1,310 PolicyArn="arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly")311 response4 =sts_client.attach_role_policy(312 RoleName=role_name_1,313 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_3}") 314 try:315 response = sts_client.get_role(316 RoleName=role_name_2317 ) 318 if len(response["Role"]) > 0:319 policy_document_4={320 "Version": "2012-10-17",321 "Statement": [322 {323 "Effect": "Allow",324 "Action": [325 "servicecatalog:*"326 ],327 "Resource": "*",328 "Condition": {329 "StringEquals": {330 "servicecatalog:roleLevel": "self"331 }332 }333 }334 ]335 }336 337 template_policy_4 =json.dumps(policy_document_4)338 template_policy_4 = str(template_policy_4)339 policy_document_5= {340 "Version": "2012-10-17",341 "Statement": [342 {343 "Effect": "Allow",344 "Action": [345 "ecs:RunTask",346 "ecs:RegisterTaskDefinition",347 "ecs:DescribeTaskDefinition"348 ],349 "Resource": "*"350 },351 {352 "Effect": "Allow",353 "Action": [354 "iam:PassRole"355 ],356 "Resource": [357 "arn:aws:iam::*:role/KB-AuditFramework-TaskRole",358 "arn:aws:iam::*:role/KB-AuditFramework-TaskExecutionRole"359 ],360 "Condition": {361 "StringLike": {362 "iam:PassedToService": "ecs-tasks.amazonaws.com"363 }364 }365 }366 ]367 }368 369 template_policy_5 =json.dumps(policy_document_5)370 template_policy_5 = str(template_policy_5) 371 372 policy_document_6= {373 "Version": "2012-10-17",374 "Statement": [375 {376 "Effect": "Allow",377 "Action": [378 "s3:GetObject"379 ],380 "Resource": "arn:aws:s3:::KbAuditAccountParamBuckets"381 },382 {383 "Effect": "Allow",384 "Action": [385 "s3:PutObject",386 "s3:PutObjectAcl"387 ],388 "Resource": "arn:aws:s3:::KbAuditAccountResultsBuckets" 389 }390 ]391 }392 393 template_policy_6 =json.dumps(policy_document_6)394 template_policy_6 = str(template_policy_6)395 policy_document_7= {396 "Version": "2012-10-17",397 "Statement": [398 {399 "Effect": "Allow",400 "Action": [401 "ssm:PutParameter",402 "ssm:Get*",403 "ssm:DeleteParameter"404 ],405 "Resource": f"arn:aws:ssm:*:{account_num}:parameter/CirrusScan/*"406 407 }408 ]409 }410 411 template_policy_7 =json.dumps(policy_document_7)412 template_policy_7 = str(template_policy_7) 413 policy_document_8= {414 "Version": "2012-10-17",415 "Statement": [416 {417 "Effect": "Allow",418 "Action": [419 "securityhub:BatchImportFindings",420 "securityhub:BatchUpdateFindings"421 ],422 "Resource": "*"423 }424 ]425 }426 427 template_policy_8 =json.dumps(policy_document_8)428 template_policy_8 = str(template_policy_8)429 430 policy_document_9={431 "Version": "2012-10-17",432 "Statement": [433 {434 "Effect": "Allow",435 "Action": [436 "sts:AssumeRole"437 ],438 "Resource": "arn:aws:iam::*:role/KB-AuditFramework-SecretsManagerReadOnlyRole"439 }440 ]441 }442 443 template_policy_9 =json.dumps(policy_document_9)444 template_policy_9 = str(template_policy_9)445 446 policy_document_10= {447 "Version": "2012-10-17",448 "Statement": [449 {450 "Effect": "Allow",451 "Action": [452 "SNS:Publish"453 ],454 "Resource": f"arn:aws:sns:*:{account_num}:AuditSNSTopic"455 456 }457 ]458 }459 template_policy_10 =json.dumps(policy_document_10)460 template_policy_10 = str(template_policy_10)461 462 try:463 response = sts_client.create_policy(464 PolicyName=policy_name_4,465 PolicyDocument=template_policy_4,466 Description='string'467 )468 response = sts_client.create_policy(469 PolicyName=policy_name_5,470 PolicyDocument=template_policy_5,471 Description='string'472 ) 473 response = sts_client.create_policy(474 PolicyName=policy_name_6,475 PolicyDocument=template_policy_6,476 Description='string'477 ) 478 response = sts_client.create_policy(479 PolicyName=policy_name_7,480 PolicyDocument=template_policy_7,481 Description='string'482 ) 483 response = sts_client.create_policy(484 PolicyName=policy_name_8,485 PolicyDocument=template_policy_8,486 Description='string'487 ) 488 response = sts_client.create_policy(489 PolicyName=policy_name_9,490 PolicyDocument=template_policy_9,491 Description='string'492 ) 493 response = sts_client.create_policy(494 PolicyName=policy_name_10,495 PolicyDocument=template_policy_10,496 Description='string'497 ) 498 response =sts_client.attach_role_policy(499 RoleName=role_name_2,500 PolicyArn="arn:aws:iam::aws:policy/SecurityAudit")501 502 response2 =sts_client.attach_role_policy(503 RoleName=role_name_2,504 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_4}")505 response3 =sts_client.attach_role_policy(506 RoleName=role_name_2,507 PolicyArn="arn:aws:iam::aws:policy/ReadOnlyAccess")508 response4 =sts_client.attach_role_policy(509 RoleName=role_name_2,510 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_5}")511 response5 =sts_client.attach_role_policy(512 RoleName=role_name_2,513 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_6}")514 response6 =sts_client.attach_role_policy(515 RoleName=role_name_2,516 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_7}")517 response7 =sts_client.attach_role_policy(518 RoleName=role_name_2,519 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_8}")520 response8 =sts_client.attach_role_policy(521 RoleName=role_name_2,522 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_9}") 523 response9 =sts_client.attach_role_policy(524 RoleName=role_name_2,525 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_10}")526 527 528 529 except botocore.exceptions.ClientError as error:530 response =sts_client.attach_role_policy(531 RoleName=role_name_2,532 PolicyArn="arn:aws:iam::aws:policy/SecurityAudit")533 534 response2 =sts_client.attach_role_policy(535 RoleName=role_name_2,536 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_4}")537 response3 =sts_client.attach_role_policy(538 RoleName=role_name_2,539 PolicyArn="arn:aws:iam::aws:policy/ReadOnlyAccess")540 response4 =sts_client.attach_role_policy(541 RoleName=role_name_2,542 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_5}")543 response5 =sts_client.attach_role_policy(544 RoleName=role_name_2,545 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_6}")546 response6 =sts_client.attach_role_policy(547 RoleName=role_name_2,548 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_7}")549 response7 =sts_client.attach_role_policy(550 RoleName=role_name_2,551 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_8}")552 response8 =sts_client.attach_role_policy(553 RoleName=role_name_2,554 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_9}") 555 response9 =sts_client.attach_role_policy(556 RoleName=role_name_2,557 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_10}")558 559 560 561 except botocore.exceptions.ClientError as error:562 json_file_2= {563 "Version": "2012-10-17",564 "Statement": [565 {566 "Effect": "Allow",567 "Principal": {568 "Service": "ec2.amazonaws.com"569 },570 "Action": "sts:AssumeRole",571 "Condition": {}572 }573 ]574 }575 576 template_2 = json.dumps(json_file_2)577 template_2 = str(template_2)578 579 policy_document_4={580 "Version": "2012-10-17",581 "Statement": [582 {583 "Effect": "Allow",584 "Action": [585 "servicecatalog:*"586 ],587 "Resource": "*",588 "Condition": {589 "StringEquals": {590 "servicecatalog:roleLevel": "self"591 }592 }593 }594 ]595 }596 597 template_policy_4 =json.dumps(policy_document_4)598 template_policy_4 = str(template_policy_4)599 policy_document_5= {600 "Version": "2012-10-17",601 "Statement": [602 {603 "Effect": "Allow",604 "Action": [605 "ecs:RunTask",606 "ecs:RegisterTaskDefinition",607 "ecs:DescribeTaskDefinition"608 ],609 "Resource": "*"610 },611 {612 "Effect": "Allow",613 "Action": [614 "iam:PassRole"615 ],616 "Resource": [617 "arn:aws:iam::*:role/KB-AuditFramework-TaskRole",618 "arn:aws:iam::*:role/KB-AuditFramework-TaskExecutionRole"619 ],620 "Condition": {621 "StringLike": {622 "iam:PassedToService": "ecs-tasks.amazonaws.com"623 }624 }625 }626 ]627 }628 629 template_policy_5 =json.dumps(policy_document_5)630 template_policy_5 = str(template_policy_5) 631 632 policy_document_6= {633 "Version": "2012-10-17",634 "Statement": [635 {636 "Effect": "Allow",637 "Action": [638 "s3:GetObject"639 ],640 "Resource": "arn:aws:s3:::KbAuditAccountParamBuckets"641 },642 {643 "Effect": "Allow",644 "Action": [645 "s3:PutObject",646 "s3:PutObjectAcl"647 ],648 "Resource": "arn:aws:s3:::KbAuditAccountResultsBuckets" 649 }650 ]651 }652 653 template_policy_6 =json.dumps(policy_document_6)654 template_policy_6 = str(template_policy_6)655 policy_document_7= {656 "Version": "2012-10-17",657 "Statement": [658 {659 "Effect": "Allow",660 "Action": [661 "ssm:PutParameter",662 "ssm:Get*",663 "ssm:DeleteParameter"664 ],665 "Resource": f"arn:aws:ssm:*:{account_num}:parameter/CirrusScan/*"666 667 }668 ]669 }670 671 template_policy_7 =json.dumps(policy_document_7)672 template_policy_7 = str(template_policy_7) 673 policy_document_8= {674 "Version": "2012-10-17",675 "Statement": [676 {677 "Effect": "Allow",678 "Action": [679 "securityhub:BatchImportFindings",680 "securityhub:BatchUpdateFindings"681 ],682 "Resource": "*"683 }684 ]685 }686 687 template_policy_8 =json.dumps(policy_document_8)688 template_policy_8 = str(template_policy_8)689 690 policy_document_9={691 "Version": "2012-10-17",692 "Statement": [693 {694 "Effect": "Allow",695 "Action": [696 "sts:AssumeRole"697 ],698 "Resource": "arn:aws:iam::*:role/KB-AuditFramework-SecretsManagerReadOnlyRole"699 }700 ]701 }702 703 template_policy_9 =json.dumps(policy_document_9)704 template_policy_9 = str(template_policy_9)705 706 policy_document_10= {707 "Version": "2012-10-17",708 "Statement": [709 {710 "Effect": "Allow",711 "Action": [712 "SNS:Publish"713 ],714 "Resource": f"arn:aws:sns:*:{account_num}:AuditSNSTopic"715 716 }717 ]718 }719 template_policy_10 =json.dumps(policy_document_10)720 template_policy_10 = str(template_policy_10)721 722 try:723 response = sts_client.create_policy(724 PolicyName=policy_name_4,725 PolicyDocument=template_policy_4,726 Description='string'727 )728 response = sts_client.create_policy(729 PolicyName=policy_name_5,730 PolicyDocument=template_policy_5,731 Description='string'732 ) 733 response = sts_client.create_policy(734 PolicyName=policy_name_6,735 PolicyDocument=template_policy_6,736 Description='string'737 ) 738 response = sts_client.create_policy(739 PolicyName=policy_name_7,740 PolicyDocument=template_policy_7,741 Description='string'742 ) 743 response = sts_client.create_policy(744 PolicyName=policy_name_8,745 PolicyDocument=template_policy_8,746 Description='string'747 ) 748 response = sts_client.create_policy(749 PolicyName=policy_name_9,750 PolicyDocument=template_policy_9,751 Description='string'752 ) 753 response = sts_client.create_policy(754 PolicyName=policy_name_10,755 PolicyDocument=template_policy_10,756 Description='string'757 ) 758 role = sts_client.create_role(759 RoleName =role_name_2,760 AssumeRolePolicyDocument = template_2 761 )762 response =sts_client.attach_role_policy(763 RoleName=role_name_2,764 PolicyArn="arn:aws:iam::aws:policy/SecurityAudit")765 766 response2 =sts_client.attach_role_policy(767 RoleName=role_name_2,768 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_4}")769 response3 =sts_client.attach_role_policy(770 RoleName=role_name_2,771 PolicyArn="arn:aws:iam::aws:policy/ReadOnlyAccess")772 response4 =sts_client.attach_role_policy(773 RoleName=role_name_2,774 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_5}")775 response5 =sts_client.attach_role_policy(776 RoleName=role_name_2,777 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_6}")778 response6 =sts_client.attach_role_policy(779 RoleName=role_name_2,780 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_7}")781 response7 =sts_client.attach_role_policy(782 RoleName=role_name_2,783 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_8}")784 response8 =sts_client.attach_role_policy(785 RoleName=role_name_2,786 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_9}") 787 response9 =sts_client.attach_role_policy(788 RoleName=role_name_2,789 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_10}")790 791 792 793 except botocore.exceptions.ClientError as error:794 role = sts_client.create_role(795 RoleName =role_name_2,796 AssumeRolePolicyDocument = template_2 797 )798 response =sts_client.attach_role_policy(799 RoleName=role_name_2,800 PolicyArn="arn:aws:iam::aws:policy/SecurityAudit")801 802 response2 =sts_client.attach_role_policy(803 RoleName=role_name_2,804 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_4}")805 response3 =sts_client.attach_role_policy(806 RoleName=role_name_2,807 PolicyArn="arn:aws:iam::aws:policy/ReadOnlyAccess")808 response4 =sts_client.attach_role_policy(809 RoleName=role_name_2,810 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_5}")811 response5 =sts_client.attach_role_policy(812 RoleName=role_name_2,813 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_6}")814 response6 =sts_client.attach_role_policy(815 RoleName=role_name_2,816 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_7}")817 response7 =sts_client.attach_role_policy(818 RoleName=role_name_2,819 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_8}")820 response8 =sts_client.attach_role_policy(821 RoleName=role_name_2,822 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_9}") 823 response9 =sts_client.attach_role_policy(824 RoleName=role_name_2,825 PolicyArn=f"arn:aws:iam::{account_num}:policy/{policy_name_10}") 826 except botocore.exceptions.ClientError as error:827 logger.error(f"Error: {error}")828 error_message = error.response["Error"]["Message"]829 sns_client = boto3.client("sns")830 sns_client.publish (831 TopicArn = f"arn:aws:sns:us-east-1:{account_num}:KB_Send_Failure_Notification_Topic",832 Message = f"An error has occured during the scanning process of account {account_num}. The error is: {error_message}",833 Subject = f"Error occured in running scan of {aws_service} on account {account_num}."834 )...

Full Screen

Full Screen

test_logtron_aws.py

Source:test_logtron_aws.py Github

copy

Full Screen

...167 discover_context=lambda: discover_context(sts_client=MockSTSClient(), refresh=True),168 )169 logger.info("test_cloudwatch_emf_non_flatten", extra={"kind": "test", "value": 123})170 flush()171def test_cloudwatch_sts_client():172 config = {173 "handlers": ["logtron_aws.CloudWatchHandler"],174 "CloudWatchHandler": {175 "logs_client": MockLogsClient(),176 "interval_sec": 30,177 },178 }179 logger = autodiscover(refresh=True, config=config, sts_client=MockSTSClient())180 logger.info("test_cloudwatch_sts_client", extra={"test123": 123})181 flush()182def test_cloudwatch_close():183 config = {184 "handlers": ["logtron_aws.CloudWatchHandler"],185 "CloudWatchHandler": {...

Full Screen

Full Screen

sts.py

Source:sts.py Github

copy

Full Screen

1from secrets import token_hex2from boto3 import (3 client as boto3_client,4 Session as boto3_session,5)6def assumed_role_session(sts_client=None, session_kwargs=None, **assume_role_kwargs):7 """Return a ``boto3.Session`` object for an assumed role:8 * *sts_client* is a ``boto3.client('sts')`` instance. If not given, one will be9 created with ``boto3.client('sts')``.10 * *session_kwargs* are the keyword arguments you want to pass to the11 ``boto3.Session()`` constructor.12 * *assume_role_kwargs* are the arguments for the ``assume_role`` operation, which13 at least include ``RoleArn``. If ``RoleSessionName`` is not given, a14 randomly-generated one will be used.15 Usage:16 .. code-block:: python17 from boto3_helpers.sts import assumed_role_session18 role_arn = 'arn:aws:iam::000000000000:role/TargetRole'19 session = assumed_role_session(RoleArn=role_arn)20 This is equivalent to:21 .. code-block:: python22 from boto3 import (23 client as boto3_client,24 Session as boto3_session,25 )26 sts_client = boto3_client('sts')27 role_arn = 'arn:aws:iam::000000000000:role/TargetRole'28 session_name = 'AssumedRoleSession1'29 resp = sts_client.assume_role(30 RoleArn=role_arn, RoleSessionName=session_name31 )32 credentials = resp['credentials']33 session = boto3_session(34 aws_access_key_id=credentials['AccessKeyId'],35 aws_secret_access_key=credentials['SecretAccessKey'],36 aws_session_token=credentials['SessionToken'],37 )38 """39 sts_client = sts_client or boto3_client('sts')40 session_kwargs = session_kwargs or {}41 assume_role_kwargs.setdefault('RoleSessionName', token_hex(4))42 credentials = sts_client.assume_role(**assume_role_kwargs)['Credentials']43 return boto3_session(44 aws_access_key_id=credentials['AccessKeyId'],45 aws_secret_access_key=credentials['SecretAccessKey'],46 aws_session_token=credentials['SessionToken'],47 **session_kwargs,48 )49def assumed_role_client(50 service_name, *, sts_client=None, client_kwargs=None, **assume_role_kwargs51):52 """Return a ``boto3.client`` object for an assumed role:53 * *service_name* is the name of a service.54 * *sts_client* is a ``boto3.client('sts')`` instance. If not given, one will be55 created with ``boto3.client('sts')``.56 * *client_kwargs* are the keyword arguments you want to pass to the57 ``boto3.client()`` constructor.58 * *assume_role_kwargs* are the arguments for the ``assume_role`` operation, which59 at least include ``RoleArn``. If ``RoleSessionName`` is not given, a60 randomly-generated one will be used.61 Usage:62 .. code-block:: python63 from boto3_helpers.sts import assumed_role_client64 client_kwargs = {'region_name': 'us-east-2'}65 role_arn = 'arn:aws:iam::000000000000:role/TargetRole'66 sqs_client = assumed_role_client(67 'sqs', client_kwargs, RoleArn=role_arn68 )69 """70 client_kwargs = client_kwargs or {}71 session = assumed_role_session(sts_client=sts_client, **assume_role_kwargs)72 return session.client(service_name, **client_kwargs)73def assumed_role_resource(74 service_name, *, sts_client=None, resource_kwargs=None, **assume_role_kwargs75):76 """Return a ``boto3.resource`` object for an assumed role:77 * *service_name* is the name of a service.78 * *sts_client* is a ``boto3.client('sts')`` instance. If not given, one will be79 created with ``boto3.client('sts')``.80 * *resource_kwargs* are the keyword arguments you want to pass to the81 ``boto3.resource()`` constructor.82 * *assume_role_kwargs* are the arguments for the ``assume_role`` operation, which at83 least include ``RoleArn``. If ``RoleSessionName`` is not given, a84 randomly-generated one will be used.85 Usage:86 .. code-block:: python87 from boto3_helpers.sts import assumed_role_resource88 resource_kwargs = {'region_name': 'us-east-2'}89 role_arn = 'arn:aws:iam::000000000000:role/TargetRole'90 dynamodb_resource = assumed_role_resource(91 'dynamodb', resource_kwargs, RoleArn=role_arn92 )93 """94 resource_kwargs = resource_kwargs or {}95 session = assumed_role_session(sts_client, **assume_role_kwargs)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful