role.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package aws
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/aws/aws-sdk-go-v2/aws"
  7. "github.com/aws/aws-sdk-go-v2/service/iam"
  8. )
  9. const (
  10. DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE = "dify-plugin-lambda-execution-role"
  11. )
  12. // getOrCreateLambdaExecutionRole creates a new lambda execution role if it doesn't exist
  13. // or returns the existing role's ARN
  14. func getOrCreateLambdaExecutionRole(ctx context.Context) (string, error) {
  15. iam_client := iam.NewFromConfig(*aws_lambda_config)
  16. // Check if the role already exists
  17. _, err := iam_client.GetRole(ctx, &iam.GetRoleInput{
  18. RoleName: aws.String(DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE),
  19. })
  20. if err == nil {
  21. // Role already exists, return its ARN
  22. return fmt.Sprintf("arn:aws:iam::%s:role/%s", lambda_account_id, DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE), nil
  23. }
  24. // Create the role if it doesn't exist
  25. assume_role_policy_document := `{
  26. "Version": "2012-10-17",
  27. "Statement": [
  28. {
  29. "Effect": "Allow",
  30. "Principal": {
  31. "Service": "lambda.amazonaws.com"
  32. },
  33. "Action": "sts:AssumeRole"
  34. }
  35. ]
  36. }`
  37. create_role_output, err := iam_client.CreateRole(ctx, &iam.CreateRoleInput{
  38. RoleName: aws.String(DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE),
  39. AssumeRolePolicyDocument: aws.String(assume_role_policy_document),
  40. })
  41. if err != nil {
  42. return "", err
  43. }
  44. // Attach the AWSLambdaBasicExecutionRole policy
  45. _, err = iam_client.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
  46. RoleName: aws.String(DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE),
  47. PolicyArn: aws.String("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"),
  48. })
  49. if err != nil {
  50. // Delete the role if the policy attachment fails
  51. _, err1 := iam_client.DeleteRole(ctx, &iam.DeleteRoleInput{
  52. RoleName: aws.String(DIFY_PLUGIN_LAMBDA_EXECUTION_ROLE),
  53. })
  54. if err1 != nil {
  55. return "", errors.Join(err, err1)
  56. }
  57. return "", err
  58. }
  59. return *create_role_output.Role.Arn, nil
  60. }