Проблема с облачной информацией и Codestar-Connections - PullRequest
0 голосов
/ 07 мая 2020

Мне был создан шаблон облачной информации, когда я использую те же услуги AWS, например: aws -lambda-function, s3, codebuild, codepipeline и т. Д. c. Мой контроль версий исходного кода - BitBucket, и я использую соединения codestar между AWS и BB. Когда я запустил свой файл облачной информации, AWS отправил мне следующую ошибку:

User: arn:aws:iam::XXXXXXXXXXXXX:user/XXXXXX.XXXXXXX@XXXXXXXXX.com is not authorized to perform: codestar-connections:PassConnection on resource: BitbucketAWSParser (Service: AWSCodePipeline; Status Code: 400; Error Code: AccessDeniedException; Request ID: e0bc17f4-11de-41d0-9724-e2a05b16b0ae)

Я попытался предоставить себе эти разрешения, но AWS IAM ответил мне, что соединения codestar не поддерживаются на консоли IAM . Я пробовал много способов исправить это, но не смог.

Я приложил свой облачный файл, чтобы помочь.


AWSTemplateFormatVersion: "2010-09-09"

Description:
  o presente template visa criar um único modelo de criação de funcoes lambda para a Intuitivecare.

Parameters:

  CodeStarConnection:
    Type: String 



  RepoName:
    Type: String 



  Version:
    Type: String 
    Default: 1
    AllowedPattern: "[V0-9]"

  PathImageCodeBuild: 
    Type: String



  LambdaRegion:
    Type: String
    Default: us-east-1


  LambdaRunTime:
    Type: String
    Default: python3.6


  LambdaFunctionSubNetA:
    Type: String



  LambdaFunctionSubNetB:
    Type: String



  LambdaSecurityGroup:
    Type: String



#Obs: todos os demais nomes de objetvos serão combinacoes dos campos acima descritos.


Resources:
#Substituido iamRole por Service Role / 

  #unico recurso que não criado referenciando a nome da funcao lambda
  # AWS CodeStar Connection
  ConnectionBitbucket:
    Type: 'AWS::CodeStarConnections::Connection'
    Properties:
      ConnectionName: !Ref CodeStarConnection
      ProviderType: "Bitbucket"

  # S3 bucket where build artifacts go
  DeploymentArtifactBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Delete
    Properties:
      AccessControl: Private
      VersioningConfiguration:
      # The guide recommends Enabled but I can't see why
        Status: Enabled

  DeployS3Bucket:
    Type: AWS::S3::Bucket
    Properties: 
      AccessControl: Private 
      BucketName: !Join ["-",["pipeline",!Ref RepoName]]
      VersioningConfiguration:
        Status: Enabled
      Tags:
        -
          Key: Appication
          Value: !Ref RepoName

  logLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      RetentionInDays: 7
      LogGroupName: 
        !Sub 
          - "Log-${RepoName}"
          - RepoName: !Ref RepoName


  CodeBuildServiceRole:
    #
    #Returns a set of temporary security credentials that you can use to access AWS resources that you might not normally have access to. These temporary credential
    #consist of an access key ID, a secret access key, and a security token. Typically, you use AssumeRole within your account or for cross-account access. For a 
    #comparison of AssumeRole with other API operations that produce temporary credentials
    #Link: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html
    #
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codebuild.amazonaws.com


  CodeBuildServicePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: CodeBuildServicePolicy
      Roles:
        - !Ref CodeBuildServiceRole
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - logs:CreateLogGroup
              - logs:CreateLogStream
              - logs:PutLogEvents
            Resource: "arn:aws:logs:*:*:*"
          - Effect: Allow
            Action:
              - s3:GetObject
              - s3:GetObjectVersion
              - s3:PutObject
              - s3:GetBucketAcl
              - s3:GetBucketLocation
            Resource:
              - !Sub "arn:aws:s3:::codepipeline-${AWS::Region}-*/*"
              - !Sub "arn:aws:s3:::${DeploymentArtifactBucket}/*"
          - Effect: Allow
            Action:
              - codebuild:CreateReportGroup
              - codebuild:CreateReport
              - codebuild:UpdateReport
              - codebuild:BatchPutTestCases
            Resource:
              - !Sub "arn:aws:codebuild:us-east-1:XXXXXXXXXXXXX:report-group/${RepoName}-${Version}-bitbucket-*"
          #acesso as repositórios armazenados na AWS 
          # !!!!! Importante mantermos uma rotina de versionamento do CloudFormation
          -   Effect: Allow
              Action:
              - ecr:GetAuthorizationToken
              Resource: '*'
          -   Effect: Allow
              Action:
              - ecr:BatchCheckLayerAvailability
              - ecr:GetDownloadUrlForLayer
              - ecr:BatchGetImage
              - ecr:PutImage
              - ecr:InitiateLayerUpload
              - ecr:UploadLayerPart
              - ecr:CompleteLayerUpload
              Resource: arn:aws:ecr:us-east-1:XXXXXXXXXXXXX:repository/bitbucket
          -   Effect: Allow #Alterei
              Action:
              - codestar-connections:UseConnection           
              Resource: !Ref ConnectionBitbucket 


  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Join ["-",[!Ref RepoName,"-codebuild"]]
      ServiceRole: !GetAtt CodeBuildServiceRole.Arn
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        Type: LINUX_CONTAINER
        # ComputeType options: BUILD_GENERAL1_SMALL, BUILD_GENERAL1_MEDIUM, BUILD_GENERAL1_LARGE
        ComputeType: BUILD_GENERAL1_SMALL
        # Run `aws codebuild list-curated-environment-images` for a complete list of images provided.
        # Como no nosso caso não usamos uma imagem padrao da AWS, temos que descrever que imagem sera usada
        # De forma a melhorar a manutencao deste Cloudformation, o formato sera gravado com uma parametro.
        Image: !Ref PathImageCodeBuild
        EnvironmentVariables:
          - Name: BUILD_ARTIFACT_BUCKET
            Value: !Ref DeploymentArtifactBucket
      Source:
        Auth:
          Type: OAUTH 
        Type: CODEPIPELINE
        Location: !Sub "https://bitbucket.org/intuitivecare/${RepoName}"
        BuildSpec: buildspec-bitbucket-parser.yml
      LogsConfig:
        CloudWatchLogs:
          Status: ENABLED
          GroupName: !Ref logLogGroup
          StreamName: !Ref Version

  CodePipelineServiceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - codepipeline.amazonaws.com



  CodePipelineServicePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: !Join ["-",[!Ref RepoName,"PipelineServicePolicy"]]
      Roles:
        - !Ref CodePipelineServiceRole
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - logs:CreateLogGroup
              - logs:CreateLogStream
              - logs:PutLogEvents
            Resource: "arn:aws:logs:*:*:*"
          - Effect: Allow
            Action:
              - s3:GetObject
              - s3:GetObjectVersion
              - s3:PutObject
            Resource: !Sub "arn:aws:s3:::${DeployS3Bucket}/*"
          - Effect: Allow
            Action:
              - cloudformation:CreateStack,
              - cloudformation:DeleteStack,
              - cloudformation:DescribeStacks,
              - cloudformation:UpdateStack,
              - cloudformation:CreateChangeSet,
              - cloudformation:DeleteChangeSet,
              - cloudformation:DescribeChangeSet,
              - cloudformation:ExecuteChangeSet,
              - cloudformation:SetStackPolicy,
              - cloudformation:ValidateTemplate,
            Resource: !Join ["-",[!Sub "arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/", RepoName, Version,"/*"]]
            #!Sub "arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${RepoName}/*"
          - Effect: Allow
            Action:
              - codebuild:BatchGetBuilds
              - codebuild:StartBuild
              - codebuild:StopBuild
            Resource: !GetAtt CodeBuildProject.Arn
          - Effect: Allow
            Action:
                - codestar-connections:UseConnection           
            Resource: "*"  # !Ref ConnectionBitbucket       #Alterei
          - Effect: Allow
            Action:
              - iam:PassRole
            Resource: [
                 "*" # !GetAtt CloudFormationServiceRole.Arn
                ]

  CloudFormationServiceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - cloudformation.amazonaws.com

  CloudFormationServicePolicy:
    # This policy deloys the project's SAM template and needs permissions to create all services defined there.
    # A number of common blocks are provided as examples.
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: CloudFormationServicePolicy
      Roles:
        - !Ref CloudFormationServiceRole
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - logs:CreateLogGroup
              - logs:CreateLogStream
              - logs:PutLogEvents
            Resource: "arn:aws:logs:*:*:*"
          - Effect: Allow
            Action:
              - cloudformation:CreateChangeSet
              - cloudformation:ListChangeSets
            Resource: !Sub "arn:aws:cloudformation:${AWS::Region}:aws:transform/*"
          - Effect: Allow
            Action:
              - s3:GetObject
            Resource:
              - !Sub "arn:aws:s3:::codepipeline-${AWS::Region}-*/*"
              - !Sub "arn:aws:s3:::${DeploymentArtifactBucket}/*"
          - Effect: Allow
            Action:
              - iam:AttachRolePolicy
              - iam:CreateRole
              - iam:DeleteRole
              - iam:DeleteRolePolicy
              - iam:DetachRolePolicy
              - iam:GetRole
              - iam:PassRole
              - iam:PutRolePolicy
              - codestar-connections:UseConnection
            Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/${RepoName}-*"
          - Effect: Allow
            Action:
              - lambda:AddPermission
              - lambda:CreateFunction
              - lambda:DeleteFunction
              - lambda:GetFunction
              - lambda:GetFunctionConfiguration
              - lambda:InvokeFunction
              - lambda:RemovePermission
              - lambda:TagResource
              - lambda:UntagResource
              - lambda:UpdateFunctionCode
              - lambda:UpdateFunctionConfiguration
            Resource: !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:Lambda-${RepoName}-${Version}-*"
          # This block is necessary for any event mapping
          - Effect: Allow
            Action:
              - lambda:CreateEventSourceMapping
              - lambda:DeleteEventSourceMapping
              - lambda:GetEventSourceMapping
            Resource: "*"
          # Lambda tagging
          - Effect: Allow
            Action:
              - lambda:ListTags
              - lambda:TagResource
              - lambda:UntagResource
            Resource: "*"
          # CloudWatch event triggers
          - Effect: Allow
            Action:
              - events:DeleteRule
              - events:DescribeRule
              - events:DisableRule
              - events:EnableRule
              - events:PutRule
              - events:PutTargets
              - events:RemoveTargets
            Resource: !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/Log-${RepoName}-*"
          # S3
          - Effect: Allow
            Action:
              - s3:CreateBucket
              - s3:GetBucketAcl
              - s3:GetBucketNotification
              - s3:GetBucketTagging
              - s3:PutBucketAcl
              - s3:PutBucketNotification
              - s3:PutBucketTagging
            Resource: "*"
          - Effect: Allow #Alterei
            Action: 
              - codestar-connections:UseConnection
            Resource: "*"

  CodePipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Name: !Join ["-",["Pipeline",!Ref RepoName, !Ref Version]]
      RoleArn: !GetAtt CodePipelineServiceRole.Arn
      ArtifactStore: 
        Type: S3
        Location: !Ref DeploymentArtifactBucket
      Stages: 
        - Name: Source
          Actions:
            - Name: Source
              ActionTypeId:
                Category: Source
                Owner: AWS
                Provider: CodeStarSourceConnection
                Version: "1"
              InputArtifacts: []
              OutputArtifacts: 
                - Name: SourceArtifact
              Configuration: {
                    ConnectionArn: !Ref CodeStarConnection,
                    FullRepositoryId: !Sub "intuitivecare/${RepoName}",
                    BranchName: master,
                    OutputArtifactFormat: CODE_ZIP
                  }
              RunOrder: 1          
        - Name: Build
          Actions:
            - Name: Build  
              ActionTypeId: 
                Category: Build
                Owner: AWS
                Provider: CodeBuild
                Version: "1"
            # caso seja necessário a inclusão de variáveis locais, teremos que implementar as varíaveis no campo parameters
            # incluir as chamadas no JSON de Configuration visitar página: https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CodeBuild.html
            # para verifcar a forma. 
              Configuration: {
                   ProjectName: !Ref CodeBuildProject             
                  }
              InputArtifacts: 
                - Name: SourceArtifact
              OutputArtifacts: 
                - Name: BuildArtifact
              RunOrder: 2
        - Name: Deploy
          Actions:
            - Name: Deploy
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Provider: CodeDeploy
                Version: "1"
            #VER PADRÃO DE CONFIGURACAO EM: https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html#reference-action-artifacts
              Configuration:
                { 
                  "BucketName": {"Fn::Join" : ["-", ["Bucket", "Ref" : "RepoName"]]},
                  "Extract": "true",
                  "ObjectKey": { "Fn::Sub": "Artifact-${RepoName}-${Version}" }
                }
              InputArtifacts:
                - Name: BuildArtifact
              RunOrder: 3

  lambdaFunctionExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - lambda.amazonaws.com

  lambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Description: !Sub "LambdaFunction-${RepoName}"
      FunctionName: !Sub "Lambda-${RepoName}-${Version}"
      Handler: lambda_handler
      MemorySize: 3008
      Role: !GetAtt lambdaFunctionExecutionRole.Arn
      Runtime: !Ref LambdaRunTime
      Timeout: 900
      VpcConfig:
        SecurityGroupIds:
          - !Ref LambdaSecurityGroup
        SubnetIds:
          - !Ref LambdaFunctionSubNetA
          - !Ref LambdaFunctionSubNetB
      Code:
        S3Bucket: !Ref DeployS3Bucket
        S3Key: { "Fn::Sub": "Artifact-${RepoName}-${Version}" }
        # S3ObjectVersion: 
        # ZipFile: 
      Tags:
        - Key: keyname
          Value: value

  lambdaVersion:
    Type: AWS::Lambda::Version
    Properties:
      Description: !Sub "Lambda Version para ${RepoName}-${Version}"
      FunctionName: !Ref lambdaFunction
      # CodeSha256: acho interessante obtermos esse dados e futuramente inclui-lo. 


  lambdaAlias:
    Type: AWS::Lambda::Alias
    Properties:
      Description: !Sub "Alias para a função lambda ${RepoName}-${Version}"
      FunctionName: !Ref lambdaFunction #The version of the Lambda function that you want to associate with this alias.
      FunctionVersion: !Ref lambdaVersion
      Name: !Sub "Alias-${RepoName}-${Version}" #A name for the alias





  logsMetricFilter:
    Type: AWS::Logs::MetricFilter
    Properties:
      FilterPattern: "[...,state = SUCCEEDED]"
      # "UPLOAD_ARTIFACTS State: SUCCEEDED"

      LogGroupName: !Ref logLogGroup
      MetricTransformations:
        - 
          MetricValue: "1"
          MetricNamespace: !Ref RepoName
          MetricName: !Sub 
            - "Deploy-Completo-${RepoName}-${Version}"
            - RepoName: !Ref RepoName
              Version: !Ref Version

  snsTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription: 
      -
        Endpoint: !GetAtt lambdaFunction.Arn
        Protocol: lambda
      TopicName: !Sub "Deploy-${RepoName}-${Version}"


  snsSubscription:
    Type: AWS::SNS::Subscription
    Properties:
      TopicArn: !Ref snsTopic
      Protocol: lambda
      Endpoint: !GetAtt lambdaFunction.Arn
      Region: !Ref LambdaRegion

  cloudWatchAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      MetricName: !Sub 
            - "Deploy-Completo-${RepoName}-${Version}"
            - RepoName: !Ref RepoName
              Version: !Ref Version
      Namespace: !Ref RepoName
      ComparisonOperator: GreaterThanThreshold
      EvaluationPeriods: 1
      Period: 1
      Statistic: SampleCount
      Threshold: 0.5
      ActionsEnabled: true
      AlarmActions: [!Ref snsTopic]
      AlarmName: !Sub "Deplpy-${RepoName}-${Version}"

С уважением, Маркос Лопес.

...