Terraform IAM Policies
One of the things that i do a lot of, is create identical IAM policies for new AWS accounts that we are onboarding. In order to simplify this, i have created a terraform script that will deploy the relevant polcieis and ensure they are able to communicate with the Master account which allows our Service Desk to switch into new AWS accounts.
This post assumes that you have already configured your aws .credentials and .config files in order to access the environment.
Terraform Files
There are 3 files that you need in order to replicate the policies.
- iam.tf
- policy.tf
- provider.tf
policy.tf
In order to create a policy, you need to define the policy permissions. We regularly use LogicMonitor to monitor any new AWS accounts (the actions have been reduced make this more readable).
resource "aws_iam_policy" "lm_policy" {
name = "aws_logicmonitor_policy"
policy = <<-EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"states:DescribeStateMachine",
"lambda:GetFunctionConfiguration",
"athena:ListWorkGroups",
"s3:List*",
"support:*",
"kinesis:ListTagsForStream",
"redshift:DescribeClusters",
"s3:GetBucketLocation"
],
"Resource": "*"
}
]
}
EOF
}
This is a much reduced list of actions, but you get the idea. You can add more lists, reads and primarily readOnly actions to ensure your policy isn’t able to make any changes.
iam.tf
Once the policy file is created, you need to create a role that can use the policy.
resource "aws_iam_role" "lm_role" {
name = "aws_logicmonitor"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<accountid>:root"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "<This is specific to each account being added into LogicMonitor>"
}
}
}
]
}
EOF
This will create the role that will use the policy, but we need to attach them together.
resource "aws_iam_role_policy_attachment" "lm_attach" {
role = aws_iam_role.lm_role.name
policy_arn = aws_iam_policy.lm_policy.arn
}
Add the above snippet into the iam.tf file and it will attach the policy to the role for LogicMonitor. These files can then be extended to add additional roles and policies as required.
This should speed up the deployment of standard roles for an AWS account. One thing i would like to make better is to run these in multiple accounts at the same time.