23 March 2016

Terraforming Amazon AWS for giving a Group the Restart Policy of EC2 instances

We are managing our Amazon AWS infrastructure with Terraform.

If you have no idea what Terraform is, below is a short description:

"Terraform is a tool for building, changing, and versioning Cloud infrastructure.
Configuration files describe to Terraform the components needed to run a single application or your entire datacenter. Terraform generates an execution plan describing what it will do to reach the desired state, and then executes it to build the described infrastructure. 
The infrastructure Terraform can manage includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features.
Infrastructure as Code: Infrastructure is described using a high-level configuration syntax. This allows a blueprint of your datacenter to be versioned and treated as you would any other code. Additionally, infrastructure can be shared and re-used."

We are usually assigning read only policy to our DevOps team for safety reasons. Our needs has recently been changed and we needed to allow our DevOps team to Start, Stop and Restart the EC2 instances.

Following is what I come up with via Terraform:

Terraform file for defining new IAM policy and attaching it to our target DevOps group:

resource "aws_iam_policy" "devops-aws-EC2RestartAccess" {
    name        = "devops-aws-EC2RestartAccess"
    description = "Allowing devops to Restart EC2 instances"
    path        = "/"
    policy      = "${file("${path.module}/aws-EC2RestartAccess.policy")}"
}
resource "aws_iam_policy_attachment" "devops-aws-EC2RestartAccess" {
    name = "devops-aws-EC2RestartAccess"
    groups = ["${aws_iam_group.devops.name}"]
    policy_arn = "${aws_iam_policy.devops-aws-EC2RestartAccess.arn}"
}
And the policy file:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:StartInstances",
        "ec2:StopInstances",
        "ec2:RebootInstances"
      ],
      "Resource": "*"
    }
  ]
}