Merge pull request #1803 from TimeIncOSS/ecs

aws: Add support for ECS (Container Service)
This commit is contained in:
Radek Simko 2015-06-05 22:25:41 +02:00
commit 1770713633
13 changed files with 1269 additions and 0 deletions

View File

@ -11,6 +11,7 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/elasticache"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/iam"
@ -35,6 +36,7 @@ type Config struct {
type AWSClient struct {
ec2conn *ec2.EC2
ecsconn *ecs.ECS
elbconn *elb.ELB
autoscalingconn *autoscaling.AutoScaling
s3conn *s3.S3
@ -116,6 +118,9 @@ func (c *Config) Client() (interface{}, error) {
log.Println("[INFO] Initializing EC2 Connection")
client.ec2conn = ec2.New(awsConfig)
log.Println("[INFO] Initializing ECS Connection")
client.ecsconn = ecs.New(awsConfig)
// aws-sdk-go uses v4 for signing requests, which requires all global
// endpoints to use 'us-east-1'.
// See http://docs.aws.amazon.com/general/latest/gr/sigv4_changes.html

View File

@ -91,6 +91,9 @@ func Provider() terraform.ResourceProvider {
"aws_db_security_group": resourceAwsDbSecurityGroup(),
"aws_db_subnet_group": resourceAwsDbSubnetGroup(),
"aws_ebs_volume": resourceAwsEbsVolume(),
"aws_ecs_cluster": resourceAwsEcsCluster(),
"aws_ecs_service": resourceAwsEcsService(),
"aws_ecs_task_definition": resourceAwsEcsTaskDefinition(),
"aws_eip": resourceAwsEip(),
"aws_elasticache_cluster": resourceAwsElasticacheCluster(),
"aws_elasticache_security_group": resourceAwsElasticacheSecurityGroup(),

View File

@ -0,0 +1,80 @@
package aws
import (
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsEcsCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEcsClusterCreate,
Read: resourceAwsEcsClusterRead,
Delete: resourceAwsEcsClusterDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAwsEcsClusterCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
clusterName := d.Get("name").(string)
log.Printf("[DEBUG] Creating ECS cluster %s", clusterName)
out, err := conn.CreateCluster(&ecs.CreateClusterInput{
ClusterName: aws.String(clusterName),
})
if err != nil {
return err
}
log.Printf("[DEBUG] ECS cluster %s created", *out.Cluster.ClusterARN)
d.SetId(*out.Cluster.ClusterARN)
d.Set("name", *out.Cluster.ClusterName)
return nil
}
func resourceAwsEcsClusterRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
clusterName := d.Get("name").(string)
log.Printf("[DEBUG] Reading ECS cluster %s", clusterName)
out, err := conn.DescribeClusters(&ecs.DescribeClustersInput{
Clusters: []*string{aws.String(clusterName)},
})
if err != nil {
return err
}
log.Printf("[DEBUG] Received ECS clusters: %#v", out.Clusters)
d.SetId(*out.Clusters[0].ClusterARN)
d.Set("name", *out.Clusters[0].ClusterName)
return nil
}
func resourceAwsEcsClusterDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
log.Printf("[DEBUG] Deleting ECS cluster %s", d.Id())
// TODO: Handle ClientException: The Cluster cannot be deleted while Container Instances are active.
// TODO: Handle ClientException: The Cluster cannot be deleted while Services are active.
out, err := conn.DeleteCluster(&ecs.DeleteClusterInput{
Cluster: aws.String(d.Id()),
})
log.Printf("[DEBUG] ECS cluster %s deleted: %#v", d.Id(), out)
return err
}

View File

@ -0,0 +1,68 @@
package aws
import (
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSEcsCluster(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSEcsClusterDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSEcsCluster,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsClusterExists("aws_ecs_cluster.foo"),
),
},
},
})
}
func testAccCheckAWSEcsClusterDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ecsconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_ecs_cluster" {
continue
}
out, err := conn.DescribeClusters(&ecs.DescribeClustersInput{
Clusters: []*string{aws.String(rs.Primary.ID)},
})
if err == nil {
if len(out.Clusters) != 0 {
return fmt.Errorf("ECS cluster still exists:\n%#v", out.Clusters)
}
}
return err
}
return nil
}
func testAccCheckAWSEcsClusterExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}
return nil
}
}
var testAccAWSEcsCluster = `
resource "aws_ecs_cluster" "foo" {
name = "red-grapes"
}
`

View File

@ -0,0 +1,316 @@
package aws
import (
"bytes"
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
var taskDefinitionRE = regexp.MustCompile("^([a-zA-Z0-9_-]+):([0-9]+)$")
func resourceAwsEcsService() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEcsServiceCreate,
Read: resourceAwsEcsServiceRead,
Update: resourceAwsEcsServiceUpdate,
Delete: resourceAwsEcsServiceDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cluster": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"task_definition": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"desired_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
},
"iam_role": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"load_balancer": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"elb_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"container_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"container_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
},
},
Set: resourceAwsEcsLoadBalancerHash,
},
},
}
}
func resourceAwsEcsServiceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
input := ecs.CreateServiceInput{
ServiceName: aws.String(d.Get("name").(string)),
TaskDefinition: aws.String(d.Get("task_definition").(string)),
DesiredCount: aws.Long(int64(d.Get("desired_count").(int))),
}
if v, ok := d.GetOk("cluster"); ok {
input.Cluster = aws.String(v.(string))
}
loadBalancers := expandEcsLoadBalancers(d.Get("load_balancer").(*schema.Set).List())
if len(loadBalancers) > 0 {
log.Printf("[DEBUG] Adding ECS load balancers: %#v", loadBalancers)
input.LoadBalancers = loadBalancers
}
if v, ok := d.GetOk("iam_role"); ok {
input.Role = aws.String(v.(string))
}
log.Printf("[DEBUG] Creating ECS service: %#v", input)
out, err := conn.CreateService(&input)
if err != nil {
return err
}
service := *out.Service
log.Printf("[DEBUG] ECS service created: %s", *service.ServiceARN)
d.SetId(*service.ServiceARN)
d.Set("cluster", *service.ClusterARN)
return resourceAwsEcsServiceUpdate(d, meta)
}
func resourceAwsEcsServiceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
log.Printf("[DEBUG] Reading ECS service %s", d.Id())
input := ecs.DescribeServicesInput{
Services: []*string{aws.String(d.Id())},
Cluster: aws.String(d.Get("cluster").(string)),
}
out, err := conn.DescribeServices(&input)
if err != nil {
return err
}
service := out.Services[0]
log.Printf("[DEBUG] Received ECS service %#v", service)
d.SetId(*service.ServiceARN)
d.Set("name", *service.ServiceName)
// Save task definition in the same format
if strings.HasPrefix(d.Get("task_definition").(string), "arn:aws:ecs:") {
d.Set("task_definition", *service.TaskDefinition)
} else {
taskDefinition := buildFamilyAndRevisionFromARN(*service.TaskDefinition)
d.Set("task_definition", taskDefinition)
}
d.Set("desired_count", *service.DesiredCount)
d.Set("cluster", *service.ClusterARN)
if service.RoleARN != nil {
d.Set("iam_role", *service.RoleARN)
}
if service.LoadBalancers != nil {
d.Set("load_balancers", flattenEcsLoadBalancers(service.LoadBalancers))
}
return nil
}
func resourceAwsEcsServiceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
log.Printf("[DEBUG] Updating ECS service %s", d.Id())
input := ecs.UpdateServiceInput{
Service: aws.String(d.Id()),
Cluster: aws.String(d.Get("cluster").(string)),
}
if d.HasChange("desired_count") {
_, n := d.GetChange("desired_count")
input.DesiredCount = aws.Long(int64(n.(int)))
}
if d.HasChange("task_definition") {
_, n := d.GetChange("task_definition")
input.TaskDefinition = aws.String(n.(string))
}
out, err := conn.UpdateService(&input)
if err != nil {
return err
}
service := out.Service
log.Printf("[DEBUG] Updated ECS service %#v", service)
return resourceAwsEcsServiceRead(d, meta)
}
func resourceAwsEcsServiceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
// Check if it's not already gone
resp, err := conn.DescribeServices(&ecs.DescribeServicesInput{
Services: []*string{aws.String(d.Id())},
Cluster: aws.String(d.Get("cluster").(string)),
})
if err != nil {
return err
}
log.Printf("[DEBUG] ECS service %s is currently %s", d.Id(), *resp.Services[0].Status)
if *resp.Services[0].Status == "INACTIVE" {
return nil
}
// Drain the ECS service
if *resp.Services[0].Status != "DRAINING" {
log.Printf("[DEBUG] Draining ECS service %s", d.Id())
_, err = conn.UpdateService(&ecs.UpdateServiceInput{
Service: aws.String(d.Id()),
Cluster: aws.String(d.Get("cluster").(string)),
DesiredCount: aws.Long(int64(0)),
})
if err != nil {
return err
}
}
input := ecs.DeleteServiceInput{
Service: aws.String(d.Id()),
Cluster: aws.String(d.Get("cluster").(string)),
}
log.Printf("[DEBUG] Deleting ECS service %#v", input)
out, err := conn.DeleteService(&input)
if err != nil {
return err
}
// Wait until it's deleted
wait := resource.StateChangeConf{
Pending: []string{"DRAINING"},
Target: "INACTIVE",
Timeout: 5 * time.Minute,
MinTimeout: 1 * time.Second,
Refresh: func() (interface{}, string, error) {
log.Printf("[DEBUG] Checking if ECS service %s is INACTIVE", d.Id())
resp, err := conn.DescribeServices(&ecs.DescribeServicesInput{
Services: []*string{aws.String(d.Id())},
Cluster: aws.String(d.Get("cluster").(string)),
})
if err != nil {
return resp, "FAILED", err
}
return resp, *resp.Services[0].Status, nil
},
}
_, err = wait.WaitForState()
if err != nil {
return err
}
log.Printf("[DEBUG] ECS service %s deleted.", *out.Service.ServiceARN)
return nil
}
func resourceAwsEcsLoadBalancerHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["elb_name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["container_name"].(string)))
buf.WriteString(fmt.Sprintf("%d-", m["container_port"].(int)))
return hashcode.String(buf.String())
}
func buildFamilyAndRevisionFromARN(arn string) string {
return strings.Split(arn, "/")[1]
}
func buildTaskDefinitionARN(taskDefinition string, meta interface{}) (string, error) {
// If it's already an ARN, just return it
if strings.HasPrefix(taskDefinition, "arn:aws:ecs:") {
return taskDefinition, nil
}
// Parse out family & revision
family, revision, err := parseTaskDefinition(taskDefinition)
if err != nil {
return "", err
}
iamconn := meta.(*AWSClient).iamconn
region := meta.(*AWSClient).region
// An zero value GetUserInput{} defers to the currently logged in user
resp, err := iamconn.GetUser(&iam.GetUserInput{})
if err != nil {
return "", fmt.Errorf("GetUser ERROR: %#v", err)
}
// arn:aws:iam::0123456789:user/username
userARN := *resp.User.ARN
accountID := strings.Split(userARN, ":")[4]
// arn:aws:ecs:us-west-2:01234567890:task-definition/mongodb:3
arn := fmt.Sprintf("arn:aws:ecs:%s:%s:task-definition/%s:%s",
region, accountID, family, revision)
log.Printf("[DEBUG] Built task definition ARN: %s", arn)
return arn, nil
}
func parseTaskDefinition(taskDefinition string) (string, string, error) {
matches := taskDefinitionRE.FindAllStringSubmatch(taskDefinition, 2)
if len(matches) == 0 || len(matches[0]) != 3 {
return "", "", fmt.Errorf(
"Invalid task definition format, family:rev or ARN expected (%#v)",
taskDefinition)
}
return matches[0][1], matches[0][2], nil
}

View File

@ -0,0 +1,276 @@
package aws
import (
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestParseTaskDefinition(t *testing.T) {
cases := map[string]map[string]interface{}{
"invalid": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"invalidWithColon:": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"1234": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"invalid:aaa": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"invalid=family:1": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"invalid:name:1": map[string]interface{}{
"family": "",
"revision": "",
"isValid": false,
},
"valid:1": map[string]interface{}{
"family": "valid",
"revision": "1",
"isValid": true,
},
"abc12-def:54": map[string]interface{}{
"family": "abc12-def",
"revision": "54",
"isValid": true,
},
"lorem_ip-sum:123": map[string]interface{}{
"family": "lorem_ip-sum",
"revision": "123",
"isValid": true,
},
"lorem-ipsum:1": map[string]interface{}{
"family": "lorem-ipsum",
"revision": "1",
"isValid": true,
},
}
for input, expectedOutput := range cases {
family, revision, err := parseTaskDefinition(input)
isValid := expectedOutput["isValid"].(bool)
if !isValid && err == nil {
t.Fatalf("Task definition %s should fail", input)
}
expectedFamily := expectedOutput["family"].(string)
if family != expectedFamily {
t.Fatalf("Unexpected family (%#v) for task definition %s\n%#v", family, input, err)
}
expectedRevision := expectedOutput["revision"].(string)
if revision != expectedRevision {
t.Fatalf("Unexpected revision (%#v) for task definition %s\n%#v", revision, input, err)
}
}
}
func TestAccAWSEcsServiceWithARN(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSEcsServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSEcsService,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"),
),
},
resource.TestStep{
Config: testAccAWSEcsServiceModified,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo"),
),
},
},
})
}
func TestAccAWSEcsServiceWithFamilyAndRevision(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSEcsServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSEcsServiceWithFamilyAndRevision,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsServiceExists("aws_ecs_service.jenkins"),
),
},
resource.TestStep{
Config: testAccAWSEcsServiceWithFamilyAndRevisionModified,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsServiceExists("aws_ecs_service.jenkins"),
),
},
},
})
}
func testAccCheckAWSEcsServiceDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ecsconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_ecs_service" {
continue
}
out, err := conn.DescribeServices(&ecs.DescribeServicesInput{
Services: []*string{aws.String(rs.Primary.ID)},
})
if err == nil {
if len(out.Services) > 0 {
return fmt.Errorf("ECS service still exists:\n%#v", out.Services)
}
}
return err
}
return nil
}
func testAccCheckAWSEcsServiceExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}
return nil
}
}
var testAccAWSEcsService = `
resource "aws_ecs_cluster" "default" {
name = "terraformecstest1"
}
resource "aws_ecs_task_definition" "mongo" {
family = "mongodb"
container_definitions = <<DEFINITION
[
{
"cpu": 128,
"essential": true,
"image": "mongo:latest",
"memory": 128,
"name": "mongodb"
}
]
DEFINITION
}
resource "aws_ecs_service" "mongo" {
name = "mongodb"
cluster = "${aws_ecs_cluster.default.id}"
task_definition = "${aws_ecs_task_definition.mongo.arn}"
desired_count = 1
}
`
var testAccAWSEcsServiceModified = `
resource "aws_ecs_cluster" "default" {
name = "terraformecstest1"
}
resource "aws_ecs_task_definition" "mongo" {
family = "mongodb"
container_definitions = <<DEFINITION
[
{
"cpu": 128,
"essential": true,
"image": "mongo:latest",
"memory": 128,
"name": "mongodb"
}
]
DEFINITION
}
resource "aws_ecs_service" "mongo" {
name = "mongodb"
cluster = "${aws_ecs_cluster.default.id}"
task_definition = "${aws_ecs_task_definition.mongo.arn}"
desired_count = 2
}
`
var testAccAWSEcsServiceWithFamilyAndRevision = `
resource "aws_ecs_cluster" "default" {
name = "terraformecstest2"
}
resource "aws_ecs_task_definition" "jenkins" {
family = "jenkins"
container_definitions = <<DEFINITION
[
{
"cpu": 128,
"essential": true,
"image": "jenkins:latest",
"memory": 128,
"name": "jenkins"
}
]
DEFINITION
}
resource "aws_ecs_service" "jenkins" {
name = "jenkins"
cluster = "${aws_ecs_cluster.default.id}"
task_definition = "${aws_ecs_task_definition.jenkins.family}:${aws_ecs_task_definition.jenkins.revision}"
desired_count = 1
}
`
var testAccAWSEcsServiceWithFamilyAndRevisionModified = `
resource "aws_ecs_cluster" "default" {
name = "terraformecstest2"
}
resource "aws_ecs_task_definition" "jenkins" {
family = "jenkins"
container_definitions = <<DEFINITION
[
{
"cpu": 128,
"essential": true,
"image": "jenkins:latest",
"memory": 128,
"name": "jenkins"
}
]
DEFINITION
}
resource "aws_ecs_service" "jenkins" {
name = "jenkins"
cluster = "${aws_ecs_cluster.default.id}"
task_definition = "${aws_ecs_task_definition.jenkins.family}:${aws_ecs_task_definition.jenkins.revision}"
desired_count = 1
}
`

View File

@ -0,0 +1,158 @@
package aws
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsEcsTaskDefinition() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEcsTaskDefinitionCreate,
Read: resourceAwsEcsTaskDefinitionRead,
Update: resourceAwsEcsTaskDefinitionUpdate,
Delete: resourceAwsEcsTaskDefinitionDelete,
Schema: map[string]*schema.Schema{
"arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"family": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"revision": &schema.Schema{
Type: schema.TypeInt,
Computed: true,
},
"container_definitions": &schema.Schema{
Type: schema.TypeString,
Required: true,
StateFunc: func(v interface{}) string {
hash := sha1.Sum([]byte(v.(string)))
return hex.EncodeToString(hash[:])
},
},
"volume": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"host_path": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
Set: resourceAwsEcsTaskDefinitionVolumeHash,
},
},
}
}
func resourceAwsEcsTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
rawDefinitions := d.Get("container_definitions").(string)
definitions, err := expandEcsContainerDefinitions(rawDefinitions)
if err != nil {
return err
}
input := ecs.RegisterTaskDefinitionInput{
ContainerDefinitions: definitions,
Family: aws.String(d.Get("family").(string)),
}
if v, ok := d.GetOk("volume"); ok {
volumes, err := expandEcsVolumes(v.(*schema.Set).List())
if err != nil {
return err
}
input.Volumes = volumes
}
log.Printf("[DEBUG] Registering ECS task definition: %#v", input)
out, err := conn.RegisterTaskDefinition(&input)
if err != nil {
return err
}
taskDefinition := *out.TaskDefinition
log.Printf("[DEBUG] ECS task definition registered: %#v (rev. %d)",
*taskDefinition.TaskDefinitionARN, *taskDefinition.Revision)
d.SetId(*taskDefinition.Family)
d.Set("arn", *taskDefinition.TaskDefinitionARN)
return resourceAwsEcsTaskDefinitionRead(d, meta)
}
func resourceAwsEcsTaskDefinitionRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
log.Printf("[DEBUG] Reading task definition %s", d.Id())
out, err := conn.DescribeTaskDefinition(&ecs.DescribeTaskDefinitionInput{
TaskDefinition: aws.String(d.Get("arn").(string)),
})
if err != nil {
return err
}
log.Printf("[DEBUG] Received task definition %#v", out)
taskDefinition := out.TaskDefinition
d.SetId(*taskDefinition.Family)
d.Set("arn", *taskDefinition.TaskDefinitionARN)
d.Set("family", *taskDefinition.Family)
d.Set("revision", *taskDefinition.Revision)
d.Set("container_definitions", taskDefinition.ContainerDefinitions)
d.Set("volumes", flattenEcsVolumes(taskDefinition.Volumes))
return nil
}
func resourceAwsEcsTaskDefinitionUpdate(d *schema.ResourceData, meta interface{}) error {
return resourceAwsEcsTaskDefinitionCreate(d, meta)
}
func resourceAwsEcsTaskDefinitionDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ecsconn
// NOT YET IMPLEMENTED o_O
_, err := conn.DeregisterTaskDefinition(&ecs.DeregisterTaskDefinitionInput{
TaskDefinition: aws.String(d.Id()),
})
log.Printf("[DEBUG] Deregistering task definition %s returned %#v", d.Id(), err)
return nil
}
func resourceAwsEcsTaskDefinitionVolumeHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["host_path"].(string)))
return hashcode.String(buf.String())
}

View File

@ -0,0 +1,111 @@
package aws
import (
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSEcsTaskDefinition(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSEcsTaskDefinition,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsTaskDefinitionExists("aws_ecs_task_definition.jenkins"),
),
},
},
})
}
func testAccCheckAWSEcsTaskDefinitionDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ecsconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_ecs_task_definition" {
continue
}
out, err := conn.DescribeTaskDefinition(&ecs.DescribeTaskDefinitionInput{
TaskDefinition: aws.String(rs.Primary.ID),
})
if err == nil {
if out.TaskDefinition != nil {
return fmt.Errorf("ECS task definition still exists:\n%#v", *out.TaskDefinition)
}
}
return err
}
return nil
}
func testAccCheckAWSEcsTaskDefinitionExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}
return nil
}
}
var testAccAWSEcsTaskDefinition = `
resource "aws_ecs_task_definition" "jenkins" {
family = "jenkins"
container_definitions = <<TASK_DEFINITION
[
{
"cpu": 10,
"command": ["sleep", "10"],
"entryPoint": ["/"],
"environment": [
{"name": "VARNAME", "value": "VARVAL"}
],
"essential": true,
"image": "jenkins",
"links": ["mongodb"],
"memory": 128,
"name": "jenkins",
"portMappings": [
{
"containerPort": 80,
"hostPort": 8080
}
]
},
{
"cpu": 10,
"command": ["sleep", "10"],
"entryPoint": ["/"],
"essential": true,
"image": "mongodb",
"memory": 128,
"name": "mongodb",
"portMappings": [
{
"containerPort": 28017,
"hostPort": 28017
}
]
}
]
TASK_DEFINITION
volume {
name = "jenkins-home"
host_path = "/ecs/jenkins-home"
}
}
`

View File

@ -1,12 +1,15 @@
package aws
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/aws/aws-sdk-go/service/route53"
@ -42,6 +45,64 @@ func expandListeners(configured []interface{}) ([]*elb.Listener, error) {
return listeners, nil
}
// Takes the result of flatmap. Expand for an array of listeners and
// returns ECS Volume compatible objects
func expandEcsVolumes(configured []interface{}) ([]*ecs.Volume, error) {
volumes := make([]*ecs.Volume, 0, len(configured))
// Loop over our configured volumes and create
// an array of aws-sdk-go compatible objects
for _, lRaw := range configured {
data := lRaw.(map[string]interface{})
l := &ecs.Volume{
Name: aws.String(data["name"].(string)),
Host: &ecs.HostVolumeProperties{
SourcePath: aws.String(data["host_path"].(string)),
},
}
volumes = append(volumes, l)
}
return volumes, nil
}
// Takes JSON in a string. Decodes JSON into
// an array of ecs.ContainerDefinition compatible objects
func expandEcsContainerDefinitions(rawDefinitions string) ([]*ecs.ContainerDefinition, error) {
var definitions []*ecs.ContainerDefinition
err := json.Unmarshal([]byte(rawDefinitions), &definitions)
if err != nil {
return nil, fmt.Errorf("Error decoding JSON: %s", err)
}
return definitions, nil
}
// Takes the result of flatmap. Expand for an array of load balancers and
// returns ecs.LoadBalancer compatible objects
func expandEcsLoadBalancers(configured []interface{}) []*ecs.LoadBalancer {
loadBalancers := make([]*ecs.LoadBalancer, 0, len(configured))
// Loop over our configured load balancers and create
// an array of aws-sdk-go compatible objects
for _, lRaw := range configured {
data := lRaw.(map[string]interface{})
l := &ecs.LoadBalancer{
ContainerName: aws.String(data["container_name"].(string)),
ContainerPort: aws.Long(int64(data["container_port"].(int))),
LoadBalancerName: aws.String(data["elb_name"].(string)),
}
loadBalancers = append(loadBalancers, l)
}
return loadBalancers
}
// Takes the result of flatmap.Expand for an array of ingress/egress security
// group rules and returns EC2 API compatible objects. This function will error
// if it finds invalid permissions input, namely a protocol of "-1" with either
@ -215,6 +276,44 @@ func flattenListeners(list []*elb.ListenerDescription) []map[string]interface{}
return result
}
// Flattens an array of Volumes into a []map[string]interface{}
func flattenEcsVolumes(list []*ecs.Volume) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, volume := range list {
l := map[string]interface{}{
"name": *volume.Name,
"host_path": *volume.Host.SourcePath,
}
result = append(result, l)
}
return result
}
// Flattens an array of ECS LoadBalancers into a []map[string]interface{}
func flattenEcsLoadBalancers(list []*ecs.LoadBalancer) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, loadBalancer := range list {
l := map[string]interface{}{
"elb_name": *loadBalancer.LoadBalancerName,
"container_name": *loadBalancer.ContainerName,
"container_port": *loadBalancer.ContainerPort,
}
result = append(result, l)
}
return result
}
// Encodes an array of ecs.ContainerDefinitions into a JSON string
func flattenEcsContainerDefinitions(definitions []*ecs.ContainerDefinition) (string, error) {
byteArray, err := json.Marshal(definitions)
if err != nil {
return "", fmt.Errorf("Error encoding to JSON: %s", err)
}
n := bytes.Index(byteArray, []byte{0})
return string(byteArray[:n]), nil
}
// Flattens an array of Parameters into a []map[string]interface{}
func flattenParameters(list []*rds.Parameter) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))

View File

@ -0,0 +1,32 @@
---
layout: "aws"
page_title: "AWS: aws_ecs_cluster"
sidebar_current: "docs-aws-resource-ecs-cluster"
description: |-
Provides an ECS cluster.
---
# aws\_ecs\_cluster
Provides an ECS cluster.
## Example Usage
```
resource "aws_ecs_cluster" "foo" {
name = "white-hart"
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) The name of the cluster (up to 255 letters, numbers, hyphens, and underscores)
## Attributes Reference
The following attributes are exported:
* `name` - The name of the cluster
* `id` - The Amazon Resource Name (ARN) that identifies the cluster

View File

@ -0,0 +1,59 @@
---
layout: "aws"
page_title: "AWS: aws_ecs_service"
sidebar_current: "docs-aws-resource-ecs-service"
description: |-
Provides an ECS service.
---
# aws\_ecs\_service
Provides an ECS service - effectively a task that is expected to run until an error occures or user terminates it (typically a webserver or a database).
See [ECS Services section in AWS developer guide](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html).
## Example Usage
```
resource "aws_ecs_service" "mongo" {
name = "mongodb"
cluster = "${aws_ecs_cluster.foo.id}"
task_definition = "${aws_ecs_task_definition.mongo.arn}"
desired_count = 3
iam_role = "${aws_iam.foo.id}"
load_balancer {
elb_name = "${aws_elb.foo.id}"
container_name = "mongo"
container_port = 8080
}
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) The name of the service (up to 255 letters, numbers, hyphens, and underscores)
* `task_definition` - (Required) The family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service.
* `desired_count` - (Required) The number of instances of the task definition to place and keep running
* `cluster` - (Optional) ARN of an ECS cluster
* `iam_role` - (Optional) IAM role that allows your Amazon ECS container agent to make calls to your load balancer on your behalf. This parameter is only required if you are using a load balancer with your service.
* `load_balancer` - (Optional) A load balancer block. Load balancers documented below.
Load balancers support the following:
* `elb_name` - (Required) The name of the load balancer.
* `container_name` - (Required) The name of the container to associate with the load balancer (as it appears in a container definition).
* `container_port` - (Required) The port on the container to associate with the load balancer.
## Attributes Reference
The following attributes are exported:
* `id` - The Amazon Resource Name (ARN) that identifies the service
* `name` - The name of the service
* `cluster` - The Amazon Resource Name (ARN) of cluster which the service runs on
* `iam_role` - The ARN of IAM role used for ELB
* `desired_count` - The number of instances of the task definition

View File

@ -0,0 +1,50 @@
---
layout: "aws"
page_title: "AWS: aws_ecs_task_definition"
sidebar_current: "docs-aws-resource-ecs-task-definition"
description: |-
Provides an ECS task definition.
---
# aws\_ecs\_task\_definition
Provides an ECS task definition to be used in `aws_ecs_service`.
~> **NOTE:** There is currently no way to unregister
any previously registered task definition.
See related [thread in AWS forum](https://forums.aws.amazon.com/thread.jspa?threadID=170378&tstart=0).
## Example Usage
```
resource "aws_ecs_task_definition" "jenkins" {
family = "jenkins"
container_definitions = "${file("task-definitions/jenkins.json")}"
volume {
name = "jenkins-home"
host_path = "/ecs/jenkins-home"
}
}
```
## Argument Reference
The following arguments are supported:
* `family` - (Required) The family, unique name for your task definition.
* `container_definitions` - (Required) A list of container definitions in JSON format. See [AWS docs](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html) for syntax.
* `volume` - (Optional) A volume block. Volumes documented below.
Volumes support the following:
* `name` - (Required) The name of the volume. This name is referenced in the `sourceVolume` parameter of container definition `mountPoints`.
* `host_path` - (Required) The path on the host container instance that is presented to the container.
## Attributes Reference
The following attributes are exported:
* `arn` - Full ARN of the task definition (including both `family` & `revision`)
* `family` - The family of the task definition.
* `revision` - The revision of the task in a particular family.

View File

@ -41,6 +41,18 @@
<a href="/docs/providers/aws/r/ebs_volume.html">aws_ebs_volume</a>
</li>
<li<%= sidebar_current("docs-aws-resource-ecs-cluster") %>>
<a href="/docs/providers/aws/r/ecs_cluster.html">aws_ecs_cluster</a>
</li>
<li<%= sidebar_current("docs-aws-resource-ecs-service") %>>
<a href="/docs/providers/aws/r/ecs_service.html">aws_ecs_service</a>
</li>
<li<%= sidebar_current("docs-aws-resource-ecs-task-definition") %>>
<a href="/docs/providers/aws/r/ecs_task_definition.html">aws_ecs_task_definition</a>
</li>
<li<%= sidebar_current("docs-aws-resource-eip") %>>
<a href="/docs/providers/aws/r/eip.html">aws_eip</a>
</li>