Last active
August 11, 2020 14:02
-
-
Save ajithreddygeth/8967d161ac2ae446af8ef19e59e5a76a to your computer and use it in GitHub Desktop.
GO-Ec2
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
package main | |
import ( | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/ec2" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-lambda-go/lambda" | |
"github.com/bluele/slack" | |
"os" | |
"fmt" | |
) | |
var ( | |
region = os.Getenv("region") | |
channelName = []string {"test","ec2info"} | |
api = slack.New(token) | |
) | |
const ( | |
token = "xoxb-xxxxxxxx35654fffffffzz" | |
) | |
func restartnode() { | |
// Load session from shared config | |
sess := session.Must(session.NewSessionWithOptions(session.Options{ | |
SharedConfigState: session.SharedConfigEnable, | |
})) | |
// Create new EC2 client | |
ec2Svc := ec2.New(sess, &aws.Config{ | |
Region: aws.String(region), | |
}) | |
// add the filters | |
params := &ec2.DescribeInstancesInput{ | |
Filters: []*ec2.Filter{ | |
{ | |
Name: aws.String("tag:STACK"), | |
Values: []*string{aws.String("ELK")}, | |
}, | |
{ | |
Name: aws.String("tag:PROJECT"), | |
Values: []*string{aws.String("MONITORING")}, | |
}, | |
{ | |
Name: aws.String("tag:billing"), | |
Values: []*string{aws.String("Rearch")}, | |
}, | |
{ | |
Name: aws.String("instance-state-name"), | |
Values: []*string{aws.String("running")}, | |
}, | |
}, | |
} | |
// Call to get detailed information on each instance | |
result, err := ec2Svc.DescribeInstances(params) | |
if err != nil { | |
fmt.Println("Error", err) | |
} else { | |
for idx := range result.Reservations { | |
for _, inst := range result.Reservations[idx].Instances { | |
fmt.Println(" Instance ID: ", *inst.InstanceId , region) | |
instid := *inst.InstanceId | |
input := &ec2.StopInstancesInput{InstanceIds: []*string{aws.String(instid),},DryRun: aws.Bool(true),} | |
fmt.Printf ("%v/t " ,instid) | |
resp,err := ec2Svc.StopInstances(input) | |
if err != nil { | |
fmt.Println("Error", err) | |
message := "Error restarting Synthetic node on region: " + region + " instance ID " + instid | |
for _,channel :=range channelName { | |
err := api.ChatPostMessage(channel, message , nil) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} else { | |
fmt.Println("Success", resp.StoppingInstances) | |
message := "Synthetic node restart is successful on region: " + region + " instance ID "+ instid | |
for _,channel :=range channelName { | |
err := api.ChatPostMessage(channel, message , nil) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
func main(){ | |
lambda.Start(restartnode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment