Giter Club home page Giter Club logo

cdk-assume-role-credential-plugin's Introduction

THIS PROJECT IS NO LONGER MAINTAINED

CDK Assume Role Credential Plugin

Now that CDK V2 is GA I no longer recommend using this plugin. This plugin was originally created to fill a feature gap in the CDK where you could not assume roles into a separate AWS account. This feature was added to the CDK CLI when using the context flag @aws-cdk/core:newStyleStackSythesis which as of V2 has been made the default value.

Now by default when you bootstrap an AWS account it will create a set of IAM roles for you, which the CDK will assume when performing actions in that account.

cdk-assume-role-credential-plugin's People

Contributors

amazon-auto avatar corymhall avatar dependabot[bot] avatar ifielder avatar john-tipper avatar polothy avatar semantic-release-bot avatar xhiroga avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cdk-assume-role-credential-plugin's Issues

AccessDeniedException when trying to get GetSecretValue cross-account

I'm modifying the code from this workshop to do cross-account rather than cross-region.

https://cdk-advanced.workshop.aws/start.html

In source stack I try to get a secret value from target account

const myKeyId = SecretValue.secretsManager(',{
jsonField: 'MyKeyID',
}).toString();

I receive this error:
User: arn:aws-us-gov:sts:::assumed-role/cdk-hnb659fds-cfn-exec-role--us-gov-west-1/AWSCloudFormation is not authorized to perform: secretsmanager:GetSecretValue on resource: arn:aws-us-gov:secretsmanager:us-gov-west-1:㊙️-xxxxxx

It seems this scenario is something the plugin was meant to solve.

Is this expected behavior?

Plugin doesn't assume role for target env if current AWS Profile is set to same account Id as target env

So, I read thru the docs and it says if the account needing to deploy to is already the currently active one via AWS Profile etc, then the plugin won't need to assume a role to deploy to the env.

This is problematic however, because the plugin is assuming that the current AWS Profile is set to an appropriate role.
Same account, doesn't mean same role.

Is there a way to FORCE the plugin to always attempt to assume the roles for each env?

cdk deploy doesn't work for a newstylesynth

I am not sure it is right place to open it, but it seems that cdk synth works, whilst cdk deploy and cdk diff doesn't when using this plugin and newstyle synth.

It looks like it returns cdk-hnb659fds-deploy-role.... to CDK, and then CDK tries to use that role to assume same role again.

Error I get:

Could not assume role in target account (did you bootstrap the environment with the right '--trust's?): 
User: arn:aws:sts::1454YYYYYYYY:assumed-role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2/1454YYYYYYY-0-session 
is not authorized to perform: sts:AssumeRole 
on resource: arn:aws:iam::1454YYYYYYY:role/cdk-hnb659fds-deploy-role-1454YYYYYYY-eu-west-2

My setup:

[profile mycorp-deploymentscore-sso]
sso_start_url = https://d-deadbeef.awsapps.com/start
sso_region = eu-west-1
sso_account_id = 0147XXXXXXX
sso_role_name = AWSAdministratorAccess
region = eu-west-2

[profile mycorp-deploymentscore]
credential_process = /home/mivanov/pyenv/aws/bin/aws2-wrap --process --profile mycorp-deploymentscore-sso
region = eu-west-2

cdk.context.json:

{
  "assume-role-credentials:readIamRoleName": "cdk-hnb659fds-deploy-role-{ACCOUNT_ID}-eu-west-2"
}

bin.ts:

const managementAccount = { account: '1454YYYYYYYY, region: 'eu-west-2' };

const app = new cdk.App();
new OrganisationStack(app, 'OrganisationStack', { env: managementAccount });

Relevant output from diff -v:

Stack OrganisationStack
Reading existing template for stack OrganisationStack.
AssumeRoleCredentialPlugin found value for readIamRole cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2. checking if we can obtain credentials
canProvideCredentails for read role: true
Using AssumeRoleCredentialPlugin credentials for account 1454YYYYYYYY
AssumeRoleCredentialPlugin getting credentials for role arn:aws:iam::1454YYYYYYYY:role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2 with mode 0
Retrieved account ID 1454YYYYYYYY from disk cache
Assuming role 'arn:aws:iam::1454YYYYYYYY:role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2'.
Call failed: describeStacks({"StackName":"OrganisationStack"}) => Could not assume role in target account (did you bootstrap the environment with the right '--trust's?): User: arn:aws:sts::1454YYYYYYYY:assumed-role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2/1454YYYYYYYY-0-session is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::1454YYYYYYYY:role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2
Could not assume role in target account (did you bootstrap the environment with the right '--trust's?): User: arn:aws:sts::1454YYYYYYYY:assumed-role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2/1454YYYYYYYY-0-session is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::1454YYYYYYYY:role/cdk-hnb659fds-deploy-role-1454YYYYYYYY-eu-west-2

Patching plugin locally, so that getProvider always returns default credentials:

   async getProvider(accountId, mode) {
            return this.defaultCredentials();
    }

makes diff, synth and deploy work on an empty stack with no assets. I didn't try with a more complicated stacks with lookups and assets, but I expect it to fail badly.

Incompatible with CDK 1.87.0

The CDK core API has changed in an incompatible way in commit aws/aws-cdk@e5c616f:

this.config = await new Configuration(yargs.argv).load();

Instead of passing the command-line args directly to new Configuration(), they now need to be wrapped in ConfigurationProps.commandLineArguments:

    this.config = await new Configuration({ commandLineArguments: yargs.argv }).load();

Alternatively, the plugin would need to fix its dependency declaration to "before 1.87.0"

Using aws sdk (boto3) calls across accounts in stacks

Hi,

I'm unsure if I'm running into a plugin installation problem or a limitation of this plugin (or how I'm supposed to call AWS APIs within stacks).

Essentially, I'd like to know if I should be able to make AWS SDK calls, or specifically boto3 in Python, within stacks when using this plugin. In my current installation, boto3 only uses the profile set in the terminal for all stacks across all accounts. This is not my desired behavior, as I'd like calls made within each stack to only apply to the account that is provided in the stack's Environment object.

Is this possible or am I asking for a feature that's not yet implemented? Thanks.

bootstrapping using environment variable credentials fails if a shared credentials file exists

bootstrapping using credential env variables (AWS_ACCESS_KEY_ID, ...) always fails if a shared credentials file (~/.aws/credentials) exists with this error:

AssumeRoleCredentialPlugin cannot obtain credentials for role cdk-writeRole
canProvideCredentails for read role: false
canProvideCredentails for write role: false
 ❌  Environment aws://111111111111/eu-central-1 failed bootstrapping: Error: Need to perform AWS calls for account 111111111111, but the current credentials are for 222222222222, and none of these plugins found any: AssumeRoleCredentialPlugin

Turns out the credentials given in the env variables are not used due to the order of the credential provider chain.

* The default CredentialProviderChain will check for
* EnvironmentCredentials first, but here we're telling
* it to first check for ECSCredentials (i.e. what CodeBuild uses).
*/
private defaultCredentials(): Promise<AWS.Credentials> {
const profile = this.config.settings.get(['profile']);
const masterCreds = new AWS.CredentialProviderChain([
function () { return new AWS.ECSCredentials(); },
function () { return new AWS.SharedIniFileCredentials({ profile: profile }); },
function () { return new AWS.TokenFileWebIdentityCredentials(); },
function () { return new AWS.ProcessCredentials({ profile: profile }); },
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); },
function () { return new AWS.EC2MetadataCredentials(); },
]);
return masterCreds.resolvePromise();

While I understand from the comment that there is a specific reason to reorder the credential provider chain concerning the priority of AWS.ECSCredentials() I think it would be less surprising to stick to the default order for the rest of the chain.

Integrate into CDK

It would be great to integrate this plugin in CDK natively and use the bootstrapped cross-account roles of the new bootstrapping flow.

problem with default credentails and named profiles

Hi, we are running cdk deploy with --profile my-profile option and have a named profile my-profile in aws credentials file. It looks like the plugin is looking for AWS.ECSCredentials and AWS.EnvironmentCredentials. I expected the plugin to use profile name from context and AWS.SharedIniFileCredentials to load default credentials. Getting an error Variable AWS_ACCESS_KEY_ID not set from AWS.EnvironmentCredentials when running cdk locally. I would expect the plugin to support named profiles in the credentials file without having to pass environment variables. Is there a way to solve this problem, or is possible to add AWS.SharedIniFileCredentials to the provider chain when fetching master (default) credentials in the plugin?

Unable to resolve plugin in CDK2

Hi,
we wanted to use this plugin with CDKv2.
It is installed via the package.json and added to the cdk.json.
When running npx cdk synth we get the error down below.

Is this a bug in CDK2 or this plugin?

Unable to resolve plugin cdk-assume-role-credential-plugin: Error: Cannot find module 'cdk-assume-role-credential-plugin'
Require stack:
- /usr/local/lib/node_modules/aws-cdk/bin/cdk.js
- /usr/local/lib/node_modules/aws-cdk/bin/cdk
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.resolve (node:internal/modules/cjs/helpers:108:19)
    at tryResolve (/usr/local/lib/node_modules/aws-cdk/bin/cdk.ts:191:24)
    at loadPlugins (/usr/local/lib/node_modules/aws-cdk/bin/cdk.ts:181:26)
    at initCommandLine (/usr/local/lib/node_modules/aws-cdk/bin/cdk.ts:199:3)
Unable to resolve plug-in: cdk-assume-role-credential-plugin

Race condition in constructor of assume-role-source

Thanks for this plugin, it's an enormous help when performing cross-account actions. Unfortunately, there is a race condition in the constructor, where under certain circumstances, loadContext() will not have finished before the plugin is called, resulting in a not-very-helpful error:

TypeError: cannot read property 'context' of undefined

which emanates from this line here: https://github.com/aws-samples/cdk-assume-role-credential-plugin/blob/main/lib/assume-role-source.ts#L101

The race condition is triggered whenever there is a delay in getting the context, which is usually a result of not having correct credentials. The constructor returns immediately, having fired off loadContext(), but if there is a delay in this occurring, then canProvideCredentials() can be called immediately, where this.config has not yet been set.

The solution, for which I will push a PR shortly, is to wait in isAvailable() for the promise to complete and only then return, rather than returning true immediately. The rest of the CDK framework will wait for the plugin to report its availability and as there is a guarantee that no other methods get called until isAvailable() has returned true, the race condition is fixed.

Ability to assume role into 300+ accounts

Even though I'm using this plugin, I'd have to specifically mention the stack multiple times in the required-resources along with the account ids. This is ideal if we have limited number of AWS Accounts.

In the context where we have 100s of accounts, this isn't scalable. Please advise, if there is a workaround of this, until this becomes a feature where I could just a for loop to iterate over boto3.Sessions with different account role credentials.

Docs incorrectly lead to belive, that cdk-hnb659fds-deploy-role is usable with newstyle synthesis

Recent CDK versions with new style synthesis are capable of assuming role in the destination account by itself, no plugin needed. Where plugin comes handy is with lookups, which still don't work cross account.

Documentation here points that readOnlyRole can be a role from bootstrap stack:

This is especially handy with the new CDK Bootstrap style because the new bootstrap already creates roles that can be used with this plugin.

But this role is not very usable, all it can do is to call cloudformation, it can't do lookups:

https://github.com/aws/aws-cdk/blob/282d242c513a9bc853e9b96ff782a7823abd5a5a/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml#L294-L365

Hence there is no much point in using it with newstyle synthesis.

EC2 Metadata roleName request returned error

I'm getting this error when cloning this app:
EC2 Metadata roleName request returned error

I've made no changes aside from entering the AWS account IDs. I've confirmed that the accounts are configured with AWS CLI credentials.

AWS CLI Version: 2.1.26
AWS CDK Version: 1.89.0
Windows

partition support

Role arn is using hard code partition aws to make it not to work in aws-cn and gov us partition.

logging.setVerbose error on clean install

Hello

When I create a new CDK app, include this plugin and cdk synth I get:

(node:9837) UnhandledPromiseRejectionWarning: TypeError: logging.setVerbose is not a function
    at AssumeRoleCredentialProviderSource.loadContext (/home/gareth/kzn/kzn/aws-operations-chatbot/node_modules/cdk-assume-role-credential-plugin/lib/assume-role-source.ts:138:13)
(node:9837) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9837) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I believe it's https://github.com/aws-samples/cdk-assume-role-credential-plugin/blob/main/lib/assume-role-source.ts#L138

Repro steps:

Does this plugin work with context lookups?

I did try to use this plugin to deploy a CDK app cross account.

But it failed on looking up vpc and R53 hosted zone. Does this plugin also having same limitation as cdk pipelines?

Unable to use cdk-assume-role-credential-plugin to deploy resources in HongKong Region (ap-east-1), probably all regions not enabled by default

I'm having an issue using this plugin to deploy resources(actually a VPC only) in ap-east-1 region, while the same code is workable is us-east-1 region.

Successfully synthesized, but with the following complaints seen in the middle of the output

Some context information is missing. Fetching...
Reading AZs for TargetAccount:ap-east-1
AssumeRoleCredentialPlugin found value for readIamRole cdk-readOnlyRole. checking if we can obtain credentials
error assuming role AccessDenied: User: arn:aws:iam::SharedAccount:user/XXX is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam:: TargetAccount:role/cdk-readOnlyRole
    at Request.extractError (/usr/local/lib/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/protocol/query.js:50:29)
...

when running cdk deploy, the following error occurred:

[Error at /EksTsDemoStack] Need to perform AWS calls for account TargetAccount, but the current credentials are for SharedAccount, and none of these plugins found any: AssumeRoleCredentialPlugin
Found errors

It might be related to the STS endpoint problem, similar issue .

Is it possible to use default credentials and assume from those?

Hello,

I don't know if this relates to #7

I have an IAM user in ~/.aws and would like that one to assume a role I would usually do this: aws sts assume-role --role-arn arn:aws:iam .... and then get the credentials and export them to environment variables.

I tried the plugin but it didn't seem to work for me. What I can see in the log is the following:

CDK toolkit version: 1.63.0 (build 7a68125)

cdk.json: {
  "app": "python /app_deploy.py",
  "plugin": [
    "cdk-assume-role-credential-plugin"
  ]
}
cdk.context.json: {
  "assume-role-credentials:writeIamRoleName": "test",
  "assume-role-credentials:readIamRoleName": "test"
}

Loading plug-in: cdk-assume-role-credential-plugin from /home/user/.nvm/versions/node/v12.18.4/lib/node_modules/cdk-assume-role-credential-plugin/lib/index.js
Toolkit stack: CDKToolkit
Setting "CDK_DEFAULT_REGION" environment variable to eu-central-1
Resolving default credentials
Retrieved account ID 582XXXXXXXXXfrom disk cache
Setting "CDK_DEFAULT_ACCOUNT" environment variable to 582XXXXXXXXX
context: {
  'assume-role-credentials:writeIamRoleName': 'test',
  'assume-role-credentials:readIamRoleName': 'test',
  'aws:cdk:enable-path-metadata': true,
  'aws:cdk:enable-asset-metadata': true
}
outdir: cdk.out
env: {
  CDK_DEFAULT_REGION: 'eu-central-1',
  CDK_DEFAULT_ACCOUNT: '582XXXXXXXXX',
  CDK_CONTEXT_JSON: '{"assume-role-credentials:writeIamRoleName":"test","assume-role-credentials:readIamRoleName":"test","aws:cdk:enable-path-metadata":true,"aws:cdk:enable-asset-metadata":true}',
  CDK_OUTDIR: 'cdk.out',
  CDK_CLI_ASM_VERSION: '5.0.0',
  CDK_CLI_VERSION: '1.63.0'

I can also paste the full log but I think these are the important bits.

When I deploy I get permission issues. So here my questions:

  • Am I supposed to see a log message like you describe in the README getting credentials for role arn:aws:iam::2383838383:role/synthRole with mode 0
  • Am I assuming right I don't need the full ARN of the role?
  • Is there some other misconfiguration?

error assuming role Error [ConfigError]: Missing region in config

I'm having an issue using this plugin in the gitlab CI that corresponds to this stack trace:

AssumeRoleCredentialPlugin found value for readIamRole CDKAdminAccess. checking if we can obtain credentials
error assuming role Error [ConfigError]: Missing region in config
    at Request.optInRegionalEndpoint (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/services/sts.js:75:30)
    at Request.callListeners (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/request.js:688:14)
    at Request.transition (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at Request.runTo (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/request.js:408:15)
    at /builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/request.js:797:12
    at new Promise (<anonymous>)
    at Request.promise (/builds/foo/node_modules/cdk-assume-role-credential-plugin/node_modules/aws-sdk/lib/request.js:783:12) {
  code: 'ConfigError',
  time: 2021-06-29T00:38:56.510Z
}

The error appears to correspond with the following function in https://github.com/aws-samples/cdk-assume-role-credential-plugin/blob/main/lib/assume-role-source.ts:

   /**
   * Try to assume the specified role and return the credentials or undefined
   */
  private async tryAssumeRole(roleArn: string, accountId: string): Promise<AWS.STS.Credentials | undefined> {
    
    const region = this.config && this.config.settings && this.config.settings.get(["context"]).region;

    region && AWS.config.update({ region });

    const sts = new AWS.STS({
      credentials: await this.defaultCredentials(),  ...(region && { region }),
    });
 
    let response: AWS.STS.Credentials | undefined;
    try {
      const resp = await sts.assumeRole({
        RoleArn: roleArn,
        RoleSessionName: `${accountId}-session`
      }).promise();
      response = resp.Credentials;
    } catch (e) {
      logging.debug('error assuming role %s', e)
      return undefined
    }
    return response
  }

This always works locally for me using yarn cdk diff and the appropriate AWS_ACCESS_KEY_ID + secret combo. I was hoping that this response would solve the issue but no luck. Any idea what's going on? Why does this plugin, when running in a CI environment rather than on my local machine, always fail to find a region?

Unable to assume cdk-hnb659fds-lookup-role when using Vpc.fromLookup

If I have this in my stack

    // Use existing VPC
    const vpc = ec2.Vpc.fromLookup(this, 'VPC', {
      isDefault: false
    });

I get the following error

credentials returned by plugin 'AssumeRoleCredentialPlugin' could not be used to assume 'arn:aws:iam::123456789012:role/cdk-hnb659fds-lookup-role-123456789012-us-east-2', but are for the right account. Proceeding anyway.
[Error at /PipelineStack/Dev/AppStack] You are not authorized to perform this operation.
Found errors

I have everything else set up correctly and am able to deploy into multiple accounts no problem using the read only deploy role using new style synthesis and all that, but it doesn't like this

Doesn't work with latest version (1.107.0)

Trying to debug this, none of the functions are executing other than loadContext() when running this with synth -v (cdk version 1.107.0).

For example you don't see in the verbose messages...

AssumeRoleCredentialPlugin found value for readIamRole cdk-readOnlyRole. checking if we can obtain credential

etc.

AssumeRoleCredentialPlugin cannot obtain credentials for role cdk-writeRole

AssumeRoleCredentialPlugin cannot obtain credentials for role cdk-writeRole
canProvideCredentails for read role: false
canProvideCredentails for write role: false
Need to perform AWS calls for account 11111111111, but the current credentials are for 22222222222, and none of these plugins found any: AssumeRoleCredentialPlugin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.