Last active
March 28, 2023 03:09
-
-
Save ramtamilan/1dbc840ce14be66f6c63b14ca4e78e0f to your computer and use it in GitHub Desktop.
This file contains 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
##Import Libraries | |
import json | |
import boto3 | |
import jmespath | |
## Recieve event from Cloud watch Event bus | |
## Variable "ID" get the instance id which triggered the alert. | |
## Variable "Sourceaccount" gets the account information from where the Cloudwatch rule triggered. | |
def lambda_handler(event, context): | |
print('Input received:') | |
print(json.dumps(event, indent=4)) | |
print('Instance ID:', event['detail']['requestParameters']['instancesSet']['items'][0]['instanceId']) | |
ID = ('Instance ID:', event['detail']['requestParameters']['instancesSet']['items'][0]['instanceId']) | |
print(ID) | |
Sourceaccount = event['account'] | |
print('Sourceaccount',Sourceaccount) | |
## AssumeRole | |
## replace "cross-accounrole" in Line 22 with your role created in each account | |
sts_connection = boto3.client('sts') | |
acct_b = sts_connection.assume_role( | |
RoleArn='arn:aws:iam::' + Sourceaccount + ':role/cross-account-role', | |
RoleSessionName='cross_acct_lambda' | |
) | |
ACCESS_KEY = acct_b['Credentials']['AccessKeyId'] | |
SECRET_KEY = acct_b['Credentials']['SecretAccessKey'] | |
SESSION_TOKEN = acct_b['Credentials']['SessionToken'] | |
## Get the tag information | |
ec2_client = boto3.client('ec2', region_name='us-east-2', | |
aws_access_key_id=ACCESS_KEY, | |
aws_secret_access_key=SECRET_KEY, | |
aws_session_token=SESSION_TOKEN,) | |
Inst = [event['detail']['requestParameters']['instancesSet']['items'][0]['instanceId']] | |
print(Inst) | |
myinstance = ec2_client.describe_instances(InstanceIds = Inst) | |
GetTag = (jmespath.search("Reservations[].Instances[].[Tags[?Key=='Name'].Value]",myinstance)) | |
Tag = (GetTag[0][0][0]) | |
print(Tag) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment