Created
August 2, 2021 10:58
-
-
Save BedrosovaYulia/22cb4e254a1d46e758be901df9656454 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if __name__ == "__main__": | |
account_id = boto3.resource('iam').CurrentUser().arn.split(':')[4] | |
# Define Argument Parser | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-i', '--iid', required=True, help='instance id') | |
parser.add_argument('-g', '--sgid', required=False, help='security group id') | |
parser.add_argument('-r', '--region', required=False, help='region') | |
parser.add_argument('-b', '--bucket', required=False, help='bucket') | |
parser.add_argument('-t', '--topic', required=False, help='topic') | |
#разбираю аргумеенты командной строки | |
args = parser.parse_args() | |
AREGION = 'us-west-2' | |
if args.region: | |
AREGION=args.region | |
instance_id = args.iid | |
#проверяю существует ли вообще инстанс с данным ИД | |
instanceid_is_valid(instance_id) | |
ec2Client = boto3.client('ec2', region_name=AREGION) | |
asgClient = boto3.client('autoscaling', region_name=AREGION) | |
ssmClient = boto3.client('ssm', region_name=AREGION) | |
#заливать данные в S3-бакет будем с шифрованием ключем - выбираю ключек | |
kmsClient = boto3.client('kms',region_name=AREGION) | |
kmskeys = kmsClient.list_keys() | |
for cmk in kmskeys["Keys"]: | |
key_info = kmsClient.describe_key(KeyId=cmk["KeyId"]) | |
if key_info["KeyMetadata"]["Description"] == 'test': | |
KEYID = cmk["KeyId"] | |
print(KEYID) | |
break | |
#если название S3-бакета не передано в аргументах, сформируем название сами согласно правилам, принятым в компании | |
BUCKET_NAME = "s3-access-logs."+account_id+"-"+AREGION | |
if args.bucket: | |
BUCKET_NAME = args.bucket | |
#для отправки оповещений будем использовать SNS-топик | |
SNS_TOPIC = "arn:aws:sns:"+AREGION+":"+account_id+":slack-events" | |
if args.topic: | |
SNS_TOPIC = args.topic | |
try: | |
instance_describe_metadata = ec2Client.describe_instances( | |
InstanceIds=[ | |
instance_id | |
], | |
) | |
except ValueError as e: | |
message = 'Unable to get instance metadata' + str(e['ErrorMessage']) | |
VPC_ID = instance_describe_metadata['Reservations'][0]['Instances'][0]['VpcId'] | |
isolateSG = args.sgid | |
#изолируем инстанс в карантинную группу | |
isolate_instance(ec2Client, instance_id, VPC_ID, isolateSG) | |
#делаем скриншот консоли | |
console_screenshot(ec2Client, instance_id) | |
#делаем снапшот дисков | |
snapshot(ec2Client, instance_id) | |
#включаем защиту от удаления, если она еще не включена | |
try: | |
set_termination_protection(ec2Client, instance_id) | |
except: | |
pass | |
#ставим теги | |
set_tags(ec2Client, instance_id) | |
message = 'Security Response mechanism complete for instance: ' + instance_id | |
print(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment