ECR + Organization

0

How can users create lambda functions in their respective accounts using the ECR image repository in management account. These users are under a particular organization.

3 Answers
2

Hello Keerthi,

Grant ECR access to user accounts in your organization, not Lambda creation. Users can then create Lambdas referencing the shared ECR image. This ensures central control over deployments.

Allow Cross-Account Access to ECR:

  • Create an ECR repository in the management account.
  • Update the ECR repository policy to allow read access to all organization accounts.

Create IAM Roles in User Accounts:

  • Create an IAM role in each user account with permissions to create Lambda functions and pull images from the ECR repository.
  • Ensure the role can be assumed by a trusted role from the management account.

Deploy Lambda Functions:

  • Use AWS CloudFormation StackSets or a script (like a Python script using Boto3) to deploy Lambda functions in each user account.
  • The deployment script should assume the role in each user account and create the Lambda function using the ECR image URI.

This process ensures the ECR repository in the management account can be used to create Lambda functions across all user accounts in the organization.

profile picture
EXPERT
answered 9 days ago
1

Hi keerthi,

Please go through below steps try it once i hope it will helps you to solve your query.

Step 1: Prepare the ECR Repository in the Management Account

Create ECR Repository:

aws ecr create-repository --repository-name my-repo

Push Docker Image to ECR:

# Authenticate Docker to the Amazon ECR registry
aws ecr get-login-password --region region | docker login --username AWS --password-stdin account-id.dkr.ecr.region.amazonaws.com

# Build your Docker image
docker build -t my-image .

# Tag the Docker image
docker tag my-image:latest account-id.dkr.ecr.region.amazonaws.com/my-repo:latest

# Push the Docker image to ECR
docker push account-id.dkr.ecr.region.amazonaws.com/my-repo:latest

Set Up Repository Permissions:

Create a policy that allows other accounts to pull the image and attach it to the repository:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPull",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:PrincipalOrgID": "o-exampleorgid"
                }
            }
        }
    ]
}

Apply the policy:

aws ecr set-repository-policy --repository-name my-repo --policy-text file://repository-policy.json

Step 2: Set Up Cross-Account Access

Create IAM Role in Each Member Account:

Create a role with a trust policy that allows the management account to assume the role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::management-account-id:root"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

Attach Policy to the Role:

Attach a policy to the role that grants permissions to manage Lambda functions and pull images from the ECR repository:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:UpdateFunctionCode",
                "lambda:UpdateFunctionConfiguration",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "ecr:BatchCheckLayerAvailability"
            ],
            "Resource": "*"
        }
    ]
}

Step 3: Automate the Deployment Process

Use CloudFormation StackSets:

  • Create a StackSet with a template to create the IAM role and Lambda function.
  • Deploy the StackSet across all accounts in the organization.

Use AWS SDK or CLI to Automate Deployment:

  • Use a script to list all accounts in the organization.
  • Assume the role in each account and create/update the Lambda function.

Here is an example script using the AWS CLI and Boto3:

import boto3

management_account_id = 'management-account-id'
organization_id = 'o-exampleorgid'
ecr_repository = 'account-id.dkr.ecr.region.amazonaws.com/my-repo:latest'
lambda_role_name = 'LambdaExecutionRole'
lambda_function_name = 'MyLambdaFunction'

org_client = boto3.client('organizations')
sts_client = boto3.client('sts')

# Get list of all accounts in the organization
accounts = org_client.list_accounts()['Accounts']

for account in accounts:
    account_id = account['Id']
    role_arn = f'arn:aws:iam::{account_id}:role/{lambda_role_name}'
    
    # Assume role in each member account
    assumed_role = sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName='DeployLambdaSession'
    )
    
    credentials = assumed_role['Credentials']
    
    lambda_client = boto3.client(
        'lambda',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken']
    )
    
    # Create or update Lambda function
    try:
        lambda_client.create_function(
            FunctionName=lambda_function_name,
            Role=role_arn,
            Code={
                'ImageUri': ecr_repository
            },
            PackageType='Image',
            Timeout=300,
            MemorySize=128
        )
    except lambda_client.exceptions.ResourceConflictException:
        lambda_client.update_function_code(
            FunctionName=lambda_function_name,
            ImageUri=ecr_repository
        )
        lambda_client.update_function_configuration(
            FunctionName=lambda_function_name,
            Role=role_arn,
            Timeout=300,
            MemorySize=128
        )

EXPERT
answered 9 days ago
  • Will this mean the management account has complete access to create lambda function whenever they need in user accounts.

    I actually wanted in a way that only user has access to their account and no one else have access to the resources in their account.

  • Hi keerthi,

    Please try this below steps.

    Apply SCPs at the organizational level to restrict the management account’s access to user accounts. Ensure SCPs do not grant permissions but rather limit the maximum permissions that can be applied in the accounts.

0

Hi,

The solution you are looking for is quite similar to this blog - Sharing Amazon ECR repositories with multiple accounts using AWS Organizations and also this post. Instead of pulling the ECR image to an ECS task/service, you will use Lambda -> Container Image.

Hope this helps!

Thanks, Rama

profile pictureAWS
Rama
answered 9 days ago
  • An error occurred (AccessDeniedException) when calling the CreateFunction operation: Lambda does not have permission to access the ECR image. Check the ECR permissions.

    Although I added the policy for ECR I am still getting this issue. Is there something I need to add in development accounts?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions