func ExampleCloudFormation_CreateStack() {
	svc := cloudformation.New(nil)

	params := &cloudformation.CreateStackInput{
		StackName: aws.String("StackName"), // Required
		Capabilities: []*string{
			aws.String("Capability"), // Required
			// More values...
		},
		DisableRollback: aws.Boolean(true),
		NotificationARNs: []*string{
			aws.String("NotificationARN"), // Required
			// More values...
		},
		OnFailure: aws.String("OnFailure"),
		Parameters: []*cloudformation.Parameter{
			&cloudformation.Parameter{ // Required
				ParameterKey:     aws.String("ParameterKey"),
				ParameterValue:   aws.String("ParameterValue"),
				UsePreviousValue: aws.Boolean(true),
			},
			// More values...
		},
		StackPolicyBody: aws.String("StackPolicyBody"),
		StackPolicyURL:  aws.String("StackPolicyURL"),
		Tags: []*cloudformation.Tag{
			&cloudformation.Tag{ // Required
				Key:   aws.String("TagKey"),
				Value: aws.String("TagValue"),
			},
			// More values...
		},
		TemplateBody:     aws.String("TemplateBody"),
		TemplateURL:      aws.String("TemplateURL"),
		TimeoutInMinutes: aws.Long(1),
	}
	resp, err := svc.CreateStack(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
Exemple #2
0
func ListChanges(app string) (Changes, error) {
	req := &dynamodb.QueryInput{
		KeyConditions: &map[string]*dynamodb.Condition{
			"app": &dynamodb.Condition{
				AttributeValueList: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{S: aws.String(app)},
				},
				ComparisonOperator: aws.String("EQ"),
			},
		},
		Limit:            aws.Long(10),
		ScanIndexForward: aws.Boolean(false),
		TableName:        aws.String(changesTable(app)),
	}

	res, err := DynamoDB().Query(req)

	if err != nil {
		return nil, err
	}

	changes := make(Changes, len(res.Items))

	for i, item := range res.Items {
		changes[i] = *changeFromItem(*item)
	}

	return changes, nil
}
func ExampleLambda_CreateEventSourceMapping() {
	svc := lambda.New(nil)

	params := &lambda.CreateEventSourceMappingInput{
		EventSourceARN:   aws.String("Arn"),                 // Required
		FunctionName:     aws.String("FunctionName"),        // Required
		StartingPosition: aws.String("EventSourcePosition"), // Required
		BatchSize:        aws.Long(1),
		Enabled:          aws.Boolean(true),
	}
	resp, err := svc.CreateEventSourceMapping(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func ExampleECS_DeregisterContainerInstance() {
	svc := ecs.New(nil)

	params := &ecs.DeregisterContainerInstanceInput{
		ContainerInstance: aws.String("String"), // Required
		Cluster:           aws.String("String"),
		Force:             aws.Boolean(true),
	}
	resp, err := svc.DeregisterContainerInstance(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func ExampleCloudFormation_EstimateTemplateCost() {
	svc := cloudformation.New(nil)

	params := &cloudformation.EstimateTemplateCostInput{
		Parameters: []*cloudformation.Parameter{
			&cloudformation.Parameter{ // Required
				ParameterKey:     aws.String("ParameterKey"),
				ParameterValue:   aws.String("ParameterValue"),
				UsePreviousValue: aws.Boolean(true),
			},
			// More values...
		},
		TemplateBody: aws.String("TemplateBody"),
		TemplateURL:  aws.String("TemplateURL"),
	}
	resp, err := svc.EstimateTemplateCost(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
// Use S3 for simplicity
func TestPaginationTruncation(t *testing.T) {
	count := 0
	client := s3.New(nil)

	reqNum := &count
	resps := []*s3.ListObjectsOutput{
		&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key1")}}},
		&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key2")}}},
		&s3.ListObjectsOutput{IsTruncated: aws.Boolean(false), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key3")}}},
		&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key4")}}},
	}

	client.Handlers.Send.Clear() // mock sending
	client.Handlers.Unmarshal.Clear()
	client.Handlers.UnmarshalMeta.Clear()
	client.Handlers.ValidateResponse.Clear()
	client.Handlers.Unmarshal.PushBack(func(r *aws.Request) {
		r.Data = resps[*reqNum]
		*reqNum++
	})

	params := &s3.ListObjectsInput{Bucket: aws.String("bucket")}

	results := []string{}
	err := client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool {
		results = append(results, *p.Contents[0].Key)
		return true
	})

	assert.Equal(t, []string{"Key1", "Key2", "Key3"}, results)
	assert.Nil(t, err)

	// Try again without truncation token at all
	count = 0
	resps[1].IsTruncated = nil
	resps[2].IsTruncated = aws.Boolean(true)
	results = []string{}
	err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool {
		results = append(results, *p.Contents[0].Key)
		return true
	})

	assert.Equal(t, []string{"Key1", "Key2"}, results)
	assert.Nil(t, err)

}
func ExampleCloudWatch_PutMetricAlarm() {
	svc := cloudwatch.New(nil)

	params := &cloudwatch.PutMetricAlarmInput{
		AlarmName:          aws.String("AlarmName"),          // Required
		ComparisonOperator: aws.String("ComparisonOperator"), // Required
		EvaluationPeriods:  aws.Long(1),                      // Required
		MetricName:         aws.String("MetricName"),         // Required
		Namespace:          aws.String("Namespace"),          // Required
		Period:             aws.Long(1),                      // Required
		Statistic:          aws.String("Statistic"),          // Required
		Threshold:          aws.Double(1.0),                  // Required
		ActionsEnabled:     aws.Boolean(true),
		AlarmActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		AlarmDescription: aws.String("AlarmDescription"),
		Dimensions: []*cloudwatch.Dimension{
			&cloudwatch.Dimension{ // Required
				Name:  aws.String("DimensionName"),  // Required
				Value: aws.String("DimensionValue"), // Required
			},
			// More values...
		},
		InsufficientDataActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		OKActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		Unit: aws.String("StandardUnit"),
	}
	resp, err := svc.PutMetricAlarm(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func TestNoErrors(t *testing.T) {
	input := &StructShape{
		RequiredList: []*ConditionalStructShape{},
		RequiredMap: &map[string]*ConditionalStructShape{
			"key1": &ConditionalStructShape{Name: aws.String("Name")},
			"key2": &ConditionalStructShape{Name: aws.String("Name")},
		},
		RequiredBool:   aws.Boolean(true),
		OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
	}

	req := aws.NewRequest(service, &aws.Operation{}, input, nil)
	aws.ValidateParameters(req)
	assert.NoError(t, req.Error)
}
Exemple #9
0
func GetBuild(app, id string) (*Build, error) {
	req := &dynamodb.GetItemInput{
		ConsistentRead: aws.Boolean(true),
		Key: &map[string]*dynamodb.AttributeValue{
			"id": &dynamodb.AttributeValue{S: aws.String(id)},
		},
		TableName: aws.String(buildsTable(app)),
	}

	res, err := DynamoDB().GetItem(req)

	if err != nil {
		return nil, err
	}

	build := buildFromItem(*res.Item)

	return build, nil
}
func TestNestedMissingRequiredParameters(t *testing.T) {
	input := &StructShape{
		RequiredList: []*ConditionalStructShape{&ConditionalStructShape{}},
		RequiredMap: &map[string]*ConditionalStructShape{
			"key1": &ConditionalStructShape{Name: aws.String("Name")},
			"key2": &ConditionalStructShape{},
		},
		RequiredBool:   aws.Boolean(true),
		OptionalStruct: &ConditionalStructShape{},
	}

	req := aws.NewRequest(service, &aws.Operation{}, input, nil)
	aws.ValidateParameters(req)

	assert.Error(t, req.Error)
	assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
	assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message())

}
Exemple #11
0
func ListReleases(app string, last map[string]string) (Releases, error) {
	req := &dynamodb.QueryInput{
		KeyConditions: &map[string]*dynamodb.Condition{
			"app": &dynamodb.Condition{
				AttributeValueList: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{S: aws.String(app)},
				},
				ComparisonOperator: aws.String("EQ"),
			},
		},
		IndexName:        aws.String("app.created"),
		Limit:            aws.Long(10),
		ScanIndexForward: aws.Boolean(false),
		TableName:        aws.String(releasesTable(app)),
	}

	if last["id"] != "" {
		req.ExclusiveStartKey = &map[string]*dynamodb.AttributeValue{
			"app":     &dynamodb.AttributeValue{S: aws.String(app)},
			"id":      &dynamodb.AttributeValue{S: aws.String(last["id"])},
			"created": &dynamodb.AttributeValue{S: aws.String(last["created"])},
		}
	}

	res, err := DynamoDB().Query(req)

	if err != nil {
		return nil, err
	}

	releases := make(Releases, len(res.Items))

	for i, item := range res.Items {
		releases[i] = *releaseFromItem(*item)
	}

	return releases, nil
}
Exemple #12
0
func GetRelease(app, id string) (*Release, error) {
	req := &dynamodb.GetItemInput{
		ConsistentRead: aws.Boolean(true),
		Key: &map[string]*dynamodb.AttributeValue{
			"id": &dynamodb.AttributeValue{S: aws.String(id)},
		},
		TableName: aws.String(releasesTable(app)),
	}

	res, err := DynamoDB().GetItem(req)

	if err != nil {
		return nil, err
	}

	if res.Item == nil {
		return nil, fmt.Errorf("release %s not found", id)
	}

	release := releaseFromItem(*res.Item)

	return release, nil
}
Exemple #13
0
func (a *App) UpdateParams(changes map[string]string) error {
	req := &cloudformation.UpdateStackInput{
		StackName:           aws.String(a.Name),
		UsePreviousTemplate: aws.Boolean(true),
		Capabilities:        []*string{aws.String("CAPABILITY_IAM")},
	}

	params := a.Parameters

	for key, val := range changes {
		params[key] = val
	}

	for key, val := range params {
		req.Parameters = append(req.Parameters, &cloudformation.Parameter{
			ParameterKey:   aws.String(key),
			ParameterValue: aws.String(val),
		})
	}

	_, err := CloudFormation().UpdateStack(req)

	return err
}
func ExampleECS_RegisterTaskDefinition() {
	svc := ecs.New(nil)

	params := &ecs.RegisterTaskDefinitionInput{
		ContainerDefinitions: []*ecs.ContainerDefinition{ // Required
			&ecs.ContainerDefinition{ // Required
				CPU: aws.Long(1),
				Command: []*string{
					aws.String("String"), // Required
					// More values...
				},
				EntryPoint: []*string{
					aws.String("String"), // Required
					// More values...
				},
				Environment: []*ecs.KeyValuePair{
					&ecs.KeyValuePair{ // Required
						Name:  aws.String("String"),
						Value: aws.String("String"),
					},
					// More values...
				},
				Essential: aws.Boolean(true),
				Image:     aws.String("String"),
				Links: []*string{
					aws.String("String"), // Required
					// More values...
				},
				Memory: aws.Long(1),
				MountPoints: []*ecs.MountPoint{
					&ecs.MountPoint{ // Required
						ContainerPath: aws.String("String"),
						ReadOnly:      aws.Boolean(true),
						SourceVolume:  aws.String("String"),
					},
					// More values...
				},
				Name: aws.String("String"),
				PortMappings: []*ecs.PortMapping{
					&ecs.PortMapping{ // Required
						ContainerPort: aws.Long(1),
						HostPort:      aws.Long(1),
					},
					// More values...
				},
				VolumesFrom: []*ecs.VolumeFrom{
					&ecs.VolumeFrom{ // Required
						ReadOnly:        aws.Boolean(true),
						SourceContainer: aws.String("String"),
					},
					// More values...
				},
			},
			// More values...
		},
		Family: aws.String("String"), // Required
		Volumes: []*ecs.Volume{
			&ecs.Volume{ // Required
				Host: &ecs.HostVolumeProperties{
					SourcePath: aws.String("String"),
				},
				Name: aws.String("String"),
			},
			// More values...
		},
	}
	resp, err := svc.RegisterTaskDefinition(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func startClusterMonitor() {
	var log = logger.New("ns=cluster_monitor")

Tick:
	for _ = range time.Tick(5 * time.Minute) {
		log.Log("tick")

		// Ger Rack InstanceCount Parameter
		instanceCount := 0

		res, err := models.CloudFormation().DescribeStacks(
			&cloudformation.DescribeStacksInput{
				StackName: aws.String(os.Getenv("RACK")),
			},
		)

		if err != nil {
			log.Error(err)
			continue
		}

		for _, p := range res.Stacks[0].Parameters {
			if *p.ParameterKey == "InstanceCount" {
				c, err := strconv.Atoi(*p.ParameterValue)

				if err != nil {
					log.Error(err)
					break Tick
				}

				instanceCount = c
				break
			}
		}

		// List and Describe ECS Container Instances
		ires, err := models.ECS().ListContainerInstances(
			&ecs.ListContainerInstancesInput{
				Cluster: aws.String(os.Getenv("CLUSTER")),
			},
		)

		if err != nil {
			log.Error(err)
			continue
		}

		dres, err := models.ECS().DescribeContainerInstances(
			&ecs.DescribeContainerInstancesInput{
				Cluster:            aws.String(os.Getenv("CLUSTER")),
				ContainerInstances: ires.ContainerInstanceARNs,
			},
		)

		if err != nil {
			log.Error(err)
			continue
		}

		cInstanceIds := make([]string, 0)
		cInstanceConnections := make(map[string]bool)

		for _, i := range dres.ContainerInstances {
			cInstanceConnections[*i.EC2InstanceID] = *i.AgentConnected

			if *i.AgentConnected {
				cInstanceIds = append(cInstanceIds, *i.EC2InstanceID)
			}
		}

		// Get and Describe Rack ASG Resource
		resources, err := models.ListResources(os.Getenv("RACK"))

		ares, err := models.AutoScaling().DescribeAutoScalingGroups(
			&autoscaling.DescribeAutoScalingGroupsInput{
				AutoScalingGroupNames: []*string{
					aws.String(resources["Instances"].Id),
				},
			},
		)

		if err != nil {
			log.Error(err)
			continue
		}

		// Test if ASG Instance is registered and connected in ECS cluster

		aInstanceIds := []string{}
		uInstanceIds := []string{}

		for _, i := range ares.AutoScalingGroups[0].Instances {
			if connected, exists := cInstanceConnections[*i.InstanceID]; connected && exists {
				aInstanceIds = append(aInstanceIds, *i.InstanceID)
			} else {
				// Not registered or not connected => set Unhealthy
				if *i.LifecycleState == "InService" {
					_, err := models.AutoScaling().SetInstanceHealth(
						&autoscaling.SetInstanceHealthInput{
							HealthStatus:             aws.String("Unhealthy"),
							InstanceID:               aws.String(*i.InstanceID),
							ShouldRespectGracePeriod: aws.Boolean(true),
						},
					)

					if err != nil {
						log.Error(err)
						continue
					}

					uInstanceIds = append(uInstanceIds, *i.InstanceID)
				}
			}
		}

		sort.Strings(aInstanceIds)
		sort.Strings(cInstanceIds)
		sort.Strings(uInstanceIds)

		log.Log("InstanceCount=%v connected='%v' healthy='%v' marked='%s'", instanceCount, strings.Join(cInstanceIds, ","), strings.Join(aInstanceIds, ","), strings.Join(uInstanceIds, ","))
	}
}
Exemple #16
0
func ECSTaskDefinitionCreate(req Request) (string, map[string]string, error) {
	// return "", fmt.Errorf("fail")

	tasks := req.ResourceProperties["Tasks"].([]interface{})

	r := &ecs.RegisterTaskDefinitionInput{
		Family: aws.String(req.ResourceProperties["Name"].(string)),
	}

	// download environment
	var env models.Environment

	if envUrl, ok := req.ResourceProperties["Environment"].(string); ok && envUrl != "" {
		res, err := http.Get(envUrl)

		if err != nil {
			return "", nil, err
		}

		defer res.Body.Close()

		data, err := ioutil.ReadAll(res.Body)

		if key, ok := req.ResourceProperties["Key"].(string); ok && key != "" {
			cr := crypt.New(Region(&req), os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"))
			cr.AwsToken = os.Getenv("AWS_SESSION_TOKEN")

			dec, err := cr.Decrypt(key, data)

			if err != nil {
				return "", nil, err
			}

			data = dec
		}

		env = models.LoadEnvironment(data)
	}

	r.ContainerDefinitions = make([]*ecs.ContainerDefinition, len(tasks))

	for i, itask := range tasks {
		task := itask.(map[string]interface{})

		cpu, _ := strconv.Atoi(task["CPU"].(string))
		memory, _ := strconv.Atoi(task["Memory"].(string))

		r.ContainerDefinitions[i] = &ecs.ContainerDefinition{
			Name:      aws.String(task["Name"].(string)),
			Essential: aws.Boolean(true),
			Image:     aws.String(task["Image"].(string)),
			CPU:       aws.Long(int64(cpu)),
			Memory:    aws.Long(int64(memory)),
		}

		if command, ok := task["Command"].(string); ok && command != "" {
			r.ContainerDefinitions[i].Command = []*string{aws.String("sh"), aws.String("-c"), aws.String(command)}
		}

		// set environment
		for key, val := range env {
			r.ContainerDefinitions[i].Environment = append(r.ContainerDefinitions[i].Environment, &ecs.KeyValuePair{
				Name:  aws.String(key),
				Value: aws.String(val),
			})
		}

		// set task environment overrides
		if oenv, ok := task["Environment"].(map[string]interface{}); ok {
			for key, val := range oenv {
				r.ContainerDefinitions[i].Environment = append(r.ContainerDefinitions[i].Environment, &ecs.KeyValuePair{
					Name:  aws.String(key),
					Value: aws.String(val.(string)),
				})
			}
		}

		// put release in environment
		if release, ok := req.ResourceProperties["Release"].(string); ok {
			r.ContainerDefinitions[i].Environment = append(r.ContainerDefinitions[i].Environment, &ecs.KeyValuePair{
				Name:  aws.String("RELEASE"),
				Value: aws.String(release),
			})
		}

		// link to Service Stacks via environment
		if task["Services"] != nil {
			services := task["Services"].([]interface{})

			for _, service := range services {
				parts := strings.Split(service.(string), ":")

				res, err := CloudFormation(req).DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(parts[0])})

				if err != nil {
					return "", nil, fmt.Errorf("SERVICE CREATION: %s", err)
				}

				s := models.ServiceFromStack(res.Stacks[0])

				// convert Port5432TcpAddr to POSTGRES_PORT_5432_TCP_ADDR
				re := regexp.MustCompile("([a-z])([A-Z0-9])") // lower case letter followed by upper case or number, i.e. Port5432
				re2 := regexp.MustCompile("([0-9])([A-Z])")   // number followed by upper case letter, i.e. 5432Tcp

				for k, v := range s.Outputs {
					u := re.ReplaceAllString(k, "${1}_${2}")
					u = re2.ReplaceAllString(u, "${1}_${2}")
					u = parts[1] + "_" + u
					u = strings.ToUpper(u)

					r.ContainerDefinitions[i].Environment = append(r.ContainerDefinitions[i].Environment, &ecs.KeyValuePair{
						Name:  aws.String(u),
						Value: aws.String(v),
					})
				}
			}
		}

		// set links
		if links, ok := task["Links"].([]interface{}); ok {
			r.ContainerDefinitions[i].Links = make([]*string, len(links))

			for j, link := range links {
				r.ContainerDefinitions[i].Links[j] = aws.String(link.(string))
			}
		}

		// set portmappings
		if ports, ok := task["PortMappings"].([]interface{}); ok {

			r.ContainerDefinitions[i].PortMappings = make([]*ecs.PortMapping, len(ports))

			for j, port := range ports {
				parts := strings.Split(port.(string), ":")
				host, _ := strconv.Atoi(parts[0])
				container, _ := strconv.Atoi(parts[1])

				r.ContainerDefinitions[i].PortMappings[j] = &ecs.PortMapping{
					ContainerPort: aws.Long(int64(container)),
					HostPort:      aws.Long(int64(host)),
				}
			}
		}

		// set volumes
		if volumes, ok := task["Volumes"].([]interface{}); ok {
			for j, volume := range volumes {
				name := fmt.Sprintf("%s-%d-%d", task["Name"].(string), i, j)
				parts := strings.Split(volume.(string), ":")

				r.Volumes = append(r.Volumes, &ecs.Volume{
					Name: aws.String(name),
					Host: &ecs.HostVolumeProperties{
						SourcePath: aws.String(parts[0]),
					},
				})

				r.ContainerDefinitions[i].MountPoints = append(r.ContainerDefinitions[i].MountPoints, &ecs.MountPoint{
					SourceVolume:  aws.String(name),
					ContainerPath: aws.String(parts[1]),
					ReadOnly:      aws.Boolean(false),
				})
			}
		}
	}

	res, err := ECS(req).RegisterTaskDefinition(r)

	if err != nil {
		return "", nil, err
	}

	return *res.TaskDefinition.TaskDefinitionARN, nil, nil
}
Exemple #17
0
func SystemUpdate(rw http.ResponseWriter, r *http.Request) {
	log := systemLogger("update").Start()

	app, err := models.GetApp(os.Getenv("RACK"))

	if err != nil {
		log.Error(err)
		RenderError(rw, err)
		return
	}

	p := map[string]string{}

	if version := GetForm(r, "version"); version != "" {
		p["Version"] = version
	}

	if count := GetForm(r, "count"); count != "" {
		p["InstanceCount"] = count
	}

	if t := GetForm(r, "type"); t != "" {
		p["InstanceType"] = t
	}

	if len(p) > 0 {
		req := &cloudformation.UpdateStackInput{
			StackName:    aws.String(app.Name),
			Capabilities: []*string{aws.String("CAPABILITY_IAM")},
		}

		if p["Version"] == "" {
			req.UsePreviousTemplate = aws.Boolean(true)
		} else {
			req.TemplateURL = aws.String(fmt.Sprintf("http://convox.s3.amazonaws.com/release/%s/formation.json", p["Version"]))
		}

		params := app.Parameters

		for key, val := range p {
			params[key] = val
		}

		for key, val := range params {
			req.Parameters = append(req.Parameters, &cloudformation.Parameter{
				ParameterKey:   aws.String(key),
				ParameterValue: aws.String(val),
			})
		}

		_, err := models.CloudFormation().UpdateStack(req)

		if ae, ok := err.(awserr.Error); ok {
			if ae.Code() == "ValidationError" {
				switch {
				case strings.Index(ae.Error(), "No updates are to be performed") > -1:
					RenderNotFound(rw, fmt.Sprintf("no system updates are to be performed."))
					return
				case strings.Index(ae.Error(), "can not be updated") > -1:
					RenderNotFound(rw, fmt.Sprintf("system is already updating."))
					return
				}
			}
		}

		if err != nil {
			log.Error(err)
			RenderError(rw, err)
			return
		}
	}

	Redirect(rw, r, "/system")
}
func ExampleDynamoDB_Scan() {
	svc := dynamodb.New(nil)

	params := &dynamodb.ScanInput{
		TableName: aws.String("TableName"), // Required
		AttributesToGet: []*string{
			aws.String("AttributeName"), // Required
			// More values...
		},
		ConditionalOperator: aws.String("ConditionalOperator"),
		ExclusiveStartKey: &map[string]*dynamodb.AttributeValue{
			"Key": &dynamodb.AttributeValue{ // Required
				B:    []byte("PAYLOAD"),
				BOOL: aws.Boolean(true),
				BS: [][]byte{
					[]byte("PAYLOAD"), // Required
					// More values...
				},
				L: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				M: &map[string]*dynamodb.AttributeValue{
					"Key": &dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				N: aws.String("NumberAttributeValue"),
				NS: []*string{
					aws.String("NumberAttributeValue"), // Required
					// More values...
				},
				NULL: aws.Boolean(true),
				S:    aws.String("StringAttributeValue"),
				SS: []*string{
					aws.String("StringAttributeValue"), // Required
					// More values...
				},
			},
			// More values...
		},
		ExpressionAttributeNames: &map[string]*string{
			"Key": aws.String("AttributeName"), // Required
			// More values...
		},
		ExpressionAttributeValues: &map[string]*dynamodb.AttributeValue{
			"Key": &dynamodb.AttributeValue{ // Required
				B:    []byte("PAYLOAD"),
				BOOL: aws.Boolean(true),
				BS: [][]byte{
					[]byte("PAYLOAD"), // Required
					// More values...
				},
				L: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				M: &map[string]*dynamodb.AttributeValue{
					"Key": &dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				N: aws.String("NumberAttributeValue"),
				NS: []*string{
					aws.String("NumberAttributeValue"), // Required
					// More values...
				},
				NULL: aws.Boolean(true),
				S:    aws.String("StringAttributeValue"),
				SS: []*string{
					aws.String("StringAttributeValue"), // Required
					// More values...
				},
			},
			// More values...
		},
		FilterExpression:       aws.String("ConditionExpression"),
		IndexName:              aws.String("IndexName"),
		Limit:                  aws.Long(1),
		ProjectionExpression:   aws.String("ProjectionExpression"),
		ReturnConsumedCapacity: aws.String("ReturnConsumedCapacity"),
		ScanFilter: &map[string]*dynamodb.Condition{
			"Key": &dynamodb.Condition{ // Required
				ComparisonOperator: aws.String("ComparisonOperator"), // Required
				AttributeValueList: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
						B:    []byte("PAYLOAD"),
						BOOL: aws.Boolean(true),
						BS: [][]byte{
							[]byte("PAYLOAD"), // Required
							// More values...
						},
						L: []*dynamodb.AttributeValue{
							&dynamodb.AttributeValue{ // Required
							// Recursive values...
							},
							// More values...
						},
						M: &map[string]*dynamodb.AttributeValue{
							"Key": &dynamodb.AttributeValue{ // Required
							// Recursive values...
							},
							// More values...
						},
						N: aws.String("NumberAttributeValue"),
						NS: []*string{
							aws.String("NumberAttributeValue"), // Required
							// More values...
						},
						NULL: aws.Boolean(true),
						S:    aws.String("StringAttributeValue"),
						SS: []*string{
							aws.String("StringAttributeValue"), // Required
							// More values...
						},
					},
					// More values...
				},
			},
			// More values...
		},
		Segment:       aws.Long(1),
		Select:        aws.String("Select"),
		TotalSegments: aws.Long(1),
	}
	resp, err := svc.Scan(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func ExampleDynamoDB_BatchWriteItem() {
	svc := dynamodb.New(nil)

	params := &dynamodb.BatchWriteItemInput{
		RequestItems: &map[string][]*dynamodb.WriteRequest{ // Required
			"Key": []*dynamodb.WriteRequest{ // Required
				&dynamodb.WriteRequest{ // Required
					DeleteRequest: &dynamodb.DeleteRequest{
						Key: &map[string]*dynamodb.AttributeValue{ // Required
							"Key": &dynamodb.AttributeValue{ // Required
								B:    []byte("PAYLOAD"),
								BOOL: aws.Boolean(true),
								BS: [][]byte{
									[]byte("PAYLOAD"), // Required
									// More values...
								},
								L: []*dynamodb.AttributeValue{
									&dynamodb.AttributeValue{ // Required
									// Recursive values...
									},
									// More values...
								},
								M: &map[string]*dynamodb.AttributeValue{
									"Key": &dynamodb.AttributeValue{ // Required
									// Recursive values...
									},
									// More values...
								},
								N: aws.String("NumberAttributeValue"),
								NS: []*string{
									aws.String("NumberAttributeValue"), // Required
									// More values...
								},
								NULL: aws.Boolean(true),
								S:    aws.String("StringAttributeValue"),
								SS: []*string{
									aws.String("StringAttributeValue"), // Required
									// More values...
								},
							},
							// More values...
						},
					},
					PutRequest: &dynamodb.PutRequest{
						Item: &map[string]*dynamodb.AttributeValue{ // Required
							"Key": &dynamodb.AttributeValue{ // Required
								B:    []byte("PAYLOAD"),
								BOOL: aws.Boolean(true),
								BS: [][]byte{
									[]byte("PAYLOAD"), // Required
									// More values...
								},
								L: []*dynamodb.AttributeValue{
									&dynamodb.AttributeValue{ // Required
									// Recursive values...
									},
									// More values...
								},
								M: &map[string]*dynamodb.AttributeValue{
									"Key": &dynamodb.AttributeValue{ // Required
									// Recursive values...
									},
									// More values...
								},
								N: aws.String("NumberAttributeValue"),
								NS: []*string{
									aws.String("NumberAttributeValue"), // Required
									// More values...
								},
								NULL: aws.Boolean(true),
								S:    aws.String("StringAttributeValue"),
								SS: []*string{
									aws.String("StringAttributeValue"), // Required
									// More values...
								},
							},
							// More values...
						},
					},
				},
				// More values...
			},
			// More values...
		},
		ReturnConsumedCapacity:      aws.String("ReturnConsumedCapacity"),
		ReturnItemCollectionMetrics: aws.String("ReturnItemCollectionMetrics"),
	}
	resp, err := svc.BatchWriteItem(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func ExampleDynamoDB_UpdateItem() {
	svc := dynamodb.New(nil)

	params := &dynamodb.UpdateItemInput{
		Key: &map[string]*dynamodb.AttributeValue{ // Required
			"Key": &dynamodb.AttributeValue{ // Required
				B:    []byte("PAYLOAD"),
				BOOL: aws.Boolean(true),
				BS: [][]byte{
					[]byte("PAYLOAD"), // Required
					// More values...
				},
				L: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				M: &map[string]*dynamodb.AttributeValue{
					"Key": &dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				N: aws.String("NumberAttributeValue"),
				NS: []*string{
					aws.String("NumberAttributeValue"), // Required
					// More values...
				},
				NULL: aws.Boolean(true),
				S:    aws.String("StringAttributeValue"),
				SS: []*string{
					aws.String("StringAttributeValue"), // Required
					// More values...
				},
			},
			// More values...
		},
		TableName: aws.String("TableName"), // Required
		AttributeUpdates: &map[string]*dynamodb.AttributeValueUpdate{
			"Key": &dynamodb.AttributeValueUpdate{ // Required
				Action: aws.String("AttributeAction"),
				Value: &dynamodb.AttributeValue{
					B:    []byte("PAYLOAD"),
					BOOL: aws.Boolean(true),
					BS: [][]byte{
						[]byte("PAYLOAD"), // Required
						// More values...
					},
					L: []*dynamodb.AttributeValue{
						&dynamodb.AttributeValue{ // Required
						// Recursive values...
						},
						// More values...
					},
					M: &map[string]*dynamodb.AttributeValue{
						"Key": &dynamodb.AttributeValue{ // Required
						// Recursive values...
						},
						// More values...
					},
					N: aws.String("NumberAttributeValue"),
					NS: []*string{
						aws.String("NumberAttributeValue"), // Required
						// More values...
					},
					NULL: aws.Boolean(true),
					S:    aws.String("StringAttributeValue"),
					SS: []*string{
						aws.String("StringAttributeValue"), // Required
						// More values...
					},
				},
			},
			// More values...
		},
		ConditionExpression: aws.String("ConditionExpression"),
		ConditionalOperator: aws.String("ConditionalOperator"),
		Expected: &map[string]*dynamodb.ExpectedAttributeValue{
			"Key": &dynamodb.ExpectedAttributeValue{ // Required
				AttributeValueList: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
						B:    []byte("PAYLOAD"),
						BOOL: aws.Boolean(true),
						BS: [][]byte{
							[]byte("PAYLOAD"), // Required
							// More values...
						},
						L: []*dynamodb.AttributeValue{
							&dynamodb.AttributeValue{ // Required
							// Recursive values...
							},
							// More values...
						},
						M: &map[string]*dynamodb.AttributeValue{
							"Key": &dynamodb.AttributeValue{ // Required
							// Recursive values...
							},
							// More values...
						},
						N: aws.String("NumberAttributeValue"),
						NS: []*string{
							aws.String("NumberAttributeValue"), // Required
							// More values...
						},
						NULL: aws.Boolean(true),
						S:    aws.String("StringAttributeValue"),
						SS: []*string{
							aws.String("StringAttributeValue"), // Required
							// More values...
						},
					},
					// More values...
				},
				ComparisonOperator: aws.String("ComparisonOperator"),
				Exists:             aws.Boolean(true),
				Value: &dynamodb.AttributeValue{
					B:    []byte("PAYLOAD"),
					BOOL: aws.Boolean(true),
					BS: [][]byte{
						[]byte("PAYLOAD"), // Required
						// More values...
					},
					L: []*dynamodb.AttributeValue{
						&dynamodb.AttributeValue{ // Required
						// Recursive values...
						},
						// More values...
					},
					M: &map[string]*dynamodb.AttributeValue{
						"Key": &dynamodb.AttributeValue{ // Required
						// Recursive values...
						},
						// More values...
					},
					N: aws.String("NumberAttributeValue"),
					NS: []*string{
						aws.String("NumberAttributeValue"), // Required
						// More values...
					},
					NULL: aws.Boolean(true),
					S:    aws.String("StringAttributeValue"),
					SS: []*string{
						aws.String("StringAttributeValue"), // Required
						// More values...
					},
				},
			},
			// More values...
		},
		ExpressionAttributeNames: &map[string]*string{
			"Key": aws.String("AttributeName"), // Required
			// More values...
		},
		ExpressionAttributeValues: &map[string]*dynamodb.AttributeValue{
			"Key": &dynamodb.AttributeValue{ // Required
				B:    []byte("PAYLOAD"),
				BOOL: aws.Boolean(true),
				BS: [][]byte{
					[]byte("PAYLOAD"), // Required
					// More values...
				},
				L: []*dynamodb.AttributeValue{
					&dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				M: &map[string]*dynamodb.AttributeValue{
					"Key": &dynamodb.AttributeValue{ // Required
					// Recursive values...
					},
					// More values...
				},
				N: aws.String("NumberAttributeValue"),
				NS: []*string{
					aws.String("NumberAttributeValue"), // Required
					// More values...
				},
				NULL: aws.Boolean(true),
				S:    aws.String("StringAttributeValue"),
				SS: []*string{
					aws.String("StringAttributeValue"), // Required
					// More values...
				},
			},
			// More values...
		},
		ReturnConsumedCapacity:      aws.String("ReturnConsumedCapacity"),
		ReturnItemCollectionMetrics: aws.String("ReturnItemCollectionMetrics"),
		ReturnValues:                aws.String("ReturnValue"),
		UpdateExpression:            aws.String("UpdateExpression"),
	}
	resp, err := svc.UpdateItem(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}