Você está na página 1de 2

Funçao iam

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeRegions",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}

stop instances

import boto3

#define ec2
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):


# definir a procura por instâncias RUNNING e com a TAG ambiente=DESLIGAR
filters = [{
'Name': 'tag:DESLIGAR',
'Values': ['19HORAS']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]

#busca as instâncias
instances = ec2.instances.filter(Filters=filters)

#Pega o ID da instância
RunningInstances = [instance.id for instance in instances]

#Log para testar quais instâncias foram impactadas


print(RunningInstances)

#verificar se existem instâncias de TAG: DESLIGAR executando


if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print("Stoppando as instâncias")
else:
print("Não foram encontradas instâncias em RUNNING")

return 'Olá, seu comando rodou corretamente!'

start instances

import boto3

#define ec2
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):


# definir a procura por instâncias STOPPED e com a TAG ambiente=LIGAR
filters = [{
'Name': 'tag:LIGAR',
'Values': ['07HORAS']
},
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]

#busca as instâncias
instances = ec2.instances.filter(Filters=filters)

#Pega o ID da instância
RunningInstances = [instance.id for instance in instances]

#Log para testar quais instâncias foram impactadas


print(RunningInstances)

#verificar se existem instâncias com a TAG: LIGAR desligadas


if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).start()
print("Startando as instâncias")
else:
print("Não foram encontradas instâncias STOPPED")

return 'Olá, seu código rodou corretamente'

Você também pode gostar