Example #1
0
func (i *EC2IaaS) CreateMachine(params map[string]string) (*iaas.Machine, error) {
	regionName, ok := params["region"]
	if !ok {
		regionName = "us-east-1"
	}
	region, ok := aws.Regions[regionName]
	if !ok {
		return nil, fmt.Errorf("region %q not found", regionName)
	}
	imageId, ok := params["image"]
	if !ok {
		return nil, fmt.Errorf("image param required")
	}
	instanceType, ok := params["type"]
	if !ok {
		return nil, fmt.Errorf("type param required")
	}
	keyName, _ := params["keyName"]
	options := ec2.RunInstances{
		ImageId:      imageId,
		InstanceType: instanceType,
		UserData:     []byte(iaas.UserData),
		MinCount:     1,
		MaxCount:     1,
		KeyName:      keyName,
	}
	securityGroup, ok := params["securityGroup"]
	if ok {
		options.SecurityGroups = []ec2.SecurityGroup{
			{Name: securityGroup},
		}
	}
	ec2Inst, err := createEC2Handler(region)
	if err != nil {
		return nil, err
	}
	resp, err := ec2Inst.RunInstances(&options)
	if err != nil {
		return nil, err
	}
	if len(resp.Instances) == 0 {
		return nil, fmt.Errorf("no instance created")
	}
	instance, err := waitForDnsName(ec2Inst, &resp.Instances[0])
	if err != nil {
		ec2Inst.TerminateInstances([]string{instance.InstanceId})
		return nil, err
	}
	machine := iaas.Machine{
		Id:      instance.InstanceId,
		Status:  instance.State.Name,
		Address: instance.DNSName,
	}
	return &machine, nil
}
Example #2
0
func Launch(args []string) {
	if len(args) != 1 {
		fmt.Println("no build given!")
		return
	}
	build := args[0]

	answer := AskQuestion("Enter Tag Name: ")

	options := ec2.RunInstances{
		ImageId:        config.Images[config.Builds[build].Image],
		InstanceType:   config.Builds[build].Size,
		KeyName:        config.Builds[build].Key,
		SecurityGroups: config.Builds[build].SecurityGroups,
	}

	cnt := config.Builds[build].Count
	if cnt != 0 {
		options.MinCount = config.Builds[build].Count
	}

	if config.Builds[build].Zone != "" {
		options.AvailZone = config.Builds[build].Zone
	}

	if config.Builds[build].UserData != "" {
		userData, err := ioutil.ReadFile(scriptPath + config.Builds[build].UserData)
		if err != nil {
			fmt.Println("Unable to read UserData script", err)
			return
		}
		options.UserData = userData
	}

	resp, err := conn.RunInstances(&options)
	if err != nil {
		fmt.Println("AWS ec2 Run Instances Fail: ", err)
		return
	}

	for idx, instance := range resp.Instances {
		fmt.Println("Now running", instance.InstanceId)
		name := answer
		if cnt > 1 {
			name = fmt.Sprintf("%s-%d", answer, idx+1)
		}
		_, err = conn.CreateTags([]string{instance.InstanceId}, []ec2.Tag{{"Name", name}})
		if err != nil {
			fmt.Println("Error Creating Tags: ", err)
		}
	}

	fmt.Println("Make sure you terminate instances to stop the cash flow.")
}