cloudformation.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package amazon
  2. import (
  3. "fmt"
  4. "strings"
  5. cloudmapapi "github.com/aws/aws-sdk-go/service/servicediscovery"
  6. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  7. "github.com/awslabs/goformation/v4/cloudformation"
  8. "github.com/awslabs/goformation/v4/cloudformation/ec2"
  9. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  10. "github.com/awslabs/goformation/v4/cloudformation/iam"
  11. "github.com/awslabs/goformation/v4/cloudformation/logs"
  12. cloudmap "github.com/awslabs/goformation/v4/cloudformation/servicediscovery"
  13. "github.com/awslabs/goformation/v4/cloudformation/tags"
  14. "github.com/docker/ecs-plugin/pkg/compose"
  15. )
  16. const (
  17. ParameterClusterName = "ParameterClusterName"
  18. ParameterVPCId = "ParameterVPCId"
  19. ParameterSubnet1Id = "ParameterSubnet1Id"
  20. ParameterSubnet2Id = "ParameterSubnet2Id"
  21. )
  22. // Convert a compose project into a CloudFormation template
  23. func (c client) Convert(project *compose.Project) (*cloudformation.Template, error) {
  24. template := cloudformation.NewTemplate()
  25. template.Parameters[ParameterClusterName] = cloudformation.Parameter{
  26. Type: "String",
  27. Description: "Name of the ECS cluster to deploy to (optional)",
  28. }
  29. template.Parameters[ParameterVPCId] = cloudformation.Parameter{
  30. Type: "AWS::EC2::VPC::Id",
  31. Description: "ID of the VPC",
  32. }
  33. /*
  34. FIXME can't set subnets: Ref("SubnetIds") see https://github.com/awslabs/goformation/issues/282
  35. template.Parameters["SubnetIds"] = cloudformation.Parameter{
  36. Type: "List<AWS::EC2::Subnet::Id>",
  37. Description: "The list of SubnetIds, for at least two Availability Zones in the region in your VPC",
  38. }
  39. */
  40. template.Parameters[ParameterSubnet1Id] = cloudformation.Parameter{
  41. Type: "AWS::EC2::Subnet::Id",
  42. Description: "SubnetId,for Availability Zone 1 in the region in your VPC",
  43. }
  44. template.Parameters[ParameterSubnet2Id] = cloudformation.Parameter{
  45. Type: "AWS::EC2::Subnet::Id",
  46. Description: "SubnetId,for Availability Zone 1 in the region in your VPC",
  47. }
  48. // Create Cluster is `ParameterClusterName` parameter is not set
  49. template.Conditions["CreateCluster"] = cloudformation.Equals("", cloudformation.Ref(ParameterClusterName))
  50. template.Resources["Cluster"] = &ecs.Cluster{
  51. ClusterName: project.Name,
  52. Tags: []tags.Tag{
  53. {
  54. Key: ProjectTag,
  55. Value: project.Name,
  56. },
  57. },
  58. AWSCloudFormationCondition: "CreateCluster",
  59. }
  60. cluster := cloudformation.If("CreateCluster", cloudformation.Ref("Cluster"), cloudformation.Ref(ParameterClusterName))
  61. for net := range project.Networks {
  62. name, resource := convertNetwork(project, net, cloudformation.Ref(ParameterVPCId))
  63. template.Resources[name] = resource
  64. }
  65. logGroup := fmt.Sprintf("/docker-compose/%s", project.Name)
  66. template.Resources["LogGroup"] = &logs.LogGroup{
  67. LogGroupName: logGroup,
  68. }
  69. // Private DNS namespace will allow DNS name for the services to be <service>.<project>.local
  70. template.Resources["CloudMap"] = &cloudmap.PrivateDnsNamespace{
  71. Description: fmt.Sprintf("Service Map for Docker Compose project %s", project.Name),
  72. Name: fmt.Sprintf("%s.local", project.Name),
  73. Vpc: cloudformation.Ref(ParameterVPCId),
  74. }
  75. for _, service := range project.Services {
  76. definition, err := Convert(project, service)
  77. if err != nil {
  78. return nil, err
  79. }
  80. taskExecutionRole := fmt.Sprintf("%sTaskExecutionRole", service.Name)
  81. policy, err := c.getPolicy(definition)
  82. if err != nil {
  83. return nil, err
  84. }
  85. rolePolicies := []iam.Role_Policy{}
  86. if policy != nil {
  87. rolePolicies = append(rolePolicies, iam.Role_Policy{
  88. PolicyDocument: policy,
  89. PolicyName: fmt.Sprintf("%sGrantAccessToSecrets", service.Name),
  90. })
  91. }
  92. definition.ExecutionRoleArn = cloudformation.Ref(taskExecutionRole)
  93. taskDefinition := fmt.Sprintf("%sTaskDefinition", service.Name)
  94. template.Resources[taskExecutionRole] = &iam.Role{
  95. AssumeRolePolicyDocument: assumeRolePolicyDocument,
  96. Policies: rolePolicies,
  97. ManagedPolicyArns: []string{
  98. ECSTaskExecutionPolicy,
  99. },
  100. }
  101. template.Resources[taskDefinition] = definition
  102. var healthCheck *cloudmap.Service_HealthCheckConfig
  103. if service.HealthCheck != nil && !service.HealthCheck.Disable {
  104. // FIXME ECS only support HTTP(s) health checks, while Docker only support CMD
  105. }
  106. serviceRegistration := fmt.Sprintf("%sServiceDiscoveryEntry", service.Name)
  107. template.Resources[serviceRegistration] = &cloudmap.Service{
  108. Description: fmt.Sprintf("%q service discovery entry in Cloud Map", service.Name),
  109. HealthCheckConfig: healthCheck,
  110. Name: service.Name,
  111. NamespaceId: cloudformation.Ref("CloudMap"),
  112. DnsConfig: &cloudmap.Service_DnsConfig{
  113. DnsRecords: []cloudmap.Service_DnsRecord{
  114. {
  115. TTL: 300,
  116. Type: cloudmapapi.RecordTypeA,
  117. },
  118. },
  119. RoutingPolicy: cloudmapapi.RoutingPolicyMultivalue,
  120. },
  121. }
  122. serviceSecurityGroups := []string{}
  123. for net := range service.Networks {
  124. logicalName := networkResourceName(project, net)
  125. serviceSecurityGroups = append(serviceSecurityGroups, cloudformation.Ref(logicalName))
  126. }
  127. template.Resources[fmt.Sprintf("%sService", service.Name)] = &ecs.Service{
  128. Cluster: cluster,
  129. DesiredCount: 1,
  130. LaunchType: ecsapi.LaunchTypeFargate,
  131. NetworkConfiguration: &ecs.Service_NetworkConfiguration{
  132. AwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{
  133. AssignPublicIp: ecsapi.AssignPublicIpEnabled,
  134. SecurityGroups: serviceSecurityGroups,
  135. Subnets: []string{
  136. cloudformation.Ref(ParameterSubnet1Id),
  137. cloudformation.Ref(ParameterSubnet2Id),
  138. },
  139. },
  140. },
  141. SchedulingStrategy: ecsapi.SchedulingStrategyReplica,
  142. ServiceName: service.Name,
  143. ServiceRegistries: []ecs.Service_ServiceRegistry{
  144. {
  145. RegistryArn: cloudformation.GetAtt(serviceRegistration, "Arn"),
  146. },
  147. },
  148. TaskDefinition: cloudformation.Ref(taskDefinition),
  149. }
  150. }
  151. return template, nil
  152. }
  153. func convertNetwork(project *compose.Project, net string, vpc string) (string, cloudformation.Resource) {
  154. var ingresses []ec2.SecurityGroup_Ingress
  155. for _, service := range project.Services {
  156. if _, ok := service.Networks[net]; ok {
  157. for _, port := range service.Ports {
  158. ingresses = append(ingresses, ec2.SecurityGroup_Ingress{
  159. CidrIp: "0.0.0.0/0",
  160. Description: fmt.Sprintf("%s:%d/%s", service.Name, port.Target, port.Protocol),
  161. FromPort: int(port.Target),
  162. IpProtocol: strings.ToUpper(port.Protocol),
  163. ToPort: int(port.Target),
  164. })
  165. }
  166. }
  167. }
  168. securityGroup := networkResourceName(project, net)
  169. resource := &ec2.SecurityGroup{
  170. GroupDescription: fmt.Sprintf("%s %s Security Group", project.Name, net),
  171. GroupName: securityGroup,
  172. SecurityGroupIngress: ingresses,
  173. VpcId: vpc,
  174. Tags: []tags.Tag{
  175. {
  176. Key: ProjectTag,
  177. Value: project.Name,
  178. },
  179. {
  180. Key: NetworkTag,
  181. Value: net,
  182. },
  183. },
  184. }
  185. return securityGroup, resource
  186. }
  187. func networkResourceName(project *compose.Project, network string) string {
  188. return fmt.Sprintf("%s%sNetwork", project.Name, strings.Title(network))
  189. }
  190. func (c client) getPolicy(taskDef *ecs.TaskDefinition) (*PolicyDocument, error) {
  191. arns := []string{}
  192. for _, container := range taskDef.ContainerDefinitions {
  193. if container.RepositoryCredentials != nil {
  194. arns = append(arns, container.RepositoryCredentials.CredentialsParameter)
  195. }
  196. if len(container.Secrets) > 0 {
  197. for _, s := range container.Secrets {
  198. arns = append(arns, s.ValueFrom)
  199. }
  200. }
  201. }
  202. if len(arns) > 0 {
  203. return &PolicyDocument{
  204. Statement: []PolicyStatement{
  205. {
  206. Effect: "Allow",
  207. Action: []string{ActionGetSecretValue, ActionGetParameters, ActionDecrypt},
  208. Resource: arns,
  209. }},
  210. }, nil
  211. }
  212. return nil, nil
  213. }