<repo_name>learn-with-aws/Lambda_Boto3<file_sep>/stop_start_ec2_instances.py
import json
import boto3
data = boto3.client('ec2')
def lambda_handler(event, context):
    instances = data.describe_instances(Filters=[{'Name': 'tag:env', 'Values': ['wc_testserver']}])
    instances_list = []
    for instance in instances['Reservations']:
        for instance_id in instance['Instances']:
            instances_list.append(instance_id['InstanceId'])
    print (instances_list)
    
    # Stop EC2 instances
    data.stop_instances(InstanceIds=instances_list)
    print ("The above instance got stopped")
    
    # Start Ec2 Instances
    #data.start_instances(InstanceIds=instances_list)
    #print ("The above instance got started")
<file_sep>/secret_manager.py
import boto3
import json

secret_name = "dev/ocp"
region_name = "us-east-1"

# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
    service_name='secretsmanager',
    region_name=region_name
)

get_secret_value_response = client.get_secret_value(SecretId=secret_name)

secret = get_secret_value_response['SecretString']

dictData = json.loads(secret)
#print(dictData)
print(dictData['host'])
print(dictData['port'])
<file_sep>/stop_ec2_instances_without_specific_tags.py

## Stop the Server if they don't have any tags.

#### Steps - Create a Lambda and setup a cloudwatch event pattren. Select EC2 service type and event.

import json
import boto3
data = boto3.client('ec2')
def lambda_handler(event, context):
    instances = data.describe_instances(Filters=[{'Name': 'tag:env', 'Values': ['wc_testserver']}])
    instances_list = []
    for instance in instances['Reservations']:
        for instance_id in instance['Instances']:
            instances_list.append(instance_id['InstanceId'])
    print (instances_list)
    data.stop_instances(InstanceIds=instances_list)
    #data.stop_instances(InstanceIds=instances_list)
    print ("The above instance got start")
