Search code examples
javaamazon-ec2aws-sdkaws-java-sdk

how to add user-data for the second time in an ec2 instance through java sdk


i am trying to add user-data for the second time after stopping the instance and while restarting i want to pass some user data again for this i am using

public InstanceStatusResponse startEc2Instance(AmazonEC2 ec2Client, String instanceId) {

    BlockDeviceMapping blockDeviceMappings = new BlockDeviceMapping();

    blockDeviceMappings.setDeviceName(storageProperties.getDeviceName());
    System.out.println("vatsal");
    ModifyInstanceAttributeRequest modifyInstanceAttributeRequest = new ModifyInstanceAttributeRequest()
            .withUserData(userdata())


    ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest();
    request.setUserData(userdata());

    System.out.println(modifyInstanceAttributeRequest.withUserData(userdata()));
    System.out.println(modifyInstanceAttributeRequest.getUserData());

    StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId);
    ec2Client.startInstances(startInstancesRequest);
    //System.out.println();
    System.out.println("Starting the ec2 instance");


    return instanceStatusResponse(ec2Client, instanceId);

}

and i am passing some userdata which also i am using base64 encoding as per demand but i am not able to send values to that ec2 machine.


Solution

  • The code you have posted is not really clear. You have created modifyInstanceAttributeRequest and request, however you don't seem to be using them.

    Nevertheless, a typically ec2 instance will not run the user-data script on reboots. The user-data scripts are only run at the first boot of the instance.

    See this about user data and run only on first boot.

    Important

    By default, user data scripts and cloud-init directives run only during the first boot cycle when an instance is launched. However, you can configure your user data scripts and cloud-init directives to run every time the instance is restarted from a stopped state. For more information, see How can I execute user data after the initial launch of my EC2 instance? in the AWS Knowledge Center

    To be able to to re-run user-data scripts on start of an ec2 instance, see this kb article from AWS.