Execute CDK Deployment on a Different AWS Account Using a Fargate Task

I have a scenario where I need to deploy a stack using CDK in Account A by running cdk synth and cdk deploy in an ECS Task located in Account B.

To enable this, I set up a role in Account A with administrator access and granted permissions to Account B so that it can assume the role. However, when the ECS task executes the commands, it encounters the following error:

Could not assume role in target account using current credentials (which are for account 614863243217). User: arn:aws:sts::<B_account_id>:assumed-role/ecs-fargate-role/65dd98a9c327410 is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::<A_account_id>:role/cdk-hnb659fds-deploy-role-473038482210-us-east-2 . Please make sure that this role exists in the account. If it doesn't exist, (re)-bootstrap the environment with the right '--trust', using the latest version of the CDK CLI.

It seems like the intended role is not being utilized to deploy the stack. How can I ensure that the created role is assumed to call CDK synth and deploy?

The role in Account A has the following permission policy and trust relationships:

Permissions Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

Trust Relationships

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<AccountB>:root"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

I've also attempted to assume the role in ECS as follows:

role_arn = stack_json["role_arn"]
aws_region = stack_json["region"]
assumed_role_object = sts_client.assume_role(
    RoleArn=role_arn,
    RoleSessionName="AssumeRoleSession1"
)
credentials = assumed_role_object['Credentials']
p = Popen(['aws configure'], stdin=PIPE, shell=True)
aws_configure_str = f"{credentials['AccessKeyId']}\n{credentials['SecretAccessKey']}\n{aws_region}\njson\n";
p.communicate(input=bytes(aws_configure_str, 'utf-8'))

This writes the credentials for the default aws cli. Additionally, I tried passing the credentials directly like this:

sb.run(f"cdk deploy", shell=True, env={
    "AWS_ACCESS_KEY_ID": credentials['AccessKeyId'],
    "AWS_SECRET_ACCESS_KEY": credentials['SecretAccessKey'],
    "AWS_DEFAULT_REGION": aws_region,
})

However, upon inspecting the logs, it appears that the credentials are not configured correctly, leading to the deployment failure with the message:

AWS Access Key ID [None]: AWS Secret Access Key [None]: Default region name [None]: Default output format [None]: Loaded stack_json

and the error states: Deployment failed: Error: Need to perform AWS calls for account , but no credentials have been configured

Answer №1

To achieve this, I created a custom script that executes cdk deploy and defines the necessary environment variables within the script itself rather than passing them as subprocess environment variables. This approach was inspired by the guidance provided in this helpful resource: AWS CDK deploy using role

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

The curious case of Node.JS: The mysterious behaviour of await not waiting

I am currently utilizing a lambda function within AWS to perform certain tasks, and it is essential for the function to retrieve some data from the AWS SSM resource in order to carry out its operations effectively. However, I am encountering difficulties i ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Expanding functionality: Steps to integrating a new endpoint into your AWS Amplify Express Server

I have created a REST express server using Amplify. Attempted to include two additional endpoints: // incorporating serverless express app.post('/myendpoint', function(req, res) { console.log('body: ', req.body) res.json(req.body) ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...