First of all I have been searching stackflow and the internet for this but I didn't find exactly where the issue is.
Basically I am trying to add custom cidr ips to a security group via lambda function. I have given all the appropriate permissions (as far as i can tell) [REMOVED]and also tried attaching the vpc (which is non-default) to the lambda function to access the security group[REMOVED].
But I am getting "An error occurred (VPCIdNotSpecified) when calling the AuthorizeSecurityGroupIngress operation: No default VPC for this user"
Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:RevokeSecurityGroupIngress",
"ec2:CreateNetworkInterface",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeVpcs",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSubnets",
"ec2:DescribeSecurityGroups"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"wafv2:GetIPSet",
"logs:CreateLogGroup",
"wafv2:UpdateIPSet"
],
"Resource": [
"arn:aws:logs:us-west-2:xxxx:log-group:xxx:log-stream:*",
"arn:aws:wafv2:us-west-2:xxx:*/ipset/*/*"
]
}
]
}
Lambda function:
#!/usr/bin/python3.9
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
response = ec2.authorize_security_group_ingress(
GroupId='sg-xxxxxxx'
IpPermissions=[
{
'FromPort': 443,
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': '1x.1x.x.1x/32',
'Description': 'adding test cidr using lambda'
},
],
'ToPort': 443
}
],
DryRun=True
)
return response
Could someone point me to the right direction? VPC is non-default. All I need is the add ingress rule to existing security group within non-default vpc
Thanks
Found the solution: Initially it was syntax error but after googling i thought it requires vpc so I added VPC to the Lambda configuration which was not required for this purpose.
For anyone having the same issue (only want to update security group with the cidr): below is the correct function and permissions (function isnt complete as depending on the solution u may want to delete old rules too):
Lambda function:
#!/usr/bin/python3.9
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
response = ec2.authorize_security_group_ingress(
DryRun=False,
GroupId='sg-0123456789',
IpPermissions=[
{
'FromPort': 443,
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': '1x.2x.3x.4x/32',
'Description': 'Security group updated via lambda'
}
],
'ToPort': 443
}
]
)
return response
IAM Policy on lambda execution role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:AuthorizeSecurityGroupIngress",
"ec2:ModifySecurityGroupRules",
"ec2:UpdateSecurityGroupRuleDescriptionsIngress"
],
"Resource": "arn or all"
}
]
}
Related
I've be trying to implement a new policy on AWS to allow a specific user to manage a specific Security Group.
I used to have this working but it stopped working a couple weeks ago and now no matter what I try I cannot get it to work again.
Does anyone have a valid JSON config on how to create a policy to allow users to modify a SPECIFIC security role? This is mainly to allow certain users to change the firewall rules when they are on dynamic IPs.
EDIT:
This is my current JSON config:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "s1",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances",
"ec2:DescribeNetworkAcls",
"ec2:DescribeSecurityGroups"
],
"Resource": [
"*"
]
},
{
"Sid": "s2",
"Effect": "Allow",
"Action": [
"ec2:AuthorizeSecurityGroupEgress",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:RevokeSecurityGroupEgress",
"ec2:RevokeSecurityGroupIngress"
],
"Resource": [
"arn:aws:ec2:*:*:security-group/sg-<my id>"
]
}
]
}
The policy you mentioned looks correct. But it will not allow you to modify the existing egress/ingress security rule. If you want to modify a security group rule, you can delete the existing security group rule and add a new security group rule.
To allow modifications on an existing security group rule add this permission as well ec2:ModifySecurityGroupRules.
Modified policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeSecurityGroupRules",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeNetworkAcls",
"ec2:DescribeSecurityGroups",
"ec2:DescribeInstanceStatus"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:RevokeSecurityGroupIngress",
"ec2:AuthorizeSecurityGroupEgress",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:UpdateSecurityGroupRuleDescriptionsEgress",
"ec2:RevokeSecurityGroupEgress",
"ec2:UpdateSecurityGroupRuleDescriptionsIngress",
"ec2:ModifySecurityGroupRules"
],
"Resource": [
"arn:aws:ec2:*:*:security-group/<sg-id>",
"arn:aws:ec2:*:*:security-group-rule/*"
]
}
]
}
Note: This policy allows you to edit a security group and any security group rules under that security group. You can also limit access using security group rule as well by mentioning security group rule id (arn:aws:ec2:::security-group-rule/$sgr-id) for the corresponding security group id.
When I try to query AWS Keyspaces (managed Cassandra) from an AWS Lambda, I get this error:
{
"errorType": "AggregateException",
"errorMessage": "One or more errors occurred. (All hosts tried for query failed (tried 11.11.111.11:9142: UnauthorizedException 'User arn:aws:iam::111111111111:user/user-for-keyspaces has no permissions.'; 11.11.111.11:9142: UnauthorizedException 'User arn:aws:iam::111111111111:user/user-for-keyspaces has no permissions.'))",
"stackTrace": [
"at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
],
"cause": {
"errorType": "NoHostAvailableException",
...
But in the AWS console for Keyspaces, I don't see anywhere to adder permissions.
The user policy for user-for-keyspaces already has this attached:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"cassandra:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
How do I add permissions in AWS Keyspaces?
You should only require cassandra
{
"Statement": [
{
"Sid": "keyspaces-full-access",
"Principal": "*",
"Action": [
"cassandra:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Additionally, Amazon Keyspaces populates the system.peers table in your account with an entry for each availability zone where a VPC endpoint is available. To look up and store available interface VPC endpoints in the system.peers table, Amazon Keyspaces requires that you grant the IAM entity used to connect to Amazon Keyspaces access permissions to query your VPC for the endpoint and network interface information.
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"ListVPCEndpoints",
"Effect":"Allow",
"Action":[
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeVpcEndpoints"
],
"Resource":"*"
}
]
}
Learn more about VPC endpoints here
The problem was actually nothing to do with the user in the error message, but the VPC endpoint I had created for Keyspaces.
The endpoint requires cassandra:* permissions to perform queries, e.g.
{
"Statement": [
{
"Sid": "keyspaces-full-access",
"Principal": "*",
"Action": [
"cassandra:*",
"keyspaces:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
We have a terraform script to create a lambda function in aws. This lambda function uses a custom bucket from S3.
The script below runs perfectly when I put "Resource": "*".
We need to specify a custom resource that aws lambda function can access on S3.
Our aws_iam_policy is configured this way:
resource "aws_iam_policy" "lambda_policy" {
name = "lambda-s3-policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*",
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
],
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
}
]
}
EOF
}
When the script runs, this error appears:
Error: Error applying plan:
1 error(s) occurred:
* aws_lambda_function.func_loader: 1 error(s) occurred:
* aws_lambda_function.func_loader: Error creating Lambda function: InvalidParameterValueException: The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.
{
RespMetadata: {
StatusCode: 400,
RequestID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
Message_: "The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.",
Type: "User"
}
Terraform does not automatically rollback in the face of errors.
I already checked the permissions, the subnet ip range limits, but it is all good to go.
These permissions:
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
Can't be restricted to this resource:
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
What you have done is given your Lambda function permission to call those EC2 actions, as long as it is calling those actions on an S3 bucket, which obviously makes no sense. You probably need to split the IAM policy into multiple statements, like so:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*",
],
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
},
{
"Effect": "Allow",
"Action": [
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs"
],
"Resource": "*"
}
]
}
I have this python 3.7 code that runs as well from my local computer. This is the code for my lambda function. However, when I test it in AWS, it does not add the inbound rule to the security group. I would like help in getting it to work. Again, when I run it from my local computer, it works.
import boto3
ec2 = boto3.client('ec2')
def modify_sg_add_rules(event, context):
response = ec2.authorize_security_group_ingress(
GroupName='boto3-sg',
IpPermissions=[
{
'FromPort': 1521,
'IpProtocol': 'tcp',
'IpRanges': [
{
'CidrIp': '12.345.67.890/32',
'Description': 'My home IP',
},
],
'ToPort': 1521,
},
],
DryRun=False
) #closes response
return response
#if __name__ == '__main__':
# modify_sg_add_rules()
These are the permission in the policy that is attached to a role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeSecurityGroups",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:RevokeSecurityGroupIngress"
],
"Resource": "*"
}
]
}
Please, help me!
Thank you!
--Willie
Based on the comments.
The issue was caused by using wrong name for lambda function handler. Instead of modify_sg_add_rules it should be lambda_handler which is default name for the handler.
Thus, the solution was to rename modify_sg_add_rules into lambda_handler. The alternative is to change the default handler's name into modify_sg_add_rules.
I have problems with execution command on Windows machine from Lambda function using ssm.send_command in Python. This Lambda functions should execute simple command on windows machine:
import boto3
ssm = boto3.client('ssm')
region = 'us-east-1'
instances = ['i-XXXXXXXXXXXXX']
def lambda_handler(event, context):
response = ssm.send_command(
InstanceIds=instances,
DocumentName='AWS-RunPowerShellScript',
DocumentVersion='$DEFAULT',
DocumentHash='2142e42a19e0955cc09e43600bf2e633df1917b69d2be9693737dfd62e0fdf61',
DocumentHashType='Sha256',
TimeoutSeconds=123,
Comment='string',
Parameters={
'commands': [
# 'query user'
'mkdir test-dir'
]
},
MaxErrors='1',
CloudWatchOutputConfig={
'CloudWatchLogGroupName': 'WindowsLogs',
'CloudWatchOutputEnabled': True
}
)
print response
Execution role for this L-functions is
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:SendCommand"
],
"Resource": [
"arn:aws:ssm:*:*:document/*"
]
},
{
"Effect": "Allow",
"Action": [
"ssm:SendCommand"
],
"Resource": [
"arn:aws:ec2:*:*:instance/*",
"arn:aws:ec2:*:*:*"
]
},
{
"Action": [
"iam:PassRole"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Also I added policies:
AmazonEC2FullAccess
AmazonEC2RoleforSSM
AmazonSSMManagedInstanceCore
CloudWatchLogsFullAccess
AmazonSSMFullAccess
AmazonSSMAutomationRole
AmazonSSMMaintenanceWindowRole
For EC2 no roles were assigned
Problem: I don't see that folder "test-dir' was created on Windows server. Please can you help me to determine what is missing, or how can I configure Lambda function for executing command and send results to CloudWatch.
Thank you.
You need to assign the AmazonSSMFullAccess policy to the instance, otherwise it won't work.
Make sure to restart the instance after the change.
If that doesn't work:
Add try and except blocks to your code to check what's the error.
Check that you have the SSMAgent installed on your instance (connect to it, open PowerShell and execute Restart-Service AmazonSSMAgent).
Thank you #fsinis90 for your recommendations.
I tried them and also I added such policies to my instance's role:
AWSHealthFullAccess
AmazonEC2RoleforSSM
AWSConfigUserAccess
AmazonSSMFullAccess
CloudWatchReadOnlyAccess
And it helps.