How to Deploy IAM conditional policies with Terraform

Updated: Apr 25

Nowadays, AWS is the top cloud provider around the world and has a wide variety of services that are provided to us One of the most important services is IAM (Identity and Access Management).

Here, we can manage the correct Access to AWS services and resources in a secure way and the best part is this is a free feature, so there is no additional charge.

The way to manage the Access and permissions is by creating IAM Policies.

Once we have the policies created, the correct way to work is to assign them to groups, and then assign our users to these groups.

This is a good practice to have our users organized and at the same time the policies assigned directly to the group to which they belong.

Another good practice and advice when working with permissions is what is known as “least privilege”, which implies always granting only the MINIMUM permissions that are necessary for our users to operate correctly, and no more than that.

Using Terraform (Infrastructure as Code) we can also deploy this, but sometimes, we need to create a policy that has more than one conditional, like the JSON code below:

{
 
"Effect": "Allow",
 
"Action": [
 
"ec2:CreateTags"
 
],
 
"Resource": "arn:aws:ec2:*:*:security-group/*",
 
"Condition": {
 
"StringEquals": {
 
"ec2:CreateAction": "CreateSecurityGroup"
 
},
 
"Null": {
 
"aws:RequestTag/elbv2.k8s.aws/cluster": "false"
 
}
 
}
 
}
 

 

So here, the solution could be like this:

statement {
 
actions = ["ec2:CreateTags"]
 
resources = ["arn:aws:ec2:*:*:security-group/*"]
 

 
condition {
 
test = "StringEquals"
 
variable = "ec2:CreateAction"
 
values = ["CreateSecurityGroup"]
 
}
 

 
condition {
 
test = "Null"
 
variable = "aws:RequestTag/elbv2.k8s.aws/cluster"
 
values = ["false"]
 
}

What we do here, is separate each conditional with its variables and values.

In this way, we can convert a JSON policy with more than one conditional to terraform.

    0