I'm working on writing custom controller for our kubernetes cluster and that'll listen to node events and perform some operation on the node.I'm using kubernetes client-go library and able to capture kubernetes events whenever a node is attached or removed from the cluster. But is it possible to get AWS instance details of kubernetes node that has been created like instance id, tags etc ? Thanks in advance.
PS: I have installed the kubernetes cluster using kops
On receiving the event for node creation, it's object object's attribute Name object.Name has the private dns of the aws instance that was created. Using the private dns of the instance, we could query for instance-id using aws-sdk-go
hostName := object.Name
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
// Create new EC2 client
ec2Svc := ec2.New(sess)
var instanceId string
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("private-dns-name"),
Values: []*string{aws.String(hostName)},
},
},
}
// Call to get detailed information on each instance
result, err := ec2Svc.DescribeInstances(params)
if err != nil {
fmt.Println("there was an error listing instances in", err.Error())
log.Fatal(err.Error())
}
for idx, res := range result.Reservations {
fmt.Println(" > Reservation Id", *res.ReservationId, " Num Instances: ", len(res.Instances))
for _, inst := range result.Reservations[idx].Instances {
// result[idx].SetDisableApiTermination(true);
instanceId = *inst.InstanceId
fmt.Println(" - Instance ID: ", *inst.InstanceId)
break // Only one instance will match the private dns
}
}
With the instance id, we could perform any operations on the ec2 instance using aws-sdk-go API's.