AWS AppConfig Validation Lambda Policy in SAM Template - amazon-web-services

I’m trying to add a policy to a lambda to allow AppConfig to invoke it.
I can do this through the terminal using this command:
aws lambda add-permission --function-name ConfigValidator.Arn --action lambda:InvokeFunction --statement-id appconfig --principal appconfig.amazonaws.com --output json --region eu-west-1
But how can this be done automatically through the SAM template?

Here is how I do this:
Create a managed policy with access to your AppConfig
Attach that managed policy to the role your lambda is configured to use
Here is the code using CDK (CDK is the latest and greatest tool to create AWS resources, I highly recommend using it!).
If you don't want to use CDK you can manually setup the same managed policies by hand.
Detailed example below:
Create a managed policy with access to your AppConfig
const resourceArn = `arn:aws:appconfig:${props.region}:${props.accountId}:application/${this.appConfigApplication.ref}*`
this.appConfigReaderManagedPolicy = new ManagedPolicy(this, `AppConfigReader-${id}`, {
managedPolicyName: `AppConfigReader-${id}`,
description: `Readonly access to ${id}`,
statements: [
new PolicyStatement({
resources: [resourceArn],
actions: [
'appconfig:GetConfiguration',
'appconfig:GetApplication',
]
})
]
})
Attach that managed policy to the role your lambda is configured to use
//assuming your lambda is already configured somewhere
this.lambdaFunction.role.addManagedPolicy(this.appConfigReaderManagedPolicy)

Related

User is not authorized to perform lambda function

I am following the aws tutorial on how to create thumbnails using lambda. I run this command to create a function:
aws lambda create-function --function-name CreateThumbnailDev --zip-file fileb://lambda-dev.zip --handler index.handler --runtime nodejs12.x --timeout 10 --memory-size 1024 --role arn:aws:iam::XXXXXXXXXXXXX:role/<MY_ROLE>
MY_ROLE is a role a created for executing lambda. The above command returns this error:
An error occurred (AccessDeniedException) when calling the CreateFunction operation: User: arn:aws:iam::XXXXXXXXXXXXX:user/MY_USER is not authorized to perform: lambda:CreateFunction .....
the problem is that XXXXXXXXXXXXX is my account id (as the tutorial says to use if) but user/MY_USER is the user I configured my AWS CLI locally, it exists but it doesn't have the necessary policy attached.
How should I configure the client to execute this command?
Here we have two different principals:
Role associated to the lambda function: permissions that the lambda function itself will have
Policies associated to your IAM user: what you can do
Looks like your IAM user named MY_USER, the one you're using for creating the lambda, is missing permissions for that. You'll need to grant them, either attaching a policy directly to the user or adding the user to a group that has the policies
You can check the official documentation for that

Add multiple user or role on AWS Lambda policy

I'm trying to invoke an AWS Lambda from one account on another account, I have the private link created for both and tried configuring a role and adding it to the was lambda polices it works as expected, but I want to limit to the individual user to invoke the function. So is it possible to add multiple users instead of root or role ARN?
The CLI command will add the root as below:
$ aws lambda add-permission --function-name my-function:prod --statement-id xaccount --action lambda:InvokeFunction \
--principal 210987654321 --output text
{"Sid":"xaccount","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function"}
From Using resource-based policies for AWS Lambda:
To limit access to a user, group, or role in another account, specify the full ARN of the identity as the principal. For example: arn:aws:iam::123456789012:user/developer

How to configure Alexa Skills Kit trigger for a lambda function via CloudFormation?

I am developing an Alexa skill and would like to use CloudFormation to deploy infrastructure for my skill.
So far IAM role, policy and lambda function deployment work fine. What I'm missing is a trigger from Alexa Skill Kit for my lambda function.
At the moment I have to manually create this trigger in the AWS console:
Or via CLI:
aws lambda add-permission --function-name DeutscheDeklinationLambdaFunction --statement-id 1 --action lambda:invokeFunction --principal alexa-appkit.amazon.com --region eu-west-1
But I'd prefer to configure this trigger via CloudFormation. I think it should be https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html, but I could not find how to implement this for Alexa Skills Kit.
A classic, three minutes after posting a question I've found an answer on my own.
It appears that "trigger" in this case is actually a lambda permission for the function to be invoked by Alexa Skills Kit. So it can be configured as follows:
DeutscheDeklinationLambdaFunctionPermission:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !GetAtt DeutscheDeklinationLambdaFunction.Arn
Principal: alexa-appkit.amazon.com
EventSourceToken: !Ref AppId
FunctionsName is ARN of the function, EventSourceToken is the id of the skill.
Here is an example of how to do it in typescript for AWS CDK (cloud development kit).
import { ServicePrincipal } from '#aws-cdk/aws-iam';
...
MyLambda.addPermission('alexa-skills-kit-trigger', {
principal: new ServicePrincipal('alexa-appkit.amazon.com'),
action: 'lambda:invokeFunction',
});
Documentation:
#aws-cdk/aws-iam
#aws-cdk_aws-lambda.Permission

Permission error when using Boto3, but works via aws cli

I'm stuck on a missing permissions issue trying to create a Lambda function.
The execution role I've configured has the following permissions:
$ aws --output=text iam get-role-policy --policy-name=MyRolePolicy --role-name=my-role
<snip>
POLICYDOCUMENT 2012-10-17
STATEMENT Allow
ACTION s3:Get*
ACTION s3:List*
ACTION logs:CreateLogGroup
ACTION logs:CreateLogStream
ACTION logs:PutLogEvents
ACTION ec2:DescribeNetworkInterfaces
ACTION ec2:CreateNetworkInterface
ACTION ec2:DeleteNetworkInterface
And when I create a Lambda function with that role, creation succeeds:
$ aws lambda create-function \
--function-name=my-test --runtime=java8 \
--role='arn:aws:iam::1234567890:role/my-role' \
--handler=MyHandler \
--code=S3Bucket=my-bucket,S3Key=app.zip
<result successful>
However, when I create the function using the same arguments (esp. the same execution role) I get the following error:
Boto3 Usage
client.create_function(
FunctionName=function_name,
Runtime='java8',
Role=getenv('execution_role_arn'),
Handler='MyHandler',
Code={
"S3Bucket": bucket,
"S3Key": artifact_name
},
Publish=True,
VpcConfig={
'SubnetIds': getenv('vpc_subnet_ids').split(','),
'SecurityGroupIds': getenv('vpc_security_group_ids').split(',')
}
)
Boto3 Result
{
'Error':{
'Message':'The provided execution role does not have permissions to call CreateNetworkInterface on EC2',
'Code':'InvalidParameterValueException'
},
'ResponseMetadata':{
'RequestId':'47b6640a-f3fe-4550-8ac3-38cfb2842461',
'HTTPStatusCode':400,
'HTTPHeaders':{
'date':'Wed, 24 Jul 2019 10:55:44 GMT',
'content-type':'application/json',
'content-length':'119',
'connection':'keep-alive',
'x-amzn-requestid':'47b6640a-f3fe-4550-8ac3-38cfb2842461',
'x-amzn-errortype':'InvalidParameterValueException'
},
'RetryAttempts':0
}
}
Creating a function via the console with this execution role works as well, so I must be missing something in how I'm using Boto3, but I'm at a loss to explain.
Hopefully someone can catch a misapplication of Boto3 here, cause I'm at a loss!
Your boto3 code is specifying a VPC:
VpcConfig={
'SubnetIds': getenv('vpc_subnet_ids').split(','),
'SecurityGroupIds': getenv('vpc_security_group_ids').split(',')
However, the CLI version is not specifying a VPC.
Therefore, the two requests are not identical. That's why one works and the other does not work.
From Configuring a Lambda Function to Access Resources in an Amazon VPC - AWS Lambda:
To connect to a VPC, your function's execution role must have the following permissions.
ec2:CreateNetworkInterface
ec2:DescribeNetworkInterfaces
ec2:DeleteNetworkInterface
These permissions are included in the AWSLambdaVPCAccessExecutionRole managed policy.
The lambda has a role that allows ec2:CreateNetworkInterface and not the account executing script.
The current role assigned to lambda function allows for the lambda to create VpcConfig.
Check that the account running the script to provision the lambda is allowed the ec2:CreateNetworkInterface action.

How to attach policy to a role while creating an AWS lambda function in nodejs in AWS CLI? Facing error while attaching role

I am creating a nodejs application and deploying it as a lambda function on AWS. I am following the link:
http://docs.aws.amazon.com/lambda/latest/dg/with-on-demand-https-example-create-iam-role.html
I am now stuck at step 2.2-2.3. Step 2.2 has the json with the policy that needs to be attached to the role. When I use the below command (step 2.3) to create the lambda function:
ws lambda create-function --region us-east-1 --function-name LambdaFunctionOverHttps --zip-file fileb://LambdaFunctionOverHttps.zip --role execution-role-arn --handler LambdaFunctionOverHttps.handler --runtime nodejs4.3
Then I get the below error:-
An error occurred (ValidationException) when calling the
CreateFunction operation: 1 validation error detected: Value
'execution-role-arn' at 'role' failed to satisfy constraint: Member
must satisfy regular expression pattern:
arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.#-_/]+
I even created the file "execution-role-arn" which had the json from Step 2.2. How can I resolve this error and create the lambda function?
I faced the same error, turns out you have to specify the Role ARN, not the Role name. So instead of --role roleName , put --role arn:aws:iam::1234567891:role/service-role/roleName . You can find you role ARN by clicking on the role name in Roles tab, and then at the top you'll find the role ARN.
AWS really needs to fix their documentation for almost all of their services.
Update: The role needs to be replaced with the actual arn role name for the lambda function instead of a separate file. This can be found on the role you just created in step 2.2. So, the proper way to do this is as follows:
aws lambda create-function
--region us-east-1
--function-name LambdaFunctionOverHttps
--zip-file fileb://LambdaFunctionOverHttps.zip
--role arn:aws:iam::9999999999999:role/lambda-gateway-execution-role
--handler LambdaFunctionOverHttps.handler
--runtime nodejs4.3
This worked out fine and the lambda function got created. Note that I had pointed the default profile to admin with the aws config command.