简体   繁体   中英

How to create cloud formation using IAM roles in AWS Java SDK?

I'm very new to Amazon cloud formation technique My current task is to create a stack on Amazon Cloud Formation using Java SDK with an IAM role. On the AWS CLI , I am able to create the amazon cloud formation by adding an additional parameter --profile . I have created a profile with the role-arn in the config file as mentioned in the following link .

Now I want to implement the same using Java SDK from AWS . My Stack request in Java is as follows

CreateStackRequest r = new CreateStackRequest();
r.withStackName(getStackName());
r.withParameters(getParameters());
r.withTemplateURL(getTemplate());
r.withCapabilities(getCapabilities());
r.withRoleARN(getArnRole());

My Amazon cloud formation client initialisation is as follows

amazonClient=AmazonCloudFormationClientBuilder.standard()
             .withCredentials(new ProfileCredentialsProvider())
             .withRegion(Regions.US_EAST_1)
             .build();

But I am unable to create an amazon cloud formation as it is giving me the following error

Exception in thread "main" com.amazonaws.services.cloudformation.model.AmazonCloudFormationException:
User: arn:aws:iam::xxxxxxx:user/xxxxxxx is not authorized to perform: iam:PassRole
on resource: arn:aws:iam::xxxxx:role/xxxxxxxx (Service: AmazonCloudFormation;
Status Code: 403; Error Code: AccessDenied; Request ID: xxxxxxxxxx)

Can somebody let me know what am I doing wrong?

EDIT:

AWS CLI

I have installed AWS SDK on my local windows system. To execute the cloud formation command on the aws cli I am doing the following

aws cloudformation create-stack  --stack-name xxxxx
--template-url xxxxxxxx 
--capabilities "CAPABILITY_IAM" --parameters xxxxxx --profile xxxxxxx

The template and parameters are stored in json format in a s3 bucket. When I ran the above command line I got the following output

{
  "StackId": "xxxxxxx"
}

AWS Java SDK

I have created a Java code which take the following as command Line arguments

--stack-name xxxxxx--template-url xxxxx 
--capabilities "CAPABILITY_IAM" --parameters xxxxx 
--profile xxxxxx --access-key xxxxxxx --secret-key xxxxxxxx

My AWS config file is as follows

 [default]
 output = json
 region = us-east-1
 [profile xxxxx]
 role_arn = arn:aws:iam::xxxxxxx:role/xxxxxxxx
 source_profile = default
 region = us-east-1

My AWS credentials file is as follows

 [default]
 aws_access_key_id = xxxxxx
 aws_secret_access_key = xxxxxx
 [profile xxxxxx]
 aws_access_key_id = xxxxxx
 aws_secret_access_key = xxxxxxx

In the Amazon cloud formation client initialisation , I have tried the following

 1. amazonClient=AmazonCloudFormationClientBuilder.standard()
             .withCredentials(new ProfileCredentialsProvider())
             .withRegion(Regions.US_EAST_1)
             .build();

 2. BasicAWSCredentials  credentials=new BasicAWSCredentials(accessKey,secretKey); 
   AmazonCloudFormationClientBuilder.standard().withCredentials(new 
   AWSStaticCredentialsProvider(credentials)).build();

In both the initialisations , I have got the same error .

You can create a new Cloud Formation stack by using the AWS CloudFormation Java API V2. To run this code, you must place your template into a S3 bucket. Also, you must setup a IAM role with CloudFormation, S3, and EC2 permissions.

The following code successfully creates a Stack.

// snippet-start:[cf.java2.create_stack.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;
import software.amazon.awssdk.services.cloudformation.model.OnFailure;
import software.amazon.awssdk.services.cloudformation.model.CreateStackResponse;
import software.amazon.awssdk.services.cloudformation.model.Parameter;
// snippet-end:[cf.java2.create_stack.import]

/**
 *  To run this example, you must have a valid template that is located in a S3 bucket.
 *  For example:
 *
 *  https://s3.amazonaws.com/mybucket/CloudFormationTemplate.yml
 *
 *  Also, the role that you use must have CloudFormation permissions as well as S3 and EC2 permissions. For more information,
 *  see "Getting started with AWS CloudFormation" in the AWS CloudFormation User Guide.
 *
 */

public class CreateStack {

   public static void main(String[] args) {


        String stackName = "mystack2";
        String roleARN = "arn:aws:iam::<enter ARN Role>";
        String location = "https://s3.amazonaws.com/<BUCKET NAME>/CloudFormationTemplate.yml";

        Region region = Region.US_EAST_1;
        CloudFormationClient cfClient = CloudFormationClient.builder()
                .region(region)
                .build();

        try {
            
            // Ensure you set the correct key name and value
            Parameter myParameter = Parameter.builder()
                    .parameterKey("KeyName")
                    .parameterValue("keypair1")
                    .build();

            CreateStackRequest stackRequest = CreateStackRequest.builder()
                .stackName(stackName)
                .templateURL(location)
                .roleARN(roleARN)
                .onFailure(OnFailure.ROLLBACK)
                .parameters(myParameter)
                .build();

            CreateStackResponse stackResponse = cfClient.createStack(stackRequest);
            System.out.println("The stack Id value is " +stackResponse.stackId());

        } catch (CloudFormationException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM