Skip to content

Instantly share code, notes, and snippets.

@scottslowe
Created March 1, 2021 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottslowe/bc023d3ea10b2cb22f59f7e295657f23 to your computer and use it in GitHub Desktop.
Save scottslowe/bc023d3ea10b2cb22f59f7e295657f23 to your computer and use it in GitHub Desktop.
Snippet of Pulumi-Go code that attempts to write out an inventory file with the IP addresses of the instances it launches
// Create a file handle for the inventory file
f, err := os.Create("hosts")
if err != nil {
log.Printf("error creating file: %s", err.Error())
}
// Launch an EC2 instance to serve as bastion host
bastion, err := ec2.NewInstance(ctx, "bastion", &ec2.InstanceArgs{
Ami: pulumi.String(amiID.Id),
InstanceType: pulumi.String("t2.small"),
AssociatePublicIpAddress: pulumi.Bool(true),
KeyName: pulumi.String("aws_vmw_rsa"),
SubnetId: pulumi.String(subnets.Ids[0]),
VpcSecurityGroupIds: pulumi.StringArray{bastionSecGrp.ID()},
Tags: pulumi.StringMap{
"Name": pulumi.String("ans-int-bastion"),
},
})
if err != nil {
log.Printf("error launching bastion instance: %s", err.Error())
}
ctx.Export("bastionInstanceId", bastion.ID())
ctx.Export("bastionPublicIpAddress", bastion.PublicIp)
ctx.Export("bastionPrivateIpAddress", bastion.PrivateIp)
// Write IP address to inventory file
fmt.Fprintln(f, bastion.PrivateIp)
if err != nil {
log.Printf("error writing to file: %s", err.Error())
}
// Launch a private EC2 instance in each subnet/AZ
nodeIds := make([]pulumi.StringInput, numSubnets)
for idx := 0; idx < numSubnets; idx++ {
instance, err := ec2.NewInstance(ctx, fmt.Sprintf("node-%d", idx), &ec2.InstanceArgs{
Ami: pulumi.String(amiID.Id),
InstanceType: pulumi.String("t2.large"),
AssociatePublicIpAddress: pulumi.Bool(false),
KeyName: pulumi.String("aws_vmw_rsa"),
SubnetId: pulumi.String(subnets.Ids[idx]),
VpcSecurityGroupIds: pulumi.StringArray{nodeSecGrp.ID()},
Tags: pulumi.StringMap{
"Name": pulumi.String(fmt.Sprintf("ans-int-%d", idx)),
},
})
if err != nil {
log.Printf("error launching instance: %s", err.Error())
}
// Export some information
nodeIds[idx] = instance.ID()
ctx.Export(fmt.Sprintf("node%dPublicIpAddress", idx), instance.PublicIp)
ctx.Export(fmt.Sprintf("node%dPrivateIpAddress", idx), instance.PrivateIp)
// Write IP address to inventory file
fmt.Fprintln(f, instance.PrivateIp.ApplyString(func(s string) string {
var res string
res = s
return res
}))
if err != nil {
log.Printf("error writing to file: %s", err.Error())
}
}
ctx.Export("nodeIdArray", pulumi.StringArray(nodeIds))
// Close the file handle on the inventory file
err = f.Close()
if err != nil {
log.Printf("error closing file: %s", err.Error())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment