<commit_before>#Configure the AWS Provider
provider "aws" {
  region  = "${var.aws_region}"
  version = "~> 0.1"
}

provider "random" {
  version = "~> 0.1"
}

module "image" {
  source = "github.com/gozer/nubis-deploy//modules/images?ref=feature%2Farena"

  region = "${var.aws_region}"
  version = "${var.nubis_version}"
  project = "nubis-consul"
}

resource "aws_sns_topic" "graceful_termination" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-${element(var.arenas, count.index)}-${var.aws_region}-termination"
}

resource "aws_iam_role" "autoscaling_role" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "autoscaling.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_autoscaling_lifecycle_hook" "graceful_shutdown_asg_hook" {
    count = "${var.enabled * length(var.arenas)}"
    name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
    autoscaling_group_name = "${element(aws_autoscaling_group.consul.*.name, count.index)}"
    default_result = "CONTINUE"
    heartbeat_timeout = 60
    lifecycle_transition = "autoscaling:EC2_INSTANCE_TERMINATING"
    notification_target_arn = "${element(aws_sns_topic.graceful_termination.*.arn, count.index)}"
    role_arn = "${element(aws_iam_role.autoscaling_role.*.arn, count.index)}"
}

resource "aws_iam_role_policy" "lifecycle_hook_autoscaling_policy" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
  role = "${element(aws_iam_role.autoscaling_role.*.id, count.index)}"
  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "sns",
            "Effect": "Allow",
            "Action": [
	        "sns:Publish"
            ],
            "Resource": [
                "${element(aws_sns_topic.graceful_termination.*.arn, count.index)}"
            ]
        }
    ]
}
POLICY
}

resource "aws_launch_configuration" "consul" {
  count = "${var.enabled * length(var.arenas)}"

  depends_on = [
    "null_resource.secrets",
    "null_resource.secrets-public",
  ]

  lifecycle {
    create_before_destroy = true
  }

  name_prefix = "${var.project}-${element(var.arenas, count.index)}-${var.aws_region}-"
  image_id = "${module.image.image_id}"

  instance_type        = "t2.small"
  key_name             = "${var.key_name}"
  iam_instance_profile = "${element(aws_iam_instance_profile.consul.*.name, count.index)}"
  enable_monitoring    = false

  security_groups = [
    "${element(aws_security_group.consul.*.id, count.index)}",
    "${element(split(",",var.internet_access_security_groups), count.index)}",
    "${element(split(",",var.shared_services_security_groups), count.index)}",
  ]

  user_data = <<EOF
NUBIS_PROJECT=${var.project}
NUBIS_ARENA=${element(var.arenas, count.index)}
NUBIS_ACCOUNT=${var.service_name}
NUBIS_DOMAIN=${var.domain}
CONSUL_ZONE_ID="${element(aws_route53_zone.consul.*.zone_id, count.index)}"
CONSUL_ACL_DEFAULT_POLICY=${var.acl_default_policy}
CONSUL_ACL_DOWN_POLICY=${var.acl_down_policy}
CONSUL_BOOTSTRAP_EXPECT=${var.servers}
CONSUL_TERMINATION_TOPIC=${element(aws_sns_topic.graceful_termination.*.id, count.index)}
NUBIS_BUMP=${md5("${var.mig["ca_cert"]}${var.mig["agent_cert"]}${var.mig["agent_key"]}${var.mig["relay_user"]}${var.mig["relay_password"]}${var.instance_mfa["ikey"]}${var.instance_mfa["skey"]}${var.instance_mfa["host"]}${var.instance_mfa["failmode"]}")}
NUBIS_SUDO_GROUPS="${var.nubis_sudo_groups}"
NUBIS_USER_GROUPS="${var.nubis_user_groups}"
EOF
}

resource "aws_autoscaling_group" "consul" {
  count = "${var.enabled * length(var.arenas)}"

  lifecycle {
    create_before_destroy = true
  }

  #XXX: Fugly, assumes 3 subnets per arenas, bad assumption, but valid ATM
  vpc_zone_identifier = [
    "${element(split(",",var.private_subnets), (count.index * 3) + 0 )}",
    "${element(split(",",var.private_subnets), (count.index * 3) + 1 )}",
    "${element(split(",",var.private_subnets), (count.index * 3) + 2 )}",
  ]

  name = "${var.project}-${element(var.arenas, count.index)} (LC ${element(aws_launch_configuration.consul.*.name, count.index)})"

  max_size                  = "${var.servers}"
  min_size                  = "${var.servers}"
  health_check_grace_period = 300
  health_check_type         = "ELB"
  desired_capacity          = "${var.servers}"
  force_delete              = true
  launch_configuration      = "${element(aws_launch_configuration.consul.*.name, count.index)}"

  # This resource isn't considered created by TF until we have var.servers in rotation
  #  wait_for_elb_capacity = "${var.servers - 1}"
  wait_for_elb_capacity = "${var.servers}"

  wait_for_capacity_timeout = "60m"

  enabled_metrics = [
    "GroupMinSize",
    "GroupMaxSize",
    "GroupDesiredCapacity",
    "GroupInServiceInstances",
  ]

  load_balancers = [
    "${element(aws_elb.consul.*.name, count.index)}",
  ]

  tag {
    key                 = "Name"
    value               = "Consul server node (${var.nubis_version}) for ${var.service_name} in ${element(var.arenas, count.index)}"
    propagate_at_launch = true
  }

  tag {
    key                 = "ServiceName"
    value               = "${var.project}"
    propagate_at_launch = true
  }

  tag {
    key                 = "Arena"
    value               = "${element(var.arenas, count.index)}"
    propagate_at_launch = true
  }

  tag {<commit_msg>enabled_metrics++<commit_after>#Configure the AWS Provider
provider "aws" {
  region  = "${var.aws_region}"
  version = "~> 0.1"
}

provider "random" {
  version = "~> 0.1"
}

module "image" {
  source = "github.com/gozer/nubis-deploy//modules/images?ref=feature%2Farena"

  region = "${var.aws_region}"
  version = "${var.nubis_version}"
  project = "nubis-consul"
}

resource "aws_sns_topic" "graceful_termination" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-${element(var.arenas, count.index)}-${var.aws_region}-termination"
}

resource "aws_iam_role" "autoscaling_role" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "autoscaling.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_autoscaling_lifecycle_hook" "graceful_shutdown_asg_hook" {
    count = "${var.enabled * length(var.arenas)}"
    name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
    autoscaling_group_name = "${element(aws_autoscaling_group.consul.*.name, count.index)}"
    default_result = "CONTINUE"
    heartbeat_timeout = 60
    lifecycle_transition = "autoscaling:EC2_INSTANCE_TERMINATING"
    notification_target_arn = "${element(aws_sns_topic.graceful_termination.*.arn, count.index)}"
    role_arn = "${element(aws_iam_role.autoscaling_role.*.arn, count.index)}"
}

resource "aws_iam_role_policy" "lifecycle_hook_autoscaling_policy" {
  count = "${var.enabled * length(var.arenas)}"
  name = "${var.project}-termination-${element(var.arenas, count.index)}-${var.aws_region}"
  role = "${element(aws_iam_role.autoscaling_role.*.id, count.index)}"
  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "sns",
            "Effect": "Allow",
            "Action": [
	        "sns:Publish"
            ],
            "Resource": [
                "${element(aws_sns_topic.graceful_termination.*.arn, count.index)}"
            ]
        }
    ]
}
POLICY
}

resource "aws_launch_configuration" "consul" {
  count = "${var.enabled * length(var.arenas)}"

  depends_on = [
    "null_resource.secrets",
    "null_resource.secrets-public",
  ]

  lifecycle {
    create_before_destroy = true
  }

  name_prefix = "${var.project}-${element(var.arenas, count.index)}-${var.aws_region}-"
  image_id = "${module.image.image_id}"

  instance_type        = "t2.small"
  key_name             = "${var.key_name}"
  iam_instance_profile = "${element(aws_iam_instance_profile.consul.*.name, count.index)}"
  enable_monitoring    = false

  security_groups = [
    "${element(aws_security_group.consul.*.id, count.index)}",
    "${element(split(",",var.internet_access_security_groups), count.index)}",
    "${element(split(",",var.shared_services_security_groups), count.index)}",
  ]

  user_data = <<EOF
NUBIS_PROJECT=${var.project}
NUBIS_ARENA=${element(var.arenas, count.index)}
NUBIS_ACCOUNT=${var.service_name}
NUBIS_DOMAIN=${var.domain}
CONSUL_ZONE_ID="${element(aws_route53_zone.consul.*.zone_id, count.index)}"
CONSUL_ACL_DEFAULT_POLICY=${var.acl_default_policy}
CONSUL_ACL_DOWN_POLICY=${var.acl_down_policy}
CONSUL_BOOTSTRAP_EXPECT=${var.servers}
CONSUL_TERMINATION_TOPIC=${element(aws_sns_topic.graceful_termination.*.id, count.index)}
NUBIS_BUMP=${md5("${var.mig["ca_cert"]}${var.mig["agent_cert"]}${var.mig["agent_key"]}${var.mig["relay_user"]}${var.mig["relay_password"]}${var.instance_mfa["ikey"]}${var.instance_mfa["skey"]}${var.instance_mfa["host"]}${var.instance_mfa["failmode"]}")}
NUBIS_SUDO_GROUPS="${var.nubis_sudo_groups}"
NUBIS_USER_GROUPS="${var.nubis_user_groups}"
EOF
}

resource "aws_autoscaling_group" "consul" {
  count = "${var.enabled * length(var.arenas)}"

  lifecycle {
    create_before_destroy = true
  }

  #XXX: Fugly, assumes 3 subnets per arenas, bad assumption, but valid ATM
  vpc_zone_identifier = [
    "${element(split(",",var.private_subnets), (count.index * 3) + 0 )}",
    "${element(split(",",var.private_subnets), (count.index * 3) + 1 )}",
    "${element(split(",",var.private_subnets), (count.index * 3) + 2 )}",
  ]

  name = "${var.project}-${element(var.arenas, count.index)} (LC ${element(aws_launch_configuration.consul.*.name, count.index)})"

  max_size                  = "${var.servers}"
  min_size                  = "${var.servers}"
  health_check_grace_period = 300
  health_check_type         = "ELB"
  desired_capacity          = "${var.servers}"
  force_delete              = true
  launch_configuration      = "${element(aws_launch_configuration.consul.*.name, count.index)}"

  # This resource isn't considered created by TF until we have var.servers in rotation
  #  wait_for_elb_capacity = "${var.servers - 1}"
  wait_for_elb_capacity = "${var.servers}"

  wait_for_capacity_timeout = "60m"

  enabled_metrics = [
    "GroupMinSize",
    "GroupMaxSize",
    "GroupDesiredCapacity",
    "GroupInServiceInstances",
    "GroupPendingInstances",
    "GroupStandbyInstances",
    "GroupTerminatingInstances",
    "GroupTotalInstances",
  ]

  load_balancers = [
    "${element(aws_elb.consul.*.name, count.index)}",
  ]

  tag {
    key                 = "Name"
    value               = "Consul server node (${var.nubis_version}) for ${var.service_name} in ${element(var.arenas, count.index)}"
    propagate_at_launch = true
  }

  tag {
    key                 = "ServiceName"
    value               = "${var.project}"
    propagate_at_launch = true
  }

  tag {
    key                 = "Arena"
    value               = "${element(var.arenas, count.index)}"
    propagate_at_launch = true
  }

  tag {
{'fraction_non_alphanumeric': 0.16856846473029047, 'fraction_numerical': 0.0070885200553250345, 'mean_word_length': 3.7433374333743337, 'pattern_counts': {'":': 26, '<': 15, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2814519', 'n_tokens_mistral': 4260, 'n_tokens_neox': 4132, 'n_words': 548}