any idea how I can modify this to passing the instance id as argument instead of putting it in the script?
import boto3
def stop_instance(instance_id):
ec2 = boto3.client("ec2", region_name="us-west-1")
response = ec2.stop_instances(InstanceIds=[instance_id])
print(response)
stop_instance()
If your objective if to stop all EC2 instances via Python script, you can first call the describe-instances method to dynamically build a list of all the running EC2 instances (pull id values based on the state property = running). From there you can pass that list into your function to stop them all, as the stop-instances method can handle a list of ids.
like this?
import boto3
import sys
import argparse
instance_id = sys.argv[1]
def stop_instance(instance_id):
ec2 = boto3.client("ec2", region_name="us-west-1")
response = ec2.stop_instances(InstanceIds=[instance_id])
print(response)
stop_instance(instance_id)
then i ran it with python3 stop_ec2.py instance-id
Related
when i try this code to change EC2 instance type, it gives me this error
----------------------------------error Response---------------------------------------------------------------
"errorMessage": "Syntax error in module 'lambda_function': expected an indented block
"Runtime.UserCodeSyntaxError",
--------------------------Lambda code--------------------------
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
# Insert your Instance ID here
my_instance = 'i-0cd1cecsdcdodid'
# Stop the instance
client.stop_instances(InstanceIds=[my_instance])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[my_instance])
# Change the instance type
client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value='t2.medium')
# Start the instance
client.start_instances(InstanceIds=[my_instance])
Looks like you have some indentation error in your code. Here is a reformatted version:
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
# Insert your Instance ID here
my_instance = 'i-0cd1cecsdcdodid' # Stop the instance
client.stop_instances(InstanceIds=[my_instance])
waiter = client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[my_instance]) # Change the instance type
client.modify_instance_attribute(InstanceId=my_instance,
Attribute='instanceType', Value='t2.medium') # Start the instance
client.start_instances(InstanceIds=[my_instance])
# This code was intended to list all the running instances that I have.
it is showing ""errorMessage": "'s3.ServiceResource' object has no attribute 'object'""
This code is intended to run on AWS Lambda. I am a beginner, and so if there are any other mistakes in this code, please do share your inputs.
import json
import boto3
ec2 = boto3.resource("ec2")
s3 = boto3.resource('s3')
object = s3.Bucket("object")
def lambda_handler(event, context):
filters = [{"Name" : "instance-state-name",
"Values" : ["running"]
}
]
instances = ec2.instances.filter(Filters = filters)
RunningInstances = []
for instance in instances:
RunningInstances.append(instance.id)
instanceList = json.dumps(RunningInstances)
s3.object(
'sameeeeeerjajs',
'instanceList.txt'
).put(Body=instanceList)
return("Status code:200")
From boto's docs for S3.Object it should be (Object, not object):
s3.Object(
'sameeeeeerjajs',
'instanceList.txt'
).put(Body=instanceList)
I have a boto3 script that describes images.
However, I want to customize the script so that it shows me only the value of the tag that is the Name of the AMI.
Currently its displaying:
([{u'Value': 'NAME OF AMI', u'Key': 'Name'}], 'ami-xxxxxxxxxxxxxx', 'available')
But I want something like this:
**Name :'NAME OF AMI', 'ami-xxxxxxxxxxxxxx', 'available'**
Here is my script:
import boto3
import sys
import pprint
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
response = client.describe_images(Owners=['self'])
for ami in response['Images']:
print (ami['Tags'], ami['ImageId'], ami['State'])
There can be multiple Tags on an AMI. This code will display the Value of the tag that has a Key of Name (and it will also show the Name of the AMI that normally appears as "AMI Name" in the console, which is a different name!):
import boto3
import sys
import pprint
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
response = client.describe_images(Owners=['self'])
for ami in response['Images']:
if 'Tags' in ami:
name = [tag['Value'] for tag in ami['Tags'] if tag['Key'] == 'Name'][0]
else:
name = ''
print (name, ami['Name'], ami['ImageId'], ami['State'])
I am running a python job in AWS Lambda to stop ec2 instances based on tags.
The script is running properly, but even if the script completes successfully, I am getting output "null" in the result returned by function execution.
Attached herewith is the python script. I am new to Python scripting. I am from ops side.
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define the connection
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:AutoOff',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances
instances = ec2.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
#print the instances for logging purposes
print RunningInstances
#make sure there are actually instances to shut down.
if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print shuttingDown
else:
print "NOTHING"
In order to get response from the lambda you need to return something (usually a dictionary) from lambda_handler method. By default all Python methods return None type, that is why you do not receive any valuable response.
def lambda_handler(event, context):
... your code here ...
return {"turned_off": RunningInstances}
PS. it is preferred to use logging.debug|info|... method instead of print(). You can find more info in the documentation: https://docs.python.org/2.7/library/logging.html
Anyway all the output is saved to CloudWatch Logs. The Log Stream is created automatically when you create a Lambda function. You can find all your prints there for debugging.
I'm trying to create RDS MySQL DB snapshot using aws lambda function. I want to create db snapshot name with time stamp (not snapshot creation time).
Example: For below code I'm expecting 'mydb-2017-08-24-06-12' as a db snapshot name.
import boto3
import datetime
def lambda_handler(event, context):
client = boto3.client('rds')
i = datetime.datetime.now()
response = client.create_db_snapshot(
DBSnapshotIdentifier="mydb" % (i),
DBInstanceIdentifier='mydb'
)
but it throwing below error:
DBSnapshotIdentifier="mydb" % (i),
TypeError: not all arguments converted during string formatting
Please provide any type of relevant solution to me.
I've fixed my code like this:
import boto3
import datetime
def lambda_handler(event, context):
client = boto3.client('rds')
x = datetime.datetime.now().strftime("mydb-%Y-%m-%d-%H-%M-%S")
response = client.create_db_snapshot(
DBSnapshotIdentifier= x,
DBInstanceIdentifier='mydb'
)