How to use the @aws-cdk/aws-iam.ServicePrincipal function in @aws-cdk/aws-iam

To help you get started, we’ve selected a few @aws-cdk/aws-iam examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws-samples / aws-cdk-examples / typescript / appsync-graphql-dynamodb / index.ts View on Github external
tableName: tableName,
      partitionKey: {
        name: `${tableName}Id`,
        type: AttributeType.STRING
      },
      billingMode: BillingMode.PAY_PER_REQUEST,
      stream: StreamViewType.NEW_IMAGE,

      // The default removal policy is RETAIN, which means that cdk destroy will not attempt to delete
      // the new table, and it will remain in your account until manually deleted. By setting the policy to 
      // DESTROY, cdk destroy will delete the table (even if it has data in it)
      removalPolicy: cdk.RemovalPolicy.DESTROY, // NOT recommended for production code
    });

    const itemsTableRole = new Role(this, 'ItemsDynamoDBRole', {
      assumedBy: new ServicePrincipal('appsync.amazonaws.com')
    });

    itemsTableRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName('AmazonDynamoDBFullAccess'));

    const dataSource = new CfnDataSource(this, 'ItemsDataSource', {
      apiId: itemsGraphQLApi.attrApiId,
      name: 'ItemsDynamoDataSource',
      type: 'AMAZON_DYNAMODB',
      dynamoDbConfig: {
        tableName: itemsTable.tableName,
        awsRegion: this.region
      },
      serviceRoleArn: itemsTableRole.roleArn
    });

    const getOneResolver = new CfnResolver(this, 'GetOneQueryResolver', {
github aws / aws-cdk / packages / @aws-cdk / aws-s3-notifications / lib / sns.ts View on Github external
public bind(_scope: Construct, bucket: s3.IBucket): s3.BucketNotificationDestinationConfig {
    this.topic.addToResourcePolicy(new iam.PolicyStatement({
      principals: [new iam.ServicePrincipal('s3.amazonaws.com')],
      actions: ['sns:Publish'],
      resources: [this.topic.topicArn],
      conditions: {
        ArnLike: { "aws:SourceArn": bucket.bucketArn }
      }
    }));

    return {
      arn: this.topic.topicArn,
      type: s3.BucketNotificationDestinationType.TOPIC,
      dependencies: [ this.topic ] // make sure the topic policy resource is created before the notification config
    };
  }
}
github seagull-js / seagull / packages / deploy / src / cdk_stack.ts View on Github external
private addIAMRole() {
    const name = `${this.name}-Role`
    const principleName = 'lambda.amazonaws.com'
    const roleParams = { assumedBy: new iam.ServicePrincipal(principleName) }
    const actions: string[] = []
    actions.push('sts:AssumeRole')
    actions.push('logs:CreateLogStream')
    actions.push('logs:PutLogEvents')
    actions.push('lambda:InvokeFunction')
    actions.push('lambda:InvokeAsync')

    const role = new iam.Role(this, name, roleParams)
    const policyStatement = new iam.PolicyStatement()
    // TODO: add actions directly to the resources that need it
    role.addToPolicy(policyStatement.addAllResources().addActions(...actions))
  }
github seagull-js / seagull / packages / deploy-aws / src / seagull_stack.ts View on Github external
addIAMRole(roleName: string, principleName: string, actions: string[]) {
    const name = `${this.id}-${roleName}`
    const roleParams = { assumedBy: new IAM.ServicePrincipal(principleName) }
    const role = new IAM.Role(this, name, roleParams)
    const policyStatement = new IAM.PolicyStatement()
    // TODO: add actions directly to the resources that need it
    role.addToPolicy(policyStatement.addAllResources().addActions(...actions))
    return role
  }
github aws / aws-cdk / packages / @aws-cdk / aws-apigateway / lib / authorizers / lambda.ts View on Github external
authorizerResultTtlInSeconds: props.resultsCacheTtl && props.resultsCacheTtl.toSeconds(),
      identitySource: props.identitySource || 'method.request.header.Authorization',
      identityValidationExpression: props.validationRegex,
    });

    this.authorizerId = resource.ref;

    this.authorizerArn = Stack.of(this).formatArn({
      service: 'execute-api',
      resource: this.restApiId,
      resourceName: `authorizers/${this.authorizerId}`
    });

    if (!props.assumeRole) {
      props.handler.addPermission(`${this.node.uniqueId}:Permissions`, {
        principal: new iam.ServicePrincipal('apigateway.amazonaws.com'),
        sourceArn: this.authorizerArn
      });
    } else if (props.assumeRole instanceof iam.Role) { // i.e., not imported
      props.assumeRole.attachInlinePolicy(new iam.Policy(this, 'authorizerInvokePolicy', {
        statements: [
          new iam.PolicyStatement({
            resources: [ props.handler.functionArn ],
            actions: [ 'lambda:InvokeFunction' ],
          })
        ]
      }));
    }
  }
github aws / aws-cdk / packages / @aws-cdk / aws-s3-notifications / lib / lambda.ts View on Github external
public bind(_scope: Construct, bucket: s3.IBucket): s3.BucketNotificationDestinationConfig {
    const permissionId = `AllowBucketNotificationsFrom${bucket.node.uniqueId}`;

    if (this.fn.node.tryFindChild(permissionId) === undefined) {
      this.fn.addPermission(permissionId, {
        sourceAccount: Stack.of(bucket).account,
        principal: new iam.ServicePrincipal('s3.amazonaws.com'),
        sourceArn: bucket.bucketArn
      });
    }

    // if we have a permission resource for this relationship, add it as a dependency
    // to the bucket notifications resource, so it will be created first.
    const permission = this.fn.node.findChild(permissionId) as CfnResource;

    return {
      type: s3.BucketNotificationDestinationType.LAMBDA,
      arn: this.fn.functionArn,
      dependencies: permission ? [ permission ] : undefined
    };
  }
}
github aws / aws-cdk / packages / aws-cdk / integ-tests / app / app.js View on Github external
constructor(parent, id) {
    super(parent, id);

    new iam.Role(this, 'SomeRole', {
      assumedBy: new iam.ServicePrincipal('ec2.amazon.aws.com')
    });
  }
}
github aws / aws-cdk / packages / @aws-cdk / aws-cognito / lib / user-pool.ts View on Github external
private addLambdaPermission(fn: lambda.IFunction, name: string): void {
    const normalize = name.charAt(0).toUpperCase() + name.slice(1);
    fn.addPermission(`${normalize}Cognito`, {
      principal: new iam.ServicePrincipal('cognito-idp.amazonaws.com'),
      sourceArn: this.userPoolArn
    });
  }
}
github aws / aws-cdk / packages / @aws-cdk / aws-config / lib / managed-rules.ts View on Github external
constructor(scope: Construct, id: string, props: CloudFormationStackDriftDetectionCheckProps = {}) {
    super(scope, id, {
      ...props,
      identifier: 'CLOUDFORMATION_STACK_DRIFT_DETECTION_CHECK',
      inputParameters: {
        cloudformationRoleArn: Lazy.stringValue({ produce: () => this.role.roleArn })
      }
    });

    this.scopeToResource('AWS::CloudFormation::Stack', props.ownStackOnly ? Stack.of(this).stackId : undefined);

    this.role = props.role || new iam.Role(this, 'Role', {
      assumedBy: new iam.ServicePrincipal('config.amazonaws.com'),
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('ReadOnlyAccess')
      ]
    });
  }
}
github aws / aws-cdk / packages / @aws-cdk / aws-codedeploy / lib / lambda / deployment-group.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: LambdaDeploymentGroupProps) {
    super(scope, id, {
      physicalName: props.deploymentGroupName,
    });

    this.application = props.application || new LambdaApplication(this, 'Application');
    this.alarms = props.alarms || [];

    this.role = props.role || new iam.Role(this, 'ServiceRole', {
      assumedBy: new iam.ServicePrincipal('codedeploy.amazonaws.com')
    });

    this.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSCodeDeployRoleForLambda'));
    this.deploymentConfig = props.deploymentConfig || LambdaDeploymentConfig.CANARY_10PERCENT_5MINUTES;

    const resource = new CfnDeploymentGroup(this, 'Resource', {
      applicationName: this.application.applicationName,
      serviceRoleArn: this.role.roleArn,
      deploymentGroupName: this.physicalName,
      deploymentConfigName: this.deploymentConfig.deploymentConfigName,
      deploymentStyle: {
        deploymentType: 'BLUE_GREEN',
        deploymentOption: 'WITH_TRAFFIC_CONTROL'
      },
      alarmConfiguration: cdk.Lazy.anyValue({ produce: () => renderAlarmConfiguration(this.alarms, props.ignorePollAlarmsFailure) }),
      autoRollbackConfiguration: cdk.Lazy.anyValue({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),