github.com/kolanos/fargate@v0.2.3/cmd/service_destroy.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/jpignata/fargate/console"
     7  	ECS "github.com/jpignata/fargate/ecs"
     8  	ELBV2 "github.com/jpignata/fargate/elbv2"
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  type ServiceDestroyOperation struct {
    13  	ServiceName string
    14  }
    15  
    16  var serviceDestroyCmd = &cobra.Command{
    17  	Use:   "destroy <service-name>",
    18  	Short: "Destroy a service",
    19  	Long: `Destroy service
    20  
    21  In order to destroy a service, it must first be scaled to 0 running tasks.`,
    22  	Args: cobra.ExactArgs(1),
    23  	Run: func(cmd *cobra.Command, args []string) {
    24  		operation := &ServiceDestroyOperation{
    25  			ServiceName: args[0],
    26  		}
    27  
    28  		destroyService(operation)
    29  	},
    30  }
    31  
    32  func init() {
    33  	serviceCmd.AddCommand(serviceDestroyCmd)
    34  }
    35  
    36  func destroyService(operation *ServiceDestroyOperation) {
    37  	elbv2 := ELBV2.New(sess)
    38  	ecs := ECS.New(sess, clusterName)
    39  	service := ecs.DescribeService(operation.ServiceName)
    40  
    41  	if service.DesiredCount > 0 {
    42  		err := fmt.Errorf("%d tasks running, scale service to 0", service.DesiredCount)
    43  		console.ErrorExit(err, "Cannot destroy service %s", operation.ServiceName)
    44  	}
    45  
    46  	if service.TargetGroupArn != "" {
    47  		loadBalancerArn := elbv2.GetTargetGroupLoadBalancerArn(service.TargetGroupArn)
    48  		loadBalancer := elbv2.DescribeLoadBalancerByArn(loadBalancerArn)
    49  		listeners := elbv2.GetListeners(loadBalancerArn)
    50  
    51  		for _, listener := range listeners {
    52  			for _, rule := range elbv2.DescribeRules(listener.Arn) {
    53  				if rule.TargetGroupArn == service.TargetGroupArn {
    54  					if rule.IsDefault {
    55  						defaultTargetGroupName := fmt.Sprintf(defaultTargetGroupFormat, loadBalancer.Name)
    56  						defaultTargetGroupArn := elbv2.GetTargetGroupArn(defaultTargetGroupName)
    57  
    58  						if defaultTargetGroupArn == "" {
    59  							defaultTargetGroupArn = elbv2.CreateTargetGroup(
    60  								&ELBV2.CreateTargetGroupInput{
    61  									Name:     defaultTargetGroupName,
    62  									Port:     listeners[0].Port,
    63  									Protocol: listeners[0].Protocol,
    64  									VpcId:    loadBalancer.VpcId,
    65  								},
    66  							)
    67  						}
    68  
    69  						elbv2.ModifyListenerDefaultAction(listener.Arn, defaultTargetGroupArn)
    70  					} else {
    71  						elbv2.DeleteRule(rule.Arn)
    72  					}
    73  				}
    74  			}
    75  		}
    76  
    77  		elbv2.DeleteTargetGroupByArn(service.TargetGroupArn)
    78  	}
    79  
    80  	ecs.DestroyService(operation.ServiceName)
    81  	console.Info("Destroyed service %s", operation.ServiceName)
    82  }