cloudformation.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package amazon
  2. import (
  3. "fmt"
  4. "strings"
  5. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  6. "github.com/awslabs/goformation/v4/cloudformation"
  7. "github.com/awslabs/goformation/v4/cloudformation/ec2"
  8. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  9. "github.com/docker/ecs-plugin/pkg/compose"
  10. "github.com/docker/ecs-plugin/pkg/convert"
  11. )
  12. func (c client) Convert(project *compose.Project, loadBalancerArn *string) (*cloudformation.Template, error) {
  13. template := cloudformation.NewTemplate()
  14. vpc, err := c.GetDefaultVPC()
  15. if err != nil {
  16. return nil, err
  17. }
  18. subnets, err := c.GetSubNets(vpc)
  19. if err != nil {
  20. return nil, err
  21. }
  22. var ingresses = []ec2.SecurityGroup_Ingress{}
  23. for _, service := range project.Services {
  24. for _, port := range service.Ports {
  25. ingresses = append(ingresses, ec2.SecurityGroup_Ingress{
  26. CidrIp: "0.0.0.0/0",
  27. Description: fmt.Sprintf("%s:%d/%s", service.Name, port.Target, port.Protocol),
  28. FromPort: int(port.Target),
  29. IpProtocol: strings.ToUpper(port.Protocol),
  30. ToPort: int(port.Target),
  31. })
  32. }
  33. }
  34. securityGroup := fmt.Sprintf("%s Security Group", project.Name)
  35. template.Resources["SecurityGroup"] = &ec2.SecurityGroup{
  36. GroupDescription: securityGroup,
  37. GroupName: securityGroup,
  38. SecurityGroupIngress: ingresses,
  39. VpcId: *vpc,
  40. }
  41. for _, service := range project.Services {
  42. definition, err := convert.Convert(project, service)
  43. if err != nil {
  44. return nil, err
  45. }
  46. role, err := c.GetEcsTaskExecutionRole(service)
  47. if err != nil {
  48. return nil, err
  49. }
  50. definition.TaskRoleArn = *role
  51. taskDefinition := fmt.Sprintf("%sTaskDefinition", service.Name)
  52. template.Resources[taskDefinition] = definition
  53. template.Resources[service.Name] = &ecs.Service{
  54. Cluster: c.Cluster,
  55. DesiredCount: 1,
  56. LaunchType: ecsapi.LaunchTypeFargate,
  57. NetworkConfiguration: &ecs.Service_NetworkConfiguration{
  58. AwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{
  59. AssignPublicIp: ecsapi.AssignPublicIpEnabled,
  60. SecurityGroups: []string{cloudformation.Ref("SecurityGroup")},
  61. Subnets: subnets,
  62. },
  63. },
  64. SchedulingStrategy: ecsapi.SchedulingStrategyReplica,
  65. ServiceName: service.Name,
  66. TaskDefinition: cloudformation.Ref(taskDefinition),
  67. }
  68. }
  69. return template, nil
  70. }