I want to know who created a particular instance. I am using Cloud Trail to find out the statistics, but I am not able to get a particular statistics of who created that instance. I am using Python and Boto3 for finding out the details.
I am using this code- Lookup events() from Cloud trail in boto3, to extract the information about an instance.
ct_conn = sess.client(service_name='cloudtrail',region_name='us-east-1')
events=ct_conn.lookup_events()
I found out the solution to the above problem using lookup_events() function.
ct_conn = boto3.client(service_name='cloudtrail',region_name='us-east-1')
events_dict= ct_conn.lookup_events(LookupAttributes=[{'AttributeKey':'ResourceName', 'AttributeValue':'i-xxxxxx'}])
for data in events_dict['Events']:
json_file= json.loads(data['CloudTrailEvent'])
print json_file['userIdentity']['userName']
#Karthik - Here is the sample of creating session
import boto3
import json
import os
session = boto3.Session(region_name='us-east-1',aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])
ct_conn = session.client(service_name='cloudtrail',region_name='us-east-1')
events_dict= ct_conn.lookup_events(LookupAttributes=[{'AttributeKey':'ResourceName', 'AttributeValue':'i-xxx'}])
for data in events_dict['Events']:
json_file= json.loads(data['CloudTrailEvent'])
print (json_file['userIdentity']['userName'])
Related
Is there a possibility to set a dynamic URI in the AWS API_GATEWAY aws_cdk description?
I currently have:
integration=api_gateway.Integration(
type=_apigw.IntegrationType.HTTP,
integration_http_method='GET',
uri=my_uri+'/my_service/my_fixed_endpoint',
...
Now I would like to use something like:
uri=my_uri+'/my_service/{my_dynamic_endpoint}',
With {my_dynamic_endpoint} being replaced with e.g. "football", "baseball", "tennis".
Is there a way to do this?
I think I found my answer in the aws api gateway docs. There, they use the following example:
api = apigateway.RestApi(self, "books-api")
api.root.add_method("ANY")
book = books.add_resource("{book_id}")
book.add_method("GET")
book.add_method("DELETE")
So I should write it in an object based manner like that
api = apigateway.RestApi(self, "sports-api")
api.root.add_method("ANY")
book = books.add_resource("{sport}")
book.add_method("GET")
book.add_method("DELETE")
What I called "my_dynamic_endpoint" is just a variable in the url path.
Sorry for the misleading formulations!!!
I'm trying to update a docker image within a deployment in EKS. I'm running a python code from a lambda function. However, I don't know how to use generate_presigned_url(). What should I pass as ClientMethod parameter???
import boto3
client = boto3.client("eks")
url = client.generate_presigned_url()
These are the clientMethods that you could perform in case of EKS.
'associate_encryption_config'
'associate_identity_provider_config'
'can_paginate'
'create_addon'
'create_cluster'
'create_fargate_profile'
'create_nodegroup'
'delete_addon'
'delete_cluster'
'delete_fargate_profile'
'delete_nodegroup'
'describe_addon'
'describe_addon_versions'
'describe_cluster'
'describe_fargate_profile'
'describe_identity_provider_config'
'describe_nodegroup'
'describe_update'
'disassociate_identity_provider_config'
'generate_presigned_url'
'get_paginator'
'get_waiter'
'list_addons'
'list_clusters'
'list_fargate_profiles'
'list_identity_provider_configs'
'list_nodegroups'
'list_tags_for_resource'
'list_updates'
'tag_resource'
'untag_resource'
'update_addon'
'update_cluster_config'
'update_cluster_version'
'update_nodegroup_config'
'update_nodegroup_version'
You can get more information about these method in the documentation here: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/eks.html#client
After over two weeks I suppose you've found your answer, anyway the ClientMethod mentioned (and, not really well explained on the boto3 docs) is just one of the methods you can use with the EKS client itself. I honestly think this is what KnowledgeGainer was trying to say by listing all the methods, basically you can just pick one. This would give you the presigned URL.
For example, here I'm using one method that isn't requiring any additional arguments, list_clusters:
>>> import boto3
>>> client = boto3.client("eks")
>>> client.generate_presigned_url("list_clusters")
'https://eks.eu-west-1.amazonaws.com/clusters?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQKOXLHHBFT756PNG%2F20210528%2Feu-west-1%2Feks%2Faws4_request&X-Amz-Date=20210528T014603Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=d25dNCC17013ad9bc75c04b6e067105c23199c23cbadbbbeForExample'
If the method requires any additional arguments, you add those into Params as a dictionary:
>>> method_params = {'name': <your_cluster_name>}
>>> client.generate_presigned_url('describe_cluster', Params=method_params)
I am developing a script in Python for deleting old AMIs and its snapshots. For testing purposes, I have been trying to create and right after deleting an AMI. My code for creating the instance is the following (including the addition of tags at the end):
import boto3
from datetime import datetime, timedelta
import time
today = datetime.utcnow().strftime('%Y%m%d')
remove_on = (datetime.utcnow() + timedelta(days=3)).strftime('%Y%m%d')
session = boto3.session.Session(region_name='eu-west-1')
client = session.client('ec2')
ec2 = session.resource('ec2')
instance_info = client.describe_instances(Filters=[{'Name': 'tag:Name',
'Values': ['Airflow']}]) #This filter DOES work
instance_id = instance_info['Reservations'][0]['Instances'][0]['InstanceId']
instance = ec2.Instance(instance_id)
image = instance.create_image(InstanceId=instance_id, Name=f"Airflow_{today}")
time.sleep(2)
image.create_tags(Tags=[{'Key': 'RemoveOn', 'Value': remove_on},
{'Key': 'BackupOf', 'Value': 'Airflow'}])
However, when I try to get the info of the recent created AMI, I get no data:
instances_to_delete = client.describe_instances(Filters=[{'Name': 'tag:RemoveOn',
'Values':[remove_on]}])
I have tried to explicitly put a string in Values but it does not work either. Also, even though it didn't make much sense (since I already had one filter working previously), I specified the region in client also (because of these answers Boto3 ec2 describe_instances always returns empty) and it doesn't work.
The tag is there as we can see in the following screenshot
Your code seems to be creating an image (AMI) and then putting a tag on the AMI.
Then, you are saying that it is unable to find the instance with that tag. That makes sense, because only the image was tagged, not the instance.
I created an alarm and want to delete it afterward...
The documentation for boto 2 doesn't show how to do that.
Any help ?
Thanks
If you want to delete alarms, the API you need is DeleteAlarms. The link you have in your question is mentioning it (search for delete_alarms).
Also, boto 3 is the recommended version to use and here is the API you need: https://boto3.readthedocs.io/en/latest/reference/services/cloudwatch.html#CloudWatch.Client.delete_alarms
Example of how to do it with Boto 3:
import boto3
client = boto3.client('cloudwatch')
client.delete_alarms(AlarmNames=['SomeAlarmName'])
Boto 2 example:
import boto
client = boto.connect_cloudwatch()
client.delete_alarms('SomeAlarmName')
If you don't know the name, you can get a list of alarms with (the same for boto 2 and 3):
client.describe_alarms()
You should use Boto3. But if you are tied to Boto2, then:
import boto
cw = boto.connect_cloudwatch()
alarms= cw.describe_alarms()
for alarm in alarms:
print alarm.name
Check if the alarm you want to delete is listed. Then use that name:
cw.delete_alarms([<alarm_to_be_deleted>])
I'm having difficulty figuring out a way (if possible) to create a new AWS keypair with the Python Boto library and then download that keypair.
The Key object returned by the create_keypair method in boto has a "save" method. So, basically you can do something like this:
>>> import boto
>>> ec2 = boto.connect_ec2()
>>> key = ec2.create_key_pair('mynewkey')
>>> key.save('/path/to/keypair/dir')
If you want a more detailed example, check out https://github.com/garnaat/paws/blob/master/ec2_launch_instance.py.
Does that help? If not, provide some specifics about the problems you are encountering.
Same for Boto3:
ec2 = boto3.resource('ec2')
keypair_name = 'my_key'
new_keypair = ec2.create_key_pair(KeyName=keypair_name)
with open('./my_key.pem', 'w') as file:
file.write(new_keypair.key_material)
print(new_keypair.key_fingerprint)