AWSTemplateFormatVersion: 2010-09-09
Description: Create an IAM role that Clazar will use to access your AWS marketplace.

Parameters:
  ClazarAccountId:
    Description: Clazar AWS Account ID which will assume the IAM role
    Type: String
  SandboxRoleName:
    Type: String
  ProductionRoleName:
    Type: String
  ClazarExternalId:
    Description: Assume Role External Id
    Type: String

Mappings:
  Role:
    APNRolePolicyAccessPolicyName:
      Value: APNRolesPolicyAccess

Resources:
  SandboxRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref SandboxRoleName
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub arn:aws:iam::${ClazarAccountId}:root
            Action:
              - sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ClazarExternalId

  ProductionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref ProductionRoleName
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub arn:aws:iam::${ClazarAccountId}:root
            Action:
              - sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ClazarExternalId

  RoleAccessPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: !FindInMap [Role, APNRolePolicyAccessPolicyName, Value]
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - 'iam:GetRole'
              - 'iam:ListRolePolicies'
              - 'iam:GetRolePolicy'
              - 'iam:PassRole'
            Resource:
              - !GetAtt SandboxRole.Arn
              - !GetAtt ProductionRole.Arn
      Roles:
        - !Ref SandboxRoleName
        - !Ref ProductionRoleName

Outputs:
  SandboxRoleArn:
    Value: !GetAtt SandboxRole.Arn
  ProductionRoleArn:
    Value: !GetAtt ProductionRole.Arn
