简体   繁体   中英

Launch AWS EC2 Instance with User-data using the .NET SDK

How do I set ECS_CLUSTER=my_cluster_name in user-data when launching a new EC2 instance using the AWS .NET SDK?

I've found info on doing this manually by running a bash script on the machine. But I'm specifically interested in learning how to do this programmatically, using the SDK.

Found it in the RunInstancesRequest class. The key for me was not only in finding the UserData field, but also in including the IamInstanceProfile. Here's an example:

string userDataString = $"#!/bin/bash \necho ECS_CLUSTER=my_cluster_name >> /etc/ecs/ecs.config";
string userData = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userDataString));
var response = client.RunInstances(new RunInstancesRequest 
{
    ImageId = "ami-abc12345",
    InstanceType = "t2.micro",
    KeyName = "my-key-pair",
    MaxCount = 1,
    MinCount = 1,
    SecurityGroupIds = new List<string> { "sg-1a2b3c4d"},
    SubnetId = "subnet-6e7f829e",
    UserData = userData,
    IamInstanceProfile = new IamInstanceProfileSpecification { Name = "ecsInstanceRole" }
});

https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html

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