Last active
October 22, 2017 12:59
-
-
Save jenseickmeyer/d6f67be0ae12e2bc762b104231c5dd60 to your computer and use it in GitHub Desktop.
Lambda function which assumes two roles of two different AWS accounts before listing S3 buckets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require('aws-sdk'); | |
exports.handler = (event, context, callback) => { | |
assumeRole('123456789012', 'RoleName', null, (error, credentials) => { | |
if(error) { | |
console.log('Failed to assume role: ' + error); | |
callback(error); | |
} else { | |
assumeRole('098765432109', 'OrganizationAccountAccessRole', credentials, (error, credentials) => { | |
if(error) { | |
callback(error); | |
return; | |
} | |
listS3Buckets(credentials, (error, buckets) => { | |
if(error) { | |
console.log('Failed to list S3 buckets: ' + error); | |
callback(error); | |
return; | |
} | |
buckets.forEach((bucket) => { | |
console.log(bucket.Name); | |
}); | |
callback(); | |
}); | |
}); | |
} | |
}); | |
}; | |
function assumeRole(accountId, roleName, credentials, callback) { | |
const params = { | |
RoleArn: `arn:aws:iam::${accountId}:role/${roleName}`, | |
RoleSessionName: 'CreateStackSession' | |
}; | |
var options = {}; | |
if(credentials) { | |
options = { | |
accessKeyId: credentials.AccessKeyId, | |
secretAccessKey: credentials.SecretAccessKey, | |
sessionToken: credentials.SessionToken | |
}; | |
} | |
const sts = new AWS.STS(options); | |
sts.assumeRole(params, (error, data) => { | |
if(error) { | |
callback(error); | |
} else { | |
callback(null, data.Credentials); | |
} | |
}); | |
} | |
function listS3Buckets(credentials, callback) { | |
var options = { | |
accessKeyId: credentials.AccessKeyId, | |
secretAccessKey: credentials.SecretAccessKey, | |
sessionToken: credentials.SessionToken | |
}; | |
const s3 = new AWS.S3(options); | |
s3.listBuckets({}, (error, data) => { | |
if(error) { | |
callback(error); | |
} else { | |
callback(null, data.Buckets); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment