Reading the title you might be coming to a perspective that I do not have right access. But I do have admin access. So here is my sceneraio.
I have a Service control policy enabled that denies resource creation if specific tags are absent. So if I create a ec2 instance and a volume that does not have mandatory tag it denies creation with error "UnauthorizedOperation: You are not authorized to perform this operation."
This is working perfectly fine from console but when I use terraform for ec2 creation it is showing me the same error that I am not authorized even though I have added the tags.
This is my SCP that has been enabled.
{
"Sid": "DenyEC2CreationSCP1",
"Effect": "Deny",
"Action": [
"ec2:RunInstances"
],
"Resource": [
"arn:aws:ec2:us-east-1:*:instance/*",
"arn:aws:ec2:us-east-1:*:volume/*"
],
"Condition": {
"Null": {
"aws:RequestTag/owner": "true"
}
}
}
This is my terraform script
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
alias = "virginia"
}
resource "aws_instance" "ec2_instance" {
ami = "ami-051f7e7f640dc1"
count = "1"
instance_type = "t3.medium"
key_name = "keypair"
vpc_security_group_ids = ["sg-xyz", "sg-abc"]
subnet_id = "subnet-xyz"
tags = {
owner = "aws"
}
root_block_device {
delete_on_termination = true
encrypted = true
tags = {
owner = "aws"
}
volume_size = 8
volume_type = "gp2"
}
}
Any sort of help will be appreciated. Thank you.
Your goal is to deny the EC2 creation if necessary tags are not added while creating. But while trying to create EC2 through terraform, it is getting denied by your SCP policy because terraform first creates the instance, and then attempts to add the tags. This creates an issue for RequestTag because this requires the tags be added at resource creation and not after the resource creation as such is causing an access to be denied.
This points to the reason why you are able to perform exactly the same action using the console/ CloudFormation with no issue but Terraform is encountering issues.
At this point I would say that if you are looking to continue with automating this process I would recommend using CloudFormation as this issue has already been resolved on that service. Otherwise it may be required that you remove this condition from the SCP such that Terraform can perform this action.
References: