cloudformation.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package amazon
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. "github.com/compose-spec/compose-go/types"
  7. "github.com/sirupsen/logrus"
  8. "github.com/aws/aws-sdk-go/service/elbv2"
  9. cloudmapapi "github.com/aws/aws-sdk-go/service/servicediscovery"
  10. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  11. "github.com/awslabs/goformation/v4/cloudformation"
  12. "github.com/awslabs/goformation/v4/cloudformation/ec2"
  13. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  14. "github.com/awslabs/goformation/v4/cloudformation/elasticloadbalancingv2"
  15. "github.com/awslabs/goformation/v4/cloudformation/iam"
  16. "github.com/awslabs/goformation/v4/cloudformation/logs"
  17. cloudmap "github.com/awslabs/goformation/v4/cloudformation/servicediscovery"
  18. "github.com/awslabs/goformation/v4/cloudformation/tags"
  19. "github.com/docker/ecs-plugin/pkg/compose"
  20. )
  21. const (
  22. ParameterClusterName = "ParameterClusterName"
  23. ParameterVPCId = "ParameterVPCId"
  24. ParameterSubnet1Id = "ParameterSubnet1Id"
  25. ParameterSubnet2Id = "ParameterSubnet2Id"
  26. ParameterLoadBalancerARN = "ParameterLoadBalancerARN"
  27. )
  28. // Convert a compose project into a CloudFormation template
  29. func (c client) Convert(project *compose.Project) (*cloudformation.Template, error) {
  30. warnings := Check(project)
  31. for _, w := range warnings {
  32. logrus.Warn(w)
  33. }
  34. template := cloudformation.NewTemplate()
  35. template.Parameters[ParameterClusterName] = cloudformation.Parameter{
  36. Type: "String",
  37. Description: "Name of the ECS cluster to deploy to (optional)",
  38. }
  39. template.Parameters[ParameterVPCId] = cloudformation.Parameter{
  40. Type: "AWS::EC2::VPC::Id",
  41. Description: "ID of the VPC",
  42. }
  43. /*
  44. FIXME can't set subnets: Ref("SubnetIds") see https://github.com/awslabs/goformation/issues/282
  45. template.Parameters["SubnetIds"] = cloudformation.Parameter{
  46. Type: "List<AWS::EC2::Subnet::Id>",
  47. Description: "The list of SubnetIds, for at least two Availability Zones in the region in your VPC",
  48. }
  49. */
  50. template.Parameters[ParameterSubnet1Id] = cloudformation.Parameter{
  51. Type: "AWS::EC2::Subnet::Id",
  52. Description: "SubnetId, for Availability Zone 1 in the region in your VPC",
  53. }
  54. template.Parameters[ParameterSubnet2Id] = cloudformation.Parameter{
  55. Type: "AWS::EC2::Subnet::Id",
  56. Description: "SubnetId, for Availability Zone 2 in the region in your VPC",
  57. }
  58. template.Parameters[ParameterLoadBalancerARN] = cloudformation.Parameter{
  59. Type: "String",
  60. Description: "Name of the LoadBalancer to connect to (optional)",
  61. }
  62. // Create Cluster is `ParameterClusterName` parameter is not set
  63. template.Conditions["CreateCluster"] = cloudformation.Equals("", cloudformation.Ref(ParameterClusterName))
  64. cluster := c.createCluster(project, template)
  65. networks := map[string]string{}
  66. for _, net := range project.Networks {
  67. networks[net.Name] = convertNetwork(project, net, cloudformation.Ref(ParameterVPCId), template)
  68. }
  69. logGroup := fmt.Sprintf("/docker-compose/%s", project.Name)
  70. template.Resources["LogGroup"] = &logs.LogGroup{
  71. LogGroupName: logGroup,
  72. }
  73. // Private DNS namespace will allow DNS name for the services to be <service>.<project>.local
  74. c.createCloudMap(project, template)
  75. loadBalancer := c.createLoadBalancer(project, template, "network")
  76. for _, service := range project.Services {
  77. definition, err := Convert(project, service)
  78. if err != nil {
  79. return nil, err
  80. }
  81. taskExecutionRole, err := c.createTaskExecutionRole(service, err, definition, template)
  82. if err != nil {
  83. return template, err
  84. }
  85. definition.ExecutionRoleArn = cloudformation.Ref(taskExecutionRole)
  86. taskDefinition := fmt.Sprintf("%sTaskDefinition", normalizeResourceName(service.Name))
  87. template.Resources[taskDefinition] = definition
  88. var healthCheck *cloudmap.Service_HealthCheckConfig
  89. if service.HealthCheck != nil && !service.HealthCheck.Disable {
  90. // FIXME ECS only support HTTP(s) health checks, while Docker only support CMD
  91. }
  92. serviceRegistry := c.createServiceRegistry(service, template, healthCheck)
  93. serviceSecurityGroups := []string{}
  94. for net := range service.Networks {
  95. serviceSecurityGroups = append(serviceSecurityGroups, networks[net])
  96. }
  97. dependsOn := []string{}
  98. serviceLB := []ecs.Service_LoadBalancer{}
  99. if len(service.Ports) > 0 {
  100. for _, port := range service.Ports {
  101. protocol := strings.ToUpper(port.Protocol)
  102. targetGroupName := c.createTargetGroup(project, service, port, template, protocol)
  103. listenerName := c.createListener(service, port, template, targetGroupName, loadBalancer, protocol)
  104. dependsOn = append(dependsOn, listenerName)
  105. serviceLB = append(serviceLB, ecs.Service_LoadBalancer{
  106. ContainerName: service.Name,
  107. ContainerPort: int(port.Published),
  108. TargetGroupArn: cloudformation.Ref(targetGroupName),
  109. })
  110. }
  111. }
  112. desiredCount := 1
  113. if service.Deploy != nil && service.Deploy.Replicas != nil {
  114. desiredCount = int(*service.Deploy.Replicas)
  115. }
  116. for _, dependency := range service.DependsOn {
  117. dependsOn = append(dependsOn, serviceResourceName(dependency))
  118. }
  119. template.Resources[serviceResourceName(service.Name)] = &ecs.Service{
  120. AWSCloudFormationDependsOn: dependsOn,
  121. Cluster: cluster,
  122. DesiredCount: desiredCount,
  123. LaunchType: ecsapi.LaunchTypeFargate,
  124. LoadBalancers: serviceLB,
  125. NetworkConfiguration: &ecs.Service_NetworkConfiguration{
  126. AwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{
  127. AssignPublicIp: ecsapi.AssignPublicIpEnabled,
  128. SecurityGroups: serviceSecurityGroups,
  129. Subnets: []string{
  130. cloudformation.Ref(ParameterSubnet1Id),
  131. cloudformation.Ref(ParameterSubnet2Id),
  132. },
  133. },
  134. },
  135. SchedulingStrategy: ecsapi.SchedulingStrategyReplica,
  136. ServiceName: service.Name,
  137. ServiceRegistries: []ecs.Service_ServiceRegistry{serviceRegistry},
  138. Tags: []tags.Tag{
  139. {
  140. Key: ProjectTag,
  141. Value: project.Name,
  142. },
  143. {
  144. Key: ServiceTag,
  145. Value: service.Name,
  146. },
  147. },
  148. TaskDefinition: cloudformation.Ref(normalizeResourceName(taskDefinition)),
  149. }
  150. }
  151. return template, nil
  152. }
  153. func (c client) createLoadBalancer(project *compose.Project, template *cloudformation.Template, loadBalancerType string) string {
  154. loadBalancerName := fmt.Sprintf("%sLoadBalancer", strings.Title(project.Name))
  155. // Create LoadBalancer if `ParameterLoadBalancerName` is not set
  156. template.Conditions["CreateLoadBalancer"] = cloudformation.Equals("", cloudformation.Ref(ParameterLoadBalancerARN))
  157. template.Resources[loadBalancerName] = &elasticloadbalancingv2.LoadBalancer{
  158. Name: loadBalancerName,
  159. Scheme: elbv2.LoadBalancerSchemeEnumInternetFacing,
  160. Subnets: []string{
  161. cloudformation.Ref(ParameterSubnet1Id),
  162. cloudformation.Ref(ParameterSubnet2Id),
  163. },
  164. Tags: []tags.Tag{
  165. {
  166. Key: ProjectTag,
  167. Value: project.Name,
  168. },
  169. },
  170. Type: loadBalancerType,
  171. AWSCloudFormationCondition: "CreateLoadBalancer",
  172. }
  173. loadBalancerRef := cloudformation.If("CreateLoadBalancer", cloudformation.Ref(loadBalancerName), cloudformation.Ref(ParameterLoadBalancerARN))
  174. return loadBalancerRef
  175. }
  176. func (c client) createListener(service types.ServiceConfig, port types.ServicePortConfig, template *cloudformation.Template, targetGroupName string, loadBalancerARN string, protocol string) string {
  177. listenerName := fmt.Sprintf(
  178. "%s%s%dListener",
  179. normalizeResourceName(service.Name),
  180. strings.ToUpper(port.Protocol),
  181. port.Published,
  182. )
  183. //add listener to dependsOn
  184. //https://stackoverflow.com/questions/53971873/the-target-group-does-not-have-an-associated-load-balancer
  185. template.Resources[listenerName] = &elasticloadbalancingv2.Listener{
  186. DefaultActions: []elasticloadbalancingv2.Listener_Action{
  187. {
  188. ForwardConfig: &elasticloadbalancingv2.Listener_ForwardConfig{
  189. TargetGroups: []elasticloadbalancingv2.Listener_TargetGroupTuple{
  190. {
  191. TargetGroupArn: cloudformation.Ref(targetGroupName),
  192. },
  193. },
  194. },
  195. Type: elbv2.ActionTypeEnumForward,
  196. },
  197. },
  198. LoadBalancerArn: loadBalancerARN,
  199. Protocol: protocol,
  200. Port: int(port.Published),
  201. }
  202. return listenerName
  203. }
  204. func (c client) createTargetGroup(project *compose.Project, service types.ServiceConfig, port types.ServicePortConfig, template *cloudformation.Template, protocol string) string {
  205. targetGroupName := fmt.Sprintf(
  206. "%s%s%dTargetGroup",
  207. normalizeResourceName(service.Name),
  208. strings.ToUpper(port.Protocol),
  209. port.Published,
  210. )
  211. template.Resources[targetGroupName] = &elasticloadbalancingv2.TargetGroup{
  212. Name: targetGroupName,
  213. Port: int(port.Target),
  214. Protocol: protocol,
  215. Tags: []tags.Tag{
  216. {
  217. Key: ProjectTag,
  218. Value: project.Name,
  219. },
  220. },
  221. VpcId: cloudformation.Ref(ParameterVPCId),
  222. TargetType: elbv2.TargetTypeEnumIp,
  223. }
  224. return targetGroupName
  225. }
  226. func (c client) createServiceRegistry(service types.ServiceConfig, template *cloudformation.Template, healthCheck *cloudmap.Service_HealthCheckConfig) ecs.Service_ServiceRegistry {
  227. serviceRegistration := fmt.Sprintf("%sServiceDiscoveryEntry", normalizeResourceName(service.Name))
  228. serviceRegistry := ecs.Service_ServiceRegistry{
  229. RegistryArn: cloudformation.GetAtt(serviceRegistration, "Arn"),
  230. }
  231. template.Resources[serviceRegistration] = &cloudmap.Service{
  232. Description: fmt.Sprintf("%q service discovery entry in Cloud Map", service.Name),
  233. HealthCheckConfig: healthCheck,
  234. Name: service.Name,
  235. NamespaceId: cloudformation.Ref("CloudMap"),
  236. DnsConfig: &cloudmap.Service_DnsConfig{
  237. DnsRecords: []cloudmap.Service_DnsRecord{
  238. {
  239. TTL: 60,
  240. Type: cloudmapapi.RecordTypeA,
  241. },
  242. },
  243. RoutingPolicy: cloudmapapi.RoutingPolicyMultivalue,
  244. },
  245. }
  246. return serviceRegistry
  247. }
  248. func (c client) createTaskExecutionRole(service types.ServiceConfig, err error, definition *ecs.TaskDefinition, template *cloudformation.Template) (string, error) {
  249. taskExecutionRole := fmt.Sprintf("%sTaskExecutionRole", normalizeResourceName(service.Name))
  250. policy, err := c.getPolicy(definition)
  251. if err != nil {
  252. return taskExecutionRole, err
  253. }
  254. rolePolicies := []iam.Role_Policy{}
  255. if policy != nil {
  256. rolePolicies = append(rolePolicies, iam.Role_Policy{
  257. PolicyDocument: policy,
  258. PolicyName: fmt.Sprintf("%sGrantAccessToSecrets", service.Name),
  259. })
  260. }
  261. template.Resources[taskExecutionRole] = &iam.Role{
  262. AssumeRolePolicyDocument: assumeRolePolicyDocument,
  263. Policies: rolePolicies,
  264. ManagedPolicyArns: []string{
  265. ECSTaskExecutionPolicy,
  266. ECRReadOnlyPolicy,
  267. },
  268. }
  269. return taskExecutionRole, nil
  270. }
  271. func (c client) createCluster(project *compose.Project, template *cloudformation.Template) string {
  272. template.Resources["Cluster"] = &ecs.Cluster{
  273. ClusterName: project.Name,
  274. Tags: []tags.Tag{
  275. {
  276. Key: ProjectTag,
  277. Value: project.Name,
  278. },
  279. },
  280. AWSCloudFormationCondition: "CreateCluster",
  281. }
  282. cluster := cloudformation.If("CreateCluster", cloudformation.Ref("Cluster"), cloudformation.Ref(ParameterClusterName))
  283. return cluster
  284. }
  285. func (c client) createCloudMap(project *compose.Project, template *cloudformation.Template) {
  286. template.Resources["CloudMap"] = &cloudmap.PrivateDnsNamespace{
  287. Description: fmt.Sprintf("Service Map for Docker Compose project %s", project.Name),
  288. Name: fmt.Sprintf("%s.local", project.Name),
  289. Vpc: cloudformation.Ref(ParameterVPCId),
  290. }
  291. }
  292. func convertNetwork(project *compose.Project, net types.NetworkConfig, vpc string, template *cloudformation.Template) string {
  293. if sg, ok := net.Extras[ExtensionSecurityGroup]; ok {
  294. logrus.Debugf("Security Group for network %q set by user to %q", net.Name, sg)
  295. return sg.(string)
  296. }
  297. var ingresses []ec2.SecurityGroup_Ingress
  298. if !net.Internal {
  299. for _, service := range project.Services {
  300. if _, ok := service.Networks[net.Name]; ok {
  301. for _, port := range service.Ports {
  302. ingresses = append(ingresses, ec2.SecurityGroup_Ingress{
  303. CidrIp: "0.0.0.0/0",
  304. Description: fmt.Sprintf("%s:%d/%s", service.Name, port.Target, port.Protocol),
  305. FromPort: int(port.Target),
  306. IpProtocol: strings.ToUpper(port.Protocol),
  307. ToPort: int(port.Target),
  308. })
  309. }
  310. }
  311. }
  312. }
  313. securityGroup := networkResourceName(project, net.Name)
  314. template.Resources[securityGroup] = &ec2.SecurityGroup{
  315. GroupDescription: fmt.Sprintf("%s %s Security Group", project.Name, net.Name),
  316. GroupName: securityGroup,
  317. SecurityGroupIngress: ingresses,
  318. VpcId: vpc,
  319. Tags: []tags.Tag{
  320. {
  321. Key: ProjectTag,
  322. Value: project.Name,
  323. },
  324. {
  325. Key: NetworkTag,
  326. Value: net.Name,
  327. },
  328. },
  329. }
  330. ingress := securityGroup + "Ingress"
  331. template.Resources[ingress] = &ec2.SecurityGroupIngress{
  332. Description: fmt.Sprintf("Allow communication within network %s", net.Name),
  333. IpProtocol: "-1", // all protocols
  334. GroupId: cloudformation.Ref(securityGroup),
  335. SourceSecurityGroupId: cloudformation.Ref(securityGroup),
  336. }
  337. return cloudformation.Ref(securityGroup)
  338. }
  339. func networkResourceName(project *compose.Project, network string) string {
  340. return fmt.Sprintf("%s%sNetwork", normalizeResourceName(project.Name), normalizeResourceName(network))
  341. }
  342. func serviceResourceName(dependency string) string {
  343. return fmt.Sprintf("%sService", normalizeResourceName(dependency))
  344. }
  345. func normalizeResourceName(s string) string {
  346. return strings.Title(regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(s, ""))
  347. }
  348. func (c client) getPolicy(taskDef *ecs.TaskDefinition) (*PolicyDocument, error) {
  349. arns := []string{}
  350. for _, container := range taskDef.ContainerDefinitions {
  351. if container.RepositoryCredentials != nil {
  352. arns = append(arns, container.RepositoryCredentials.CredentialsParameter)
  353. }
  354. if len(container.Secrets) > 0 {
  355. for _, s := range container.Secrets {
  356. arns = append(arns, s.ValueFrom)
  357. }
  358. }
  359. }
  360. if len(arns) > 0 {
  361. return &PolicyDocument{
  362. Statement: []PolicyStatement{
  363. {
  364. Effect: "Allow",
  365. Action: []string{ActionGetSecretValue, ActionGetParameters, ActionDecrypt},
  366. Resource: arns,
  367. }},
  368. }, nil
  369. }
  370. return nil, nil
  371. }