I'm using terraform to create an EC2 instance and an AWS Lambda function. I'd like the EC2 instance to be able to assign tags to all resources across the account using the resourcegroupstaggingapi
, e.g aws resourcegroupstaggingapi tag-resources
. When I run the following command from the AWS CLI via EC2 Instance Connect (after configuring the CLI of course), the command hangs. I suspect this might be an IAM issue. Does the following configuration provide the necessary permissions to achieve my goal?
provider "aws" {
version = "~> 2.0"
region = "us-east-1"
}
data "aws_availability_zones" "available" {
state = "available"
}
data "aws_ami" "amazon_linux_2" {
most_recent = true
filter {
name = "name"
values = ["amzn2-ami-hvm*"]
}
owners = ["amazon"]
}
resource "aws_iam_role" "ec2_role" {
name = "ec2_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy" "ec2_policy" {
name = "ec2_policy"
role = "${aws_iam_role.ec2_role.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"tag:GetResources",
"tag:TagResources",
"tag:UntagResources",
"tag:GetTagKeys",
"tag:GetTagValues"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Action": ["ec2:*"],
"Effect": "Allow",
"Resource": "*"
},
{
"Action": ["lambda:*"],
"Effect": "Allow",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_instance_profile" "ec2_profile" {
name = "ec2_profile"
role = "${aws_iam_role.ec2_role.name}"
}
resource "aws_security_group" "allow_ssh" {
name = "allow_ssh"
description = "Allow SSH inbound traffic"
ingress {
description = "TLS from VPC"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_iam_role" "my_lambda" {
name = "backend-service"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_lambda_function" "lambda" {
function_name = "lambda"
role = aws_iam_role.my_lambda.arn
runtime = "nodejs12.x"
filename = "index.js.zip"
handler = "index.handler"
}
resource "aws_instance" "web-ec2" {
ami = data.aws_ami.amazon_linux_2.id
instance_type = "t2.micro"
availability_zone = data.aws_availability_zones.available.names[0]
vpc_security_group_ids = ["${aws_security_group.allow_ssh.id}"]
iam_instance_profile = "${aws_iam_instance_profile.ec2_profile.name}"
}
Note that the IAM user I am using has the AdministratorAccess
policy applied to it.