В предыдущей статье мы рассказывали о AWS SDK для Go и объясняли, как использовать S3 для загрузки файлов. Вы изучите больше AWS SDK для Go для запуска и остановки инстансов EC2, обычно вы используете это с помощью Lambda, как в этом посте. Но я буду использовать AWS SDK для своих сервисов Go. Давайте начнем!
Начальный проект
Вы можете попробовать начать проект с этого коммита. Чтобы проверить мои изменения, вы можете проверить этот коммит.
Настройка/установка AWS SDK для Go
Другие зависимости (за исключением S3) вы можете посмотреть в предыдущем посте.
go get github.com/aws/aws-sdk-go-v2/service/ec2
Функции
В настоящее время в примере используется жестко заданный список экземпляров, которые я хочу запускать и останавливать.
- Запуск экземпляра
func (ec2Handler *EC2Handler) StartInstance(ctx context.Context) (err error) {
instanceId := "i-0b33f0e5d8d00d6f3" // list your instances here, if you want to have a list instead of 1 instance. You may need to update the input from InstanceIds: []string{instanceId} to InstancedIds: instanceIds and rename the variable to instanceIds also do some changes in the for loop.
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
ec2Client := ec2.NewFromConfig(cfg)
input := &ec2.DescribeInstanceStatusInput{
InstanceIds: []string{instanceId},
}
output, err := ec2Client.DescribeInstanceStatus(ctx, input)
if err != nil {
log.Println(err)
return
}
isRunning := false
for _, instanceStatus := range output.InstanceStatuses {
log.Printf("%s: %sn", *instanceStatus.InstanceId, instanceStatus.InstanceState.Name)
if *instanceStatus.InstanceId == instanceId && instanceStatus.InstanceState.Name == "running" {
isRunning = true
}
}
if !isRunning {
runInstance := &ec2.StartInstancesInput{
InstanceIds: []string{instanceId},
}
log.Printf("Start %s", instanceId)
if outputStart, errInstance := ec2Client.StartInstances(ctx, runInstance); errInstance != nil {
return
} else {
log.Println(outputStart.StartingInstances)
}
} else {
log.Printf("Skip starting %s", instanceId)
}
return
}
- Остановка экземпляра
func (ec2Handler *EC2Handler) StopInstance(ctx context.Context) (err error) {
instanceId := "i-0b33f0e5d8d00d6f3"
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
ec2Client := ec2.NewFromConfig(cfg)
input := &ec2.DescribeInstanceStatusInput{
InstanceIds: []string{instanceId},
}
output, err := ec2Client.DescribeInstanceStatus(ctx, input)
if err != nil {
log.Println(err)
return
}
isStop := false
for _, instanceStatus := range output.InstanceStatuses {
log.Printf("%s: %sn", *instanceStatus.InstanceId, instanceStatus.InstanceState.Name)
if *instanceStatus.InstanceId == instanceId && instanceStatus.InstanceState.Name == "stop" {
isStop = true
}
}
if !isStop {
stopInstance := &ec2.StopInstancesInput{
InstanceIds: []string{instanceId},
}
log.Printf("Stop %s", instanceId)
if outputStop, errInstance := ec2Client.StopInstances(ctx, stopInstance); errInstance != nil {
return
} else {
log.Println(outputStop.StoppingInstances)
}
} else {
log.Printf("Skip stop %s", instanceId)
}
return
}
Не забудьте настроить учетные данные. В настоящее время я использую переменные окружения.
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=ap-southeast-3
Довольно просто, верно? Вы можете использовать AWS SDK для Go для другого случая. Если вы хотите подробнее изучить репозиторий, вы можете посетить эту ссылку.
bervProject / go-microservice-boilerplate
Go Microservice Boilerplate
go-microservice-boilerplate
Go Microservice Boilerplate
Окружение
DB_CONNECTION_STRING= PORT=
Построить
go build
Запустить локально
go run server.go
Протестировать
go test ./... -cover
ЛИЦЕНЗИЯ
MIT
Спасибо, что прочитали. Счастливого изучения!