Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

r/ecs_service: Add NetworkConfiguration #2299

Merged
merged 2 commits into from
Dec 4, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion aws/resource_aws_ecs_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func resourceAwsEcsService() *schema.Resource {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Computed: true,
},

"deployment_maximum_percent": {
Expand Down Expand Up @@ -101,7 +102,25 @@ func resourceAwsEcsService() *schema.Resource {
},
Set: resourceAwsEcsLoadBalancerHash,
},

"network_configuration": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"security_groups": {
Type: schema.TypeList,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the ordering of SGs is not significant shouldn't this field be TypeSet to avoid potential spurious diffs in case the list of SGs comes back in a different order from the API?

Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"subnets": {
Type: schema.TypeList,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the ordering of subnets is not significant shouldn't this field be TypeSet to avoid potential spurious diffs in case the list of subnets comes back in a different order from the API?

Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"placement_strategy": {
Type: schema.TypeSet,
Optional: true,
Expand Down Expand Up @@ -194,6 +213,8 @@ func resourceAwsEcsServiceCreate(d *schema.ResourceData, meta interface{}) error
input.Role = aws.String(v.(string))
}

input.NetworkConfiguration = expandEcsNetworkConfigration(d.Get("network_configuration").([]interface{}))

strategies := d.Get("placement_strategy").(*schema.Set).List()
if len(strategies) > 0 {
var ps []*ecs.PlacementStrategy
Expand Down Expand Up @@ -353,9 +374,36 @@ func resourceAwsEcsServiceRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("[ERR] Error setting placement_constraints for (%s): %s", d.Id(), err)
}

if err := d.Set("network_configuration", flattenEcsNetworkConfigration(service.NetworkConfiguration)); err != nil {
log.Printf("[ERR] Error setting network_configuration for (%s): %s", d.Id(), err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason why we should silently fail here instead of returning error?

}

return nil
}

func flattenEcsNetworkConfigration(nc *ecs.NetworkConfiguration) []interface{} {
if nc == nil {
return nil
}
result := make(map[string]interface{})
result["security_groups"] = flattenStringList(nc.AwsvpcConfiguration.SecurityGroups)
result["subnets"] = flattenStringList(nc.AwsvpcConfiguration.Subnets)
return []interface{}{result}
}

func expandEcsNetworkConfigration(nc []interface{}) *ecs.NetworkConfiguration {
if len(nc) == 0 {
return nil
}
awsVpcConfig := &ecs.AwsVpcConfiguration{}
raw := nc[0].(map[string]interface{})
if val, ok := raw["security_groups"]; ok {
awsVpcConfig.SecurityGroups = expandStringList(val.([]interface{}))
}
awsVpcConfig.Subnets = expandStringList(raw["subnets"].([]interface{}))
return &ecs.NetworkConfiguration{AwsvpcConfiguration: awsVpcConfig}
}

func flattenServicePlacementConstraints(pcs []*ecs.PlacementConstraint) []map[string]interface{} {
if len(pcs) == 0 {
return nil
Expand Down Expand Up @@ -418,6 +466,10 @@ func resourceAwsEcsServiceUpdate(d *schema.ResourceData, meta interface{}) error
}
}

if d.HasChange("network_configration") {
input.NetworkConfiguration = expandEcsNetworkConfigration(d.Get("network_configuration").([]interface{}))
}

// Retry due to IAM & ECS eventual consistency
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
out, err := conn.UpdateService(&input)
Expand Down
90 changes: 90 additions & 0 deletions aws/resource_aws_ecs_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,22 @@ func TestAccAWSEcsServiceWithPlacementConstraints_emptyExpression(t *testing.T)
})
}

func TestAccAWSEcsServiceWithNetworkConfiguration(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSEcsServiceDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSEcsServiceWithNetworkConfigration(acctest.RandString(5)),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSEcsServiceExists("aws_ecs_service.main"),
),
},
},
})
}

func testAccCheckAWSEcsServiceDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ecsconn

Expand Down Expand Up @@ -1074,3 +1090,77 @@ resource "aws_ecs_service" "with_alb" {
}
`, rName, rName, rName, rName, rName, rName, rName)
}

func testAccAWSEcsServiceWithNetworkConfigration(rName string) string {
return fmt.Sprintf(`
data "aws_availability_zones" "available" {}

resource "aws_vpc" "main" {
cidr_block = "10.10.0.0/16"
}

resource "aws_subnet" "main" {
count = 2
cidr_block = "${cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)}"
availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
vpc_id = "${aws_vpc.main.id}"
}

resource "aws_security_group" "allow_all_a" {
name = "allow_all_a"
description = "Allow all inbound traffic"
vpc_id = "${aws_vpc.main.id}"

ingress {
protocol = "6"
from_port = 80
to_port = 8000
cidr_blocks = ["${aws_vpc.main.cidr_block}"]
}
}

resource "aws_security_group" "allow_all_b" {
name = "allow_all_b"
description = "Allow all inbound traffic"
vpc_id = "${aws_vpc.main.id}"

ingress {
protocol = "6"
from_port = 80
to_port = 8000
cidr_blocks = ["${aws_vpc.main.cidr_block}"]
}
}

resource "aws_ecs_cluster" "main" {
name = "tf-ecs-cluster-%s"
}

resource "aws_ecs_task_definition" "mongo" {
family = "mongodb"
network_mode = "awsvpc"
container_definitions = <<DEFINITION
[
{
"cpu": 128,
"essential": true,
"image": "mongo:latest",
"memory": 128,
"name": "mongodb"
}
]
DEFINITION
}

resource "aws_ecs_service" "main" {
name = "tf-ecs-service-%s"
cluster = "${aws_ecs_cluster.main.id}"
task_definition = "${aws_ecs_task_definition.mongo.arn}"
desired_count = 1
network_configuration {
security_groups = ["${aws_security_group.allow_all_a.id}", "${aws_security_group.allow_all_b.id}"]
subnets = ["${aws_subnet.main.*.id}"]
}
}
`, rName, rName)
}
1 change: 1 addition & 0 deletions aws/resource_aws_ecs_task_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ func validateAwsEcsTaskDefinitionNetworkMode(v interface{}, k string) (ws []stri
validTypes := map[string]struct{}{
"bridge": {},
"host": {},
"awsvpc": {},
"none": {},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not necessarily a blocker for this PR, but I'm pondering with an idea of removing this validation completely as theoretically the list may grow again (knowing how complex and big the container networking "market" is). What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my opinion, it's better to prevent error as early as possible. When constructing state is better than when requesting API.
So I disagree with you.
Of course, I understood your concern but it won't release new network mode as soon as modifying codes coudn't follow it.

Copy link
Contributor Author

@atsushi-ishibashi atsushi-ishibashi Dec 2, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My opinion comes from users' perspective but you have to consider maintainability more than me...
Finally I respect your decision👍

}

Expand Down
6 changes: 6 additions & 0 deletions website/docs/r/ecs_service.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ into consideration during task placement. The maximum number of
* `load_balancer` - (Optional) A load balancer block. Load balancers documented below.
* `placement_constraints` - (Optional) rules that are taken into consideration during task placement. Maximum number of
`placement_constraints` is `10`. Defined below.
* `network_configuration` - (Optional) The network configuration for the service. This parameter is required for task definitions that use the awsvpc network mode to receive their own Elastic Network Interface, and it is not supported for other network modes.

-> **Note:** As a result of an AWS limitation, a single `load_balancer` can be attached to the ECS service at most. See [related docs](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-load-balancing.html#load-balancing-concepts).

Expand Down Expand Up @@ -93,7 +94,12 @@ For more information, see [Cluster Query Language in the Amazon EC2 Container
Service Developer
Guide](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query-language.html).

## network_configuration

`network_configuration` support the following:
* `subnets` - (Required) The subnets associated with the task or service.
* `security_groups` - (Optional) The security groups associated with the task or service. If you do not specify a security group, the default security group for the VPC is used.
For more information, see [Task Networking](http://docs.aws.amazon.com/AmazonECS/latest/developerguidetask-networking.html)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation has already been fixed in #2694

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, but it is still wrong, in fact, the link is https.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ozbillwang Sure. Thanks!


## Attributes Reference

Expand Down
2 changes: 1 addition & 1 deletion website/docs/r/ecs_task_definition.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ definition document. For a detailed description of what parameters are available
(https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html) section from the
official [Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide).
* `task_role_arn` - (Optional) The ARN of IAM role that allows your Amazon ECS container task to make calls to other AWS services.
* `network_mode` - (Optional) The Docker networking mode to use for the containers in the task. The valid values are `none`, `bridge`, and `host`.
* `network_mode` - (Optional) The Docker networking mode to use for the containers in the task. The valid values are `none`, `bridge`, `awsvpc`, and `host`.
* `volume` - (Optional) A set of [volume blocks](#volume-block-arguments) that containers in your task may use.
* `placement_constraints` - (Optional) A set of [placement constraints](#placement-constraints-arguments) rules that are taken into consideration during task placement. Maximum number of `placement_constraints` is `10`.

Expand Down