Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run cdk commands from an IAM role?

I am trying to deploy aws-cdk infrastructure as code from a jenkins pipeline but it requires aws credentials stored in ~/.aws/credentials.

The server running jenkins was provided with an IAM role with enough permissions to deploy any type of ressource. I have also tried passing env variables to provide it with the correct regions and account: CDK_DEFAULT_ACCOUNT=XXX CDK_DEFAULT_REGION=us-east-2.

This is my current stage

        stage('Deploy test infrastructure') {
          container(cdkDeployContainer.getName()) {
            sh("npm install -g aws-cdk aws-cli")
            sh("cd test-infrastructure && npm install && CDK_DEFAULT_ACCOUNT=154438573167 CDK_DEFAULT_REGION=us-east-2 cdk bootstrap")
          }
        }

I am receiving this error Unable to determine default account and/or region Is it possible to use a role IAM while using the CDK? what are the other alternatives to providing an IAM programatic access key?

like image 826
Guillaume Bibeau-Laviolette Avatar asked Sep 04 '19 18:09

Guillaume Bibeau-Laviolette


2 Answers

It is possible. You just need to assume the role. Here's how you can do it:

#!/usr/bin/env bash

export ACCOUNT_ID="154438573167"
role_arn="arn:aws:iam::${ACCOUNT_ID}:role/jenkins-deploy-role"

export AWS_DEFAULT_REGION="us-east-2"
KST=($(aws sts assume-role --role-arn "${role_arn}" --role-session-name jenkins --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text))
unset AWS_SECURITY_TOKEN
export AWS_ACCESS_KEY_ID=${KST[0]}
export AWS_SECRET_ACCESS_KEY=${KST[1]}
export AWS_SESSION_TOKEN=${KST[2]}
export AWS_SECURITY_TOKEN=${KST[2]}

# Now you have assumed the role and obtained temporary credentials.
cdk bootstrap
like image 77
0x32e0edfb Avatar answered Oct 11 '22 20:10

0x32e0edfb


You can use --role-arn parameter of the cdk cli to assume a role.

for example:

cdk deploy --role-arn arn:aws:iam::01234567890:role/jenkins-deploy-role
like image 23
Vincent Claes Avatar answered Oct 11 '22 21:10

Vincent Claes