aws-cdk-lib#aws_iam TypeScript Examples
The following examples show how to use
aws-cdk-lib#aws_iam.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From cdk-ec2-key-pair with Apache License 2.0 | 6 votes |
private grantRead(arn: string, grantee: aws_iam.IGrantable) {
const result = aws_iam.Grant.addToPrincipal({
grantee,
actions: [
'secretsmanager:DescribeSecret',
'secretsmanager:GetResourcePolicy',
'secretsmanager:GetSecretValue',
'secretsmanager:ListSecretVersionIds',
],
resourceArns: [arn],
scope: this,
});
return result;
}
Example #2
Source File: index.ts From cdk-ec2-key-pair with Apache License 2.0 | 5 votes |
/**
* Grants read access to the private key in AWS Secrets Manager
*/
grantReadOnPrivateKey(grantee: aws_iam.IGrantable) {
return this.grantRead(this.privateKeyArn, grantee);
}
Example #3
Source File: index.ts From cdk-ec2-key-pair with Apache License 2.0 | 5 votes |
/**
* Grants read access to the public key in AWS Secrets Manager
*/
grantReadOnPublicKey(grantee: aws_iam.IGrantable) {
return this.grantRead(this.publicKeyArn, grantee);
}
Example #4
Source File: index.ts From cdk-ssm-document with Apache License 2.0 | 5 votes |
private ensureLambda(): aws_lambda.Function {
const stack = Stack.of(this);
const constructName = 'SSM-Document-Manager-Lambda';
const existing = stack.node.tryFindChild(constructName);
if (existing) {
return existing as aws_lambda.Function;
}
const policy = new aws_iam.ManagedPolicy(
stack,
'SSM-Document-Manager-Policy',
{
managedPolicyName: `${stack.stackName}-${cleanID}`,
description: `Used by Lambda ${cleanID}, which is a custom CFN resource, managing SSM documents`,
statements: [
new aws_iam.PolicyStatement({
actions: ['ssm:ListDocuments', 'ssm:ListTagsForResource'],
resources: ['*'],
}),
new aws_iam.PolicyStatement({
actions: ['ssm:AddTagsToResource', 'ssm:CreateDocument'],
resources: ['*'],
conditions: {
StringLike: {
'aws:RequestTag/CreatedByCfnCustomResource': ID,
},
},
}),
new aws_iam.PolicyStatement({
actions: [
'ssm:AddTagsToResource',
'ssm:DeleteDocument',
'ssm:DescribeDocument',
'ssm:GetDocument',
'ssm:ListDocumentVersions',
'ssm:ModifyDocumentPermission',
'ssm:RemoveTagsFromResource',
'ssm:UpdateDocument',
'ssm:UpdateDocumentDefaultVersion',
],
resources: ['*'],
conditions: {
StringLike: {
'ssm:ResourceTag/CreatedByCfnCustomResource': ID,
},
},
}),
],
}
);
const role = new aws_iam.Role(stack, 'SSM-Document-Manager-Role', {
roleName: `${stack.stackName}-${cleanID}`,
description: `Used by Lambda ${cleanID}, which is a custom CFN resource, managing SSM documents`,
assumedBy: new aws_iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
policy,
aws_iam.ManagedPolicy.fromAwsManagedPolicyName(
'service-role/AWSLambdaBasicExecutionRole'
),
],
});
const fn = new aws_lambda.Function(stack, constructName, {
functionName: `${stack.stackName}-${cleanID}`,
role: role,
description: 'Custom CFN resource: Manage SSM Documents',
runtime: aws_lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: aws_lambda.Code.fromAsset(
path.join(__dirname, '../lambda/code.zip')
),
timeout: Duration.minutes(lambdaTimeout),
});
return fn;
}
Example #5
Source File: index.ts From cdk-ec2-key-pair with Apache License 2.0 | 4 votes |
private ensureLambda(): aws_lambda.Function {
const stack = Stack.of(this);
const constructName = 'EC2-Key-Name-Manager-Lambda';
const existing = stack.node.tryFindChild(constructName);
if (existing) {
return existing as aws_lambda.Function;
}
const resources = [`arn:${stack.partition}:ec2:*:*:key-pair/*`];
const policy = new aws_iam.ManagedPolicy(
stack,
'EC2-Key-Pair-Manager-Policy',
{
managedPolicyName: `${this.prefix}-${cleanID}`,
description: `Used by Lambda ${cleanID}, which is a custom CFN resource, managing EC2 Key Pairs`,
statements: [
new aws_iam.PolicyStatement({
actions: ['ec2:DescribeKeyPairs'],
resources: ['*'],
}),
new aws_iam.PolicyStatement({
actions: [
'ec2:CreateKeyPair',
'ec2:CreateTags',
'ec2:ImportKeyPair',
],
conditions: {
StringLike: {
'aws:RequestTag/CreatedByCfnCustomResource': ID,
},
},
resources,
}),
new aws_iam.PolicyStatement({
// allow delete/update, only if createdByTag is set
actions: ['ec2:CreateTags', 'ec2:DeleteKeyPair', 'ec2:DeleteTags'],
conditions: {
StringLike: {
'ec2:ResourceTag/CreatedByCfnCustomResource': ID,
},
},
resources,
}),
new aws_iam.PolicyStatement({
// we need this to check if a secret exists before attempting to delete it
actions: ['secretsmanager:ListSecrets'],
resources: ['*'],
}),
new aws_iam.PolicyStatement({
actions: [
'secretsmanager:CreateSecret',
'secretsmanager:TagResource',
],
conditions: {
StringLike: {
'aws:RequestTag/CreatedByCfnCustomResource': ID,
},
},
resources: ['*'],
}),
new aws_iam.PolicyStatement({
// allow delete/update, only if createdByTag is set
actions: [
'secretsmanager:DeleteResourcePolicy',
'secretsmanager:DeleteSecret',
'secretsmanager:DescribeSecret',
'secretsmanager:GetResourcePolicy',
'secretsmanager:GetSecretValue',
'secretsmanager:ListSecretVersionIds',
'secretsmanager:PutResourcePolicy',
'secretsmanager:PutSecretValue',
'secretsmanager:RestoreSecret',
'secretsmanager:UntagResource',
'secretsmanager:UpdateSecret',
'secretsmanager:UpdateSecretVersionStage',
],
conditions: {
StringLike: {
'secretsmanager:ResourceTag/CreatedByCfnCustomResource': ID,
},
},
resources: ['*'],
}),
],
}
);
const role = new aws_iam.Role(stack, 'EC2-Key-Pair-Manager-Role', {
roleName: `${this.prefix}-${cleanID}`,
description: `Used by Lambda ${cleanID}, which is a custom CFN resource, managing EC2 Key Pairs`,
assumedBy: new aws_iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
policy,
aws_iam.ManagedPolicy.fromAwsManagedPolicyName(
'service-role/AWSLambdaBasicExecutionRole'
),
],
});
const fn = new aws_lambda.Function(stack, constructName, {
functionName: `${this.prefix}-${cleanID}`,
role: role,
description: 'Custom CFN resource: Manage EC2 Key Pairs',
runtime: aws_lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: aws_lambda.Code.fromAsset(
path.join(__dirname, '../lambda/code.zip')
),
timeout: Duration.minutes(lambdaTimeout),
});
return fn;
}
Example #6
Source File: test-stack.ts From cdk-ssm-document with Apache License 2.0 | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
let file = path.join(
__dirname,
'../documents/command/hello-world-yaml.yml'
);
const docA = new Document(this, 'SSM-Document-HelloWorld-Yaml', {
name: `${this.stackName}-HelloWorld-from-yaml-file`,
content: fs.readFileSync(file).toString(),
});
file = path.join(__dirname, '../documents/command/hello-world-json.json');
const docB = new Document(this, 'SSM-Document-HelloWorld-Json', {
name: `${this.stackName}-HelloWorld-from-json-file`,
content: fs.readFileSync(file).toString(),
});
file = path.join(
__dirname,
'../documents/automation/automation-document.yml'
);
const docC = new Document(this, `SSM-Document-Automation`, {
documentType: 'Automation',
name: 'Test-Automation',
content: fs.readFileSync(file).toString(),
});
const docD = new Document(this, 'SSM-Document-HelloWorld-Inline', {
name: `${this.stackName}-HelloWorld-from-inline`,
content: {
schemaVersion: '2.2',
description: 'Echo Hello World!',
parameters: {
text: {
default: 'Hello World!',
description: 'Text to echo',
type: 'String',
},
},
mainSteps: [
{
name: 'echo',
action: 'aws:runShellScript',
inputs: {
runCommand: ['echo "{{text}}"'],
},
precondition: {
StringEquals: ['platformType', 'Linux'],
},
},
],
},
});
/**
* Distributor example.
*
* Requires a bucket to hold install/update/uninstall scripts.
*/
const bucketName = `${Stack.of(this).account}-cdk-ssm-document-storage`;
const bucket = new aws_s3.Bucket(this, 'DistributorPackages', {
bucketName: bucketName,
blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
encryption: aws_s3.BucketEncryption.KMS_MANAGED,
// Makes for easy destroy and rerun of this stack over and over.
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
const packageDeploy = new aws_s3_deployment.BucketDeployment(
this,
'distribution-packages',
{
sources: [
aws_s3_deployment.Source.asset('../test/documents/distributor'),
],
destinationBucket: bucket,
}
);
let attachments: { [key: string]: any } = {};
// flip this condition to test an attachment update
if (true) {
file = path.join(__dirname, '../documents/distributor/v1/manifest.json');
attachments = {
versionName: '1.0-Custom-Name',
attachments: [{ key: 'SourceUrl', values: [`s3://${bucketName}/v1`] }],
};
} else {
file = path.join(__dirname, '../documents/distributor/v2/manifest.json');
attachments = {
versionName: '2.0-Better-Than_Sliced_Bread',
attachments: [{ key: 'SourceUrl', values: [`s3://${bucketName}/v2`] }],
};
}
const docE = new Document(this, `SSM-Distribution-Package`, {
documentType: 'Package',
name: 'Test-Distribution-Package',
content: fs.readFileSync(file).toString(),
...attachments,
});
/**
* The owner/creator of the document must have read access to the
* s3 files that make up a distribution. Since that is the lambda in this
* case we must give it `GetObject` permissions before they will can become
* `Active`.
*/
docE.lambda.role?.addToPrincipalPolicy(
new aws_iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [`${bucket.arnForObjects('*')}`],
})
);
docE.node.addDependency(docD);
docE.node.addDependency(packageDeploy);
docD.node.addDependency(docC);
docC.node.addDependency(docB);
docB.node.addDependency(docA);
const dir = path.join(__dirname, '../documents/command');
const files = fs.readdirSync(dir);
var last: Document | undefined = undefined;
for (const i in files) {
const name = files[i];
const shortName = name.split('.').slice(0, -1).join('.'); // removes file extension
const file = `${dir}/${name}`;
const doc = new Document(this, `SSM-Document-Loop-${shortName}`, {
name: `${this.stackName}-${shortName}`,
content: fs.readFileSync(file).toString(),
});
if (typeof last !== 'undefined') {
last.node.addDependency(doc);
}
last = doc;
}
}