AWS MediaConvert Python AccessDeniedException: when calling the CreateJob operation - amazon-web-services

I am trying to create a simple MediaConnect job with Python.
My pipeline is simple. S3Put triggers a Python lambda, and I am trying to create a simple job.
I created a simple job using AWS Console and the json job is this -
{
"Queue": "arn:aws:mediaconvert:ap-south-1:----:queues/Default",
"UserMetadata": {},
"Role": "arn:aws:iam::----:role/mediaConverterRole",
"Settings": {
"TimecodeConfig": {
"Source": "ZEROBASED"
},
"OutputGroups": [
{
"Name": "File Group",
"Outputs": [
{
"Preset": "System-Generic_Hd_Mp4_Av1_Aac_16x9_640x360p_24Hz_250Kbps_Qvbr_Vq6",
"Extension": ".mp4",
"NameModifier": "converted"
}
],
"OutputGroupSettings": {
"Type": "FILE_GROUP_SETTINGS",
"FileGroupSettings": {
"Destination": "s3://----/"
}
}
}
],
"Inputs": [
{
"AudioSelectors": {
"Audio Selector 1": {
"DefaultSelection": "DEFAULT"
}
},
"VideoSelector": {},
"TimecodeSource": "ZEROBASED",
"FileInput": "s3://----/videos/sample786.mp4"
}
]
},
"AccelerationSettings": {
"Mode": "DISABLED"
},
"StatusUpdateInterval": "SECONDS_60",
"Priority": 0
}
Please note that the Role worked fine while using on AWS console. So far this is ok.
Now coming to my pipeline with s3Put -> Python Lambda -> MediaConnect, the infrastructure is written using Terraform. My iam.tf file -
# create a role
# reseource_type - resource_name
resource "aws_iam_role" "lambda_role" {
name = "${local.resource_component}-lambda-role"
assume_role_policy = jsonencode({
"Version": "2012-10-17",
"Statement": [{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
},
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "mediaconvert.amazonaws.com"
},
"Sid": "",
"Effect": "Allow",
}
]
})
}
# create policy
resource "aws_iam_policy" "policy" {
name = "${local.resource_component}-lambda-policy"
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::*"
}
]
})
}
# attach policy to the role
resource "aws_iam_role_policy_attachment" "policy_attachment" {
role = "${aws_iam_role.lambda_role.name}"
policy_arn = "${aws_iam_policy.policy.arn}"
}
The lambda code gets triggered by S3Put successfully. But the lambda throws error -
(AccessDeniedException) when calling the CreateJob operation: User: arn:aws:sts::---:assumed-role/vidstream-inputVideoProcessor-lambda-role/vidstream-inputVideoProcessor is not authorized to perform: iam:PassRole on resource: arn:aws:iam::---:role/mediaConverterRole
I have tried to find boto3 simple examples but nothing simpler is found online.
The lambda Python Code is here -
import json
import logging
import boto3
# initialize logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
# get input bucket
input_bucket_name = event['Records'][0]['s3']['bucket']['name']
# get file/object name
media_object = event['Records'][0]['s3']['object']['key']
# open json mediaconvert template
with open("job.json", "r") as jsonfile:
job_object = json.load(jsonfile)
# prepare data for mediaconvert job
input_file = f's3://{input_bucket_name}/{media_object}'
# edit job object
job_object['Settings']['Inputs'][0]['FileInput'] = input_file
# updated job object
logger.info("updated job object")
# Create MediaConvert client
mediaconvert_client = boto3.client('mediaconvert')
try:
# try to create a job
mediaconvert_client.create_job(**job_object)
except Exception as e:
logger.error(e)
return {
'statusCode': 200,
'body': json.dumps(event)
}
The boto3 MediaConvert documentation is provided by AWS
I am at a loss, no idea what to do. Is there any simpler example anyone can help me with?
I just need to create a simple job with Lambda that works, no complexity.
Any kind of help will be highly appreciated.

Okay I solved this issue by putting iam:PassRole to lambda policy.
{
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": "*"
}
So the updated iam.tf file is -
# create a role
# reseource_type - resource_name
resource "aws_iam_role" "lambda_role" {
name = "${local.resource_component}-lambda-role"
assume_role_policy = jsonencode({
"Version": "2012-10-17",
"Statement": [{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
},
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "mediaconvert.amazonaws.com"
},
"Sid": "",
"Effect": "Allow",
}
]
})
}
# create policy
resource "aws_iam_policy" "policy" {
name = "${local.resource_component}-lambda-policy"
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::*"
},
{
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": "*"
}
]
})
}
# attach policy to the role
resource "aws_iam_role_policy_attachment" "policy_attachment" {
role = "${aws_iam_role.lambda_role.name}"
policy_arn = "${aws_iam_policy.policy.arn}"
}
I first added this to lambda policy from aws console. After that worked I added this on my tf file. Be careful when editing something on console while the main infrastructure is written in IACs such as Terraform, this might cause drift if you forget what you have done.

Related

Terraform AWS CMK script throws a Not Authorized Error

I am trying to create a CMK for my SQS queue to allow encrypted SNS messages to be sent to my encrypted queue. After I create the cmk, I will set it to the "kms_master_key_id" in my queue.
resource "aws_kms_key" "mycmk" {
description = "KMS Key"
deletion_window_in_days = 10
policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": [
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": "*"
}]
}
POLICY
}
This is throwing an error:
my_role_arn is not authorized to perform: kms:CreateKey on resource: *
I've double checked to make sure that action is allowed and it is.
Do I need to update the 'resource' in the policy? If so to what?
The role I am using to run this has these permissions:
Effect = "Allow"
Action = [
"kms:CreateAlias",
"kms:CreateGrant",
"kms:CreateKey",
"kms:DeleteAlias",
"kms:DisableKey",
"kms:EnableKey",
"kms:PutKeyPolicy",
"kms:RevokeGrant",
"kms:ScheduleKeyDeletion",
"kms:TagResource",
"kms:UntagResource",
"kms:UpdateAlias",
"kms:UpdateKeyDescription"
]
Resource = [
"arn:aws:kms:${local.aws_region}:${var.aws_account_id}:key/*",
"arn:aws:kms:${local.aws_region}:${var.aws_account_id}:alias/*"
]
As someone else suggested, it looks like the credentials you use to run Terraform don't have the right permissions.
CreateKey explicitly only works with the "*" resource, so change the policy to this:
data "aws_iam_policy_document" "key_Access" {
statement {
actions = [
"kms:CreateAlias",
"kms:CreateGrant",
"kms:DeleteAlias",
"kms:DisableKey",
"kms:EnableKey",
"kms:PutKeyPolicy",
"kms:RevokeGrant",
"kms:ScheduleKeyDeletion",
"kms:TagResource",
"kms:UntagResource",
"kms:UpdateAlias",
"kms:UpdateKeyDescription"
]
resources = [
"arn:aws:kms:${local.aws_region}:${var.aws_account_id}:key/*",
"arn:aws:kms:${local.aws_region}:${var.aws_account_id}:alias/*"
]
}
statement {
actions = ["kms:CreateKey"]
resources = ["*"]
}
}
With that being said, maybe don't make your own policy. Just assign the existing policy arn:aws:iam::aws:policy/AWSKeyManagementServicePowerUser to the role. That gives the following permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:CreateAlias",
"kms:CreateKey",
"kms:DeleteAlias",
"kms:Describe*",
"kms:GenerateRandom",
"kms:Get*",
"kms:List*",
"kms:TagResource",
"kms:UntagResource",
"iam:ListGroups",
"iam:ListRoles",
"iam:ListUsers"
],
"Resource": "*"
}
]
}

IAM policy for EBS volume with EC2 instance

I am trying to create an IAM role/policy to enable my EC2 instance to be able to list and attach EBS volumes (via scripts that call the aws cli). I want this policy to allow only listing/attaching of EBS volumes that have a specific tag.
I've noticed that the script is able to list/attach volumes when I set Resources: "*" and no Conditions in my policy below.
But as soon as I introduce the policy I have below, the AWS cli throws the following error:
./aws ec2 describe-volumes
An error occurred (UnauthorizedOperation) when calling the DescribeVolumes operation: You are not authorized to perform this operation.
Here is the IAM policy I have so far defined in terraform:
resource "aws_iam_role" "web_role" {
name = "web_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_instance_profile" "web_profile" {
name = "web_profile"
role = aws_iam_role.web_role.name
}
resource "aws_iam_role_policy" "web_disk_policy" {
name = "web_disk_policy"
role = aws_iam_role.web_role.id
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:AttachVolume",
"ec2:DetachVolume",
"ec2:DescribeVolumes"
],
"Resource": [
"arn:aws:ec2:*:*:instance/*",
"arn:aws:ec2:*:*:volume/*"
],
"Condition": {
"StringEquals": {
"ec2:ResourceTag/app": "web"
}
}
}
]
}
EOF
}
And my EC2 instances is created with the following:
resource "aws_instance" "web_vm" {
...
iam_instance_profile = aws_iam_instance_profile.web_profile.name
...
tags = {
app = "web"
}
}
And disk created with:
resource "aws_ebs_volume" "ebs-volume-1" {
availability_zone = "us-west-2a"
size = 10
tags = {
app = "web"
}
}
DescribeVolumes does not support aws:ResourceTag/${TagKey} condition, nor any other.
Most Describe/List type operations that target many resources aren't compatible with the conditional logic. DescribeVolumes does not work with conditions so split that off into a different statement.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:AttachVolume",
"ec2:DetachVolume"
],
"Resource": [
"arn:aws:ec2:*:*:instance/*",
"arn:aws:ec2:*:*:volume/*"
],
"Condition": {
"StringEquals": {
"ec2:ResourceTag/app": "web"
}
}
},
{
"Effect": "Allow",
"Action": "ec2:DescribeVolumes",
"Resource": "*"
}
]
}

AWS lambda cloudwatch subscription

I want to add a cloudwatch subscription to a AWS lambda logs thereby making my AWS lambda triggered by cloudwatch logs. What permissions should I add to the role which lambda is using to enable this?
Your Lambda will by default have access to CloudWatch to write logs (with the default AWSLambdaBasicExecutionRole), however if you want to manually add it this is the policy with the required permissions:
{
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
},
"name": "AWSLambdaBasicExecutionRole",
"id": "xxxxx",
"type": "managed",
"arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
Lambda function policy for CloudWatch event trigger on Lambda:
{
"Version": "2012-10-17",
"Id": "default",
"Statement": [
{
"Sid": "uuid",
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "lambda:invokeFunction",
"Resource": "arn:aws:lambda:us-east-x:xxxxxxxxxxxx:function:LambdaFunction",
"Condition": {
"ArnLike": {
"AWS:SourceArn": "arn:aws:events:us-east-x:xxxxxxxxxxxx:rule/CloudWatchRule"
}
}
}
]
}

How to create roles in terraform

I would like to create a aws_iam_role with terraform but after running terraform applyI get the following error message:
aws_iam_role.role: Error Updating IAM Role (edb_eb_role) Assume Role Policy: MalformedPolicyDocument: Has prohibited field Resource
That is my policy:
resource "aws_iam_role" "role" {
name = "edb_eb_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
},
{
"Action": [
"logs:*"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"*"
]
}
]
}
EOF
}
What did I wrong? I also tried to do it only with Principals but then I get the message that "Principals" is also not prohibited?
Assume_role_policy don't accept the aws policy json files. So the above code is not working. For detailed explanation of assume_role_policy in aws_iam_role, see this thread.
Update the code as shown below and execute.
variable policy_arn{
default = "arn:aws:iam::aws:policy/service-role/AWSLambdaRole"
}
resource "aws_iam_role" "edb_role" {
name = "edb_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_attachment" "test-attach" {
role = "${aws_iam_role.edb_role.name}"
policy_arn = "${var.policy_arn}"
}
output "role" {
value = "${aws_iam_role.edb_role.name}"
}
Here, we are using the AWSLambdaRole Policy present in Policies section of IAM.
Add multiple policies to a role using aws_iam_role_policy_attach
Use the default policies provided by aws as show above. Else to create a new policy, see the docs here

Security token service exception while restoring snapshot from S3 to AWS managed elasticsearch

I have an AWS managed Elasticsearch Service (say smallES) which has an properly working S3 bucket attached to containing day wise rolling indices of last 1 year. I've created another AWS managed ES cluster (say bigES) for some business reason. I want to restore last 1 year's data from bucket into bigES. It's guaranteed that smallES bigES and bucket all are in the same region and same VPC.
So, I created a policy :
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:ListBucketMultipartUploads",
"s3:ListBucketVersions"
],
"Resource": [
"arn:aws:s3:::bucket"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::bucket/*"
]
}
]
}
And attached the policy with a role. Trust relationship of that role is
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "s3.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Now, when I create a snapshot by http request within the same VPC, it can create a snapshot-repo for the bigES and I can query for that too
curl -XGET 'http://bigESid.region.es.amazonaws.com:80/_snapshot'
Output
{
"snapshot-repo": {
"type": "s3",
"settings": {
"bucket": "bucket",
"region": "region",
"role_arn": "role_arn"
}
}
}
But when I try to see the snapshots in this snapshot repo I get error (described below)
curl -XGET 'http://bigESid.region.es.amazonaws.com:80/_cat/snapshots/snapshot-repo'
I get the following error:
{
"error": {
"root_cause": [
{
"type": "a_w_s_security_token_service_exception",
"reason": "User: arn:aws:sts::acountid:assumed-role/cp-sts-grant-role/swift-region-prod-365021432299 is not authorized to perform: sts:AssumeRole on resource: role-arn (Service: AWSSecurityTokenService; Status Code: 403; Error Code: AccessDenied; Request ID: some-id)"
}
],
"type": "a_w_s_security_token_service_exception",
"reason": "User: arn:aws:sts::acountid:assumed-role/cp-sts-grant-role/swift-region-prod-365021432299 is not authorized to perform: sts:AssumeRole on resource: role-arn (Service: AWSSecurityTokenService; Status Code: 403; Error Code: AccessDenied; Request ID: some-id)"
},
"status": 500
}
I've given all access of s3 to my role, but no luck. I've posted all the http requests from a ec2 machine inside the VPC.
Also to mention, if I query like following, I see expected result
curl -XGET 'http://smallESid.region.es.amazonaws.com:80/_cat/snapshots/snapshot-repo'
IDK why I tried making a role which has trust relationship like following. Still no luck.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Thanks in advance for any kind of help/suggestions.
I had the same issue, and it was because I'd not allowed the Elasticsearch service to assume the role. I had to update my trust relationship policy document to include es.amazonaws.com.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"es.amazonaws.com",
"ec2.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
I solved this problem using the following policy
{
"Statement": [
{
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:ListBucketMultipartUploads",
"s3:ListBucketVersions"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucket-name"
]
},
{
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts",
"iam:PassRole"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucket-name/*"
]
}
],
"Version": "2012-10-17"
}
Then I attached the policy to the role. I think "iam:PassRole"has done the work.