func (s *CloudFormationStack) buildUpdateStackInput(stackName string, stackDetails StackDetails) *cloudformation.UpdateStackInput { updateStackInput := &cloudformation.UpdateStackInput{ StackName: aws.String(stackName), TemplateURL: aws.String(stackDetails.TemplateURL), } if len(stackDetails.Capabilities) > 0 { updateStackInput.Capabilities = aws.StringSlice(stackDetails.Capabilities) } if len(stackDetails.NotificationARNs) > 0 { updateStackInput.NotificationARNs = aws.StringSlice(stackDetails.NotificationARNs) } if len(stackDetails.Parameters) > 0 { updateStackInput.Parameters = BuilCloudFormationParameters(stackDetails.Parameters) } if len(stackDetails.ResourceTypes) > 0 { updateStackInput.ResourceTypes = aws.StringSlice(stackDetails.ResourceTypes) } if stackDetails.StackPolicyURL != "" { updateStackInput.StackPolicyURL = aws.String(stackDetails.StackPolicyURL) } return updateStackInput }
func (clst *amazonCluster) tagSpotRequests(awsIDs []awsID) error { OuterLoop: for region, ids := range groupByRegion(awsIDs) { session := clst.getSession(region) spotIDs := getSpotIDs(ids) var err error for i := 0; i < 30; i++ { _, err = session.CreateTags(&ec2.CreateTagsInput{ Tags: []*ec2.Tag{ { Key: aws.String(clst.namespace), Value: aws.String(""), }, }, Resources: aws.StringSlice(spotIDs), }) if err == nil { continue OuterLoop } time.Sleep(5 * time.Second) } log.Warn("Failed to tag spot requests: ", err) session.CancelSpotInstanceRequests( &ec2.CancelSpotInstanceRequestsInput{ SpotInstanceRequestIds: aws.StringSlice(spotIDs), }) return err } return nil }
func setDocumentPermissions(d *schema.ResourceData, meta interface{}) error { ssmconn := meta.(*AWSClient).ssmconn log.Printf("[INFO] Setting permissions for document: %s", d.Id()) permission := d.Get("permissions").(map[string]interface{}) ids := aws.StringSlice([]string{permission["account_ids"].(string)}) if strings.Contains(permission["account_ids"].(string), ",") { ids = aws.StringSlice(strings.Split(permission["account_ids"].(string), ",")) } permInput := &ssm.ModifyDocumentPermissionInput{ Name: aws.String(d.Get("name").(string)), PermissionType: aws.String(permission["type"].(string)), AccountIdsToAdd: ids, } _, err := ssmconn.ModifyDocumentPermission(permInput) if err != nil { return errwrap.Wrapf("[ERROR] Error setting permissions for SSM document: {{err}}", err) } return nil }
// convertToContainerDef transforms each service in the compose yml // to an equivalent container definition func convertToContainerDef(inputCfg *libcompose.ServiceConfig, volumes map[string]string, outputContDef *ecs.ContainerDefinition) error { // setting memory var mem int64 if inputCfg.MemLimit != 0 { mem = inputCfg.MemLimit / kiB / kiB // convert bytes to MiB } if mem == 0 { mem = defaultMemLimit } // convert environment variables // TODO, read env file environment := []*ecs.KeyValuePair{} for _, env := range inputCfg.Environment.Slice() { parts := strings.SplitN(env, "=", 2) name := &parts[0] var value *string if len(parts) > 1 { value = &parts[1] } environment = append(environment, &ecs.KeyValuePair{ Name: name, Value: value, }) } // convert port mappings portMappings, err := convertToPortMappings(*outputContDef.Name, inputCfg.Ports) if err != nil { return err } // convert volumes from volumesFrom := []*ecs.VolumeFrom{} for _, val := range inputCfg.VolumesFrom { volumeFrom := &ecs.VolumeFrom{ SourceContainer: aws.String(val), } volumesFrom = append(volumesFrom, volumeFrom) } // convert mount points mountPoints, err := convertToMountPoints(inputCfg.Volumes, volumes) if err != nil { return err } // populating container definition, offloading the validation to aws-sdk outputContDef.Cpu = aws.Int64(inputCfg.CpuShares) outputContDef.Memory = aws.Int64(mem) outputContDef.EntryPoint = aws.StringSlice(inputCfg.Entrypoint.Slice()) outputContDef.Command = aws.StringSlice(inputCfg.Command.Slice()) outputContDef.Environment = environment outputContDef.Image = aws.String(inputCfg.Image) outputContDef.Links = aws.StringSlice(inputCfg.Links.Slice()) //TODO, read from external links outputContDef.MountPoints = mountPoints outputContDef.PortMappings = portMappings outputContDef.VolumesFrom = volumesFrom return nil }
func (clst amazonCluster) Stop(machines []Machine) error { var awsIDs []awsID for _, m := range machines { awsIDs = append(awsIDs, awsID{ region: m.Region, spotID: m.ID, }) } for region, ids := range groupByRegion(awsIDs) { session := clst.getSession(region) spotIDs := getSpotIDs(ids) spots, err := session.DescribeSpotInstanceRequests( &ec2.DescribeSpotInstanceRequestsInput{ SpotInstanceRequestIds: aws.StringSlice(spotIDs), }) if err != nil { return err } instIds := []string{} for _, spot := range spots.SpotInstanceRequests { if spot.InstanceId != nil { instIds = append(instIds, *spot.InstanceId) } } if len(instIds) > 0 { _, err = session.TerminateInstances(&ec2.TerminateInstancesInput{ InstanceIds: aws.StringSlice(instIds), }) if err != nil { return err } } _, err = session.CancelSpotInstanceRequests( &ec2.CancelSpotInstanceRequestsInput{ SpotInstanceRequestIds: aws.StringSlice(spotIDs), }) if err != nil { return err } if err := clst.wait(ids, false); err != nil { return err } } return nil }
func dropGeneratedSecurityGroup(settingValue string, meta interface{}) string { conn := meta.(*AWSClient).ec2conn groups := strings.Split(settingValue, ",") // Check to see if groups are ec2-classic or vpc security groups ec2Classic := true beanstalkSGRegexp := "sg-[0-9a-fA-F]{8}" for _, g := range groups { if ok, _ := regexp.MatchString(beanstalkSGRegexp, g); ok { ec2Classic = false break } } var resp *ec2.DescribeSecurityGroupsOutput var err error if ec2Classic { resp, err = conn.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ GroupNames: aws.StringSlice(groups), }) } else { resp, err = conn.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ GroupIds: aws.StringSlice(groups), }) } if err != nil { log.Printf("[DEBUG] Elastic Beanstalk error describing SecurityGroups: %v", err) return settingValue } log.Printf("[DEBUG] Elastic Beanstalk using ec2-classic security-groups: %t", ec2Classic) var legitGroups []string for _, group := range resp.SecurityGroups { log.Printf("[DEBUG] Elastic Beanstalk SecurityGroup: %v", *group.GroupName) if !strings.HasPrefix(*group.GroupName, "awseb") { if ec2Classic { legitGroups = append(legitGroups, *group.GroupName) } else { legitGroups = append(legitGroups, *group.GroupId) } } } sort.Strings(legitGroups) return strings.Join(legitGroups, ",") }
// convertMapToSlice converts the map [String -> bool] to a AWS String Slice that is used by our APIs as input func convertMapToSlice(mapItems map[string]bool) []*string { sliceItems := make([]string, 0, len(mapItems)) for key := range mapItems { sliceItems = append(sliceItems, key) } return aws.StringSlice(sliceItems) }
func resourceAwsVPCEndpointRouteTableAssociationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn endpointId := d.Get("vpc_endpoint_id").(string) rtId := d.Get("route_table_id").(string) input := &ec2.ModifyVpcEndpointInput{ VpcEndpointId: aws.String(endpointId), RemoveRouteTableIds: aws.StringSlice([]string{rtId}), } _, err := conn.ModifyVpcEndpoint(input) if err != nil { ec2err, ok := err.(awserr.Error) if !ok { return fmt.Errorf("Error deleting VPC Endpoint/Route Table association: %s", err.Error()) } switch ec2err.Code() { case "InvalidVpcEndpointId.NotFound": fallthrough case "InvalidRouteTableId.NotFound": fallthrough case "InvalidParameter": log.Printf("[DEBUG] VPC Endpoint/Route Table association is already gone") default: return fmt.Errorf("Error deleting VPC Endpoint/Route Table association: %s", err.Error()) } } log.Printf("[DEBUG] VPC Endpoint/Route Table association %q deleted", d.Id()) d.SetId("") return nil }
func resourceAwsVPCEndpointRouteTableAssociationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn endpointId := d.Get("vpc_endpoint_id").(string) rtId := d.Get("route_table_id").(string) _, err := findResourceVPCEndpoint(conn, endpointId) if err != nil { return err } log.Printf( "[INFO] Creating VPC Endpoint/Route Table association: %s => %s", endpointId, rtId) input := &ec2.ModifyVpcEndpointInput{ VpcEndpointId: aws.String(endpointId), AddRouteTableIds: aws.StringSlice([]string{rtId}), } _, err = conn.ModifyVpcEndpoint(input) if err != nil { return fmt.Errorf("Error creating VPC Endpoint/Route Table association: %s", err.Error()) } id := vpcEndpointIdRouteTableIdHash(endpointId, rtId) log.Printf("[DEBUG] VPC Endpoint/Route Table association %q created.", id) d.SetId(id) return resourceAwsVPCEndpointRouteTableAssociationRead(d, meta) }
func dropGeneratedSecurityGroup(settingValue string, meta interface{}) string { conn := meta.(*AWSClient).ec2conn groups := strings.Split(settingValue, ",") resp, err := conn.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ GroupIds: aws.StringSlice(groups), }) if err != nil { log.Printf("[DEBUG] Elastic Beanstalk error describing SecurityGroups: %v", err) return settingValue } var legitGroups []string for _, group := range resp.SecurityGroups { log.Printf("[DEBUG] Elastic Beanstalk SecurityGroup: %v", *group.GroupName) if !strings.HasPrefix(*group.GroupName, "awseb") { legitGroups = append(legitGroups, *group.GroupId) } } sort.Strings(legitGroups) return strings.Join(legitGroups, ",") }
// RunTask issues a run task request for the input task definition func (client *ecsClient) RunTaskWithOverrides(taskDefinition, startedBy string, count int, overrides map[string]string) (*ecs.RunTaskOutput, error) { commandOverrides := []*ecs.ContainerOverride{} for cont, command := range overrides { contOverride := &ecs.ContainerOverride{ Name: aws.String(cont), Command: aws.StringSlice([]string{command}), } commandOverrides = append(commandOverrides, contOverride) } ecsOverrides := &ecs.TaskOverride{ ContainerOverrides: commandOverrides, } resp, err := client.client.RunTask(&ecs.RunTaskInput{ Cluster: aws.String(client.params.Cluster), TaskDefinition: aws.String(taskDefinition), StartedBy: aws.String(startedBy), Count: aws.Int64(int64(count)), Overrides: ecsOverrides, }) if err != nil { log.WithFields(log.Fields{ "task definition": taskDefinition, "error": err, }).Error("Error running tasks") } return resp, err }
func TestStringValueSlice(t *testing.T) { for idx, in := range testCasesStringValueSlice { if in == nil { continue } out := aws.StringValueSlice(in) assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) for i := range out { if in[i] == nil { assert.Empty(t, out[i], "Unexpected value at idx %d", idx) } else { assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) } } out2 := aws.StringSlice(out) assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) for i := range out2 { if in[i] == nil { assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) } else { assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) } } } }
func GetEc2PrivateIpsFromInstanceIds(ec2_obj *ec2.EC2, instance_ids []string, debug bool) ([]string, error) { params := &ec2.DescribeInstancesInput{ InstanceIds: aws.StringSlice(instance_ids), } resp, err := ec2_obj.DescribeInstances(params) if err != nil { return []string{}, fmt.Errorf("Cannot retrieve EC2 instance information: %s", FormatAwsError(err)) } if len(resp.Reservations) <= 0 { return []string{}, fmt.Errorf("No EC2 instances found (Reservations.*) with specified Instance IDs filter: ", strings.Join(instance_ids, ", ")) } if len(resp.Reservations[0].Instances) <= 0 { return []string{}, fmt.Errorf("No EC2 instances found (Reservations[0].* with specified Instance IDs filter: ", strings.Join(instance_ids, ", ")) } var result []string for idx, _ := range resp.Reservations { for _, value := range resp.Reservations[idx].Instances { if *value.State.Name == "running" { result = append(result, *value.PrivateIpAddress) } else { if debug == true { fmt.Println(*value.InstanceId, "is not in a running state, excluded from results.") } } } } if len(result) == 0 { return []string{}, fmt.Errorf("No running EC2 instances found in result set, cannot proceed.") } return result, nil }
func GetEc2InstanceIdsFromContainerInstances(ecs_obj *ecs.ECS, cluster string, container_instances []string, debug bool) ([]string, error) { params := &ecs.DescribeContainerInstancesInput{ Cluster: aws.String(cluster), ContainerInstances: aws.StringSlice(container_instances), } resp, err := ecs_obj.DescribeContainerInstances(params) if err != nil { return []string{}, fmt.Errorf("Cannot retrieve ECS container instance information: %s", FormatAwsError(err)) } if len(resp.ContainerInstances) <= 0 { return []string{}, fmt.Errorf("No ECS container instances found with specified filter - cluster:", cluster, "- instances:", strings.Join(container_instances, ", ")) } var result []string for _, value := range resp.ContainerInstances { if *value.Status == "ACTIVE" { result = append(result, *value.Ec2InstanceId) } else { if debug == true { fmt.Println(*value.Ec2InstanceId, "is not in an ACTIVE state, excluded from results.") } } } if len(result) == 0 { return []string{}, fmt.Errorf("No running ECS container instances found in result set, cannot proceed.") } return result, nil }
func (s *SQSQueue) getQueueAttributes(queueURL string) (map[string]string, error) { getQueueAttributesInput := &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueURL), AttributeNames: aws.StringSlice([]string{"All"}), } s.logger.Debug("get-queue-attributes", lager.Data{"input": getQueueAttributesInput}) getQueueAttributesOutput, err := s.sqssvc.GetQueueAttributes(getQueueAttributesInput) if err != nil { s.logger.Error("aws-sqs-error", err) if awsErr, ok := err.(awserr.Error); ok { if reqErr, ok := err.(awserr.RequestFailure); ok { // AWS SQS returns a 400 if Queue is not found if reqErr.StatusCode() == 400 || reqErr.StatusCode() == 404 { return nil, ErrQueueDoesNotExist } } return nil, errors.New(awsErr.Code() + ": " + awsErr.Message()) } return nil, err } s.logger.Debug("get-queue-attributes", lager.Data{"output": getQueueAttributesOutput}) return aws.StringValueMap(getQueueAttributesOutput.Attributes), nil }
func testAccCheckASGNotificationExists(n string, groups []string, asgn *autoscaling.DescribeNotificationConfigurationsOutput) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ASG Notification ID is set") } conn := testAccProvider.Meta().(*AWSClient).autoscalingconn opts := &autoscaling.DescribeNotificationConfigurationsInput{ AutoScalingGroupNames: aws.StringSlice(groups), MaxRecords: aws.Int64(100), } resp, err := conn.DescribeNotificationConfigurations(opts) if err != nil { return fmt.Errorf("Error describing notifications: %s", err) } *asgn = *resp return nil } }
func createScheduleRunInput(p *model.RunParameters) *devicefarm.ScheduleRunInput { var wg sync.WaitGroup result := &devicefarm.ScheduleRunInput{ ProjectArn: aws.String(p.ProjectArn), Test: &devicefarm.ScheduleRunTest{}, Configuration: &devicefarm.ScheduleRunConfiguration{ Radios: &devicefarm.Radios{ Bluetooth: aws.Bool(true), Gps: aws.Bool(true), Nfc: aws.Bool(true), Wifi: aws.Bool(true), }, Location: &devicefarm.Location{ Latitude: aws.Float64(47.6204), Longitude: aws.Float64(-122.3491), }, }, } result.Name = aws.String(p.Config.RunName) result.Configuration.AuxiliaryApps = aws.StringSlice(p.Config.AdditionalData.AuxiliaryApps) if p.Config.AdditionalData.BillingMethod != "" { result.Configuration.BillingMethod = aws.String(p.Config.AdditionalData.BillingMethod) } result.Configuration.Locale = aws.String(p.Config.AdditionalData.Locale) if p.Config.AdditionalData.Location.Latitude != 0 { result.Configuration.Location.Latitude = aws.Float64(p.Config.AdditionalData.Location.Latitude) } if p.Config.AdditionalData.Location.Longitude != 0 { result.Configuration.Location.Longitude = aws.Float64(p.Config.AdditionalData.Location.Longitude) } if p.Config.AdditionalData.NetworkProfileArn != "" { result.Configuration.NetworkProfileArn = aws.String(p.Config.AdditionalData.NetworkProfileArn) } result.Configuration.Radios.Bluetooth = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Bluetooth)) result.Configuration.Radios.Gps = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Gps)) result.Configuration.Radios.Nfc = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Nfc)) result.Configuration.Radios.Wifi = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Wifi)) result.Test.Filter = aws.String(p.Config.Test.Filter) result.Test.Parameters = aws.StringMap(p.Config.Test.Parameters) if p.Config.Test.Type != "" { result.Test.Type = aws.String(p.Config.Test.Type) } else { result.Test.Type = aws.String("BUILTIN_FUZZ") } if p.Config.Test.TestPackageArn != "" { result.Test.TestPackageArn = aws.String(p.Config.Test.TestPackageArn) } else { uploadTestPackage(p, result, &wg) } if p.Config.AdditionalData.ExtraDataPackageArn != "" { result.Configuration.ExtraDataPackageArn = aws.String(p.Config.AdditionalData.ExtraDataPackageArn) } else { uploadExtraData(p, result, &wg) } wg.Wait() return result }
func (s *CloudFormationStack) buildCreateStackInput(stackName string, stackDetails StackDetails) *cloudformation.CreateStackInput { createStackInput := &cloudformation.CreateStackInput{ StackName: aws.String(stackName), TemplateURL: aws.String(stackDetails.TemplateURL), } if len(stackDetails.Capabilities) > 0 { createStackInput.Capabilities = aws.StringSlice(stackDetails.Capabilities) } if stackDetails.DisableRollback { createStackInput.DisableRollback = aws.Bool(stackDetails.DisableRollback) } if len(stackDetails.NotificationARNs) > 0 { createStackInput.NotificationARNs = aws.StringSlice(stackDetails.NotificationARNs) } if stackDetails.OnFailure != "" { createStackInput.OnFailure = aws.String(stackDetails.OnFailure) } if len(stackDetails.Parameters) > 0 { createStackInput.Parameters = BuilCloudFormationParameters(stackDetails.Parameters) } if len(stackDetails.ResourceTypes) > 0 { createStackInput.ResourceTypes = aws.StringSlice(stackDetails.ResourceTypes) } if stackDetails.StackPolicyURL != "" { createStackInput.StackPolicyURL = aws.String(stackDetails.StackPolicyURL) } if len(stackDetails.Tags) > 0 { createStackInput.Tags = BuilCloudFormationTags(stackDetails.Tags) } if stackDetails.TimeoutInMinutes > 0 { createStackInput.TimeoutInMinutes = aws.Int64(stackDetails.TimeoutInMinutes) } return createStackInput }
// VolumeAttach attaches a volume and provides a token clients can use // to validate that device has appeared locally. func (d *driver) VolumeAttach( ctx types.Context, volumeID string, opts *types.VolumeAttachOpts) (*types.Volume, string, error) { svc := mustSession(ctx) vol, err := d.VolumeInspect(ctx, volumeID, &types.VolumeInspectOpts{Attachments: types.VolAttReqTrue}) if err != nil { return nil, "", err } iid := context.MustInstanceID(ctx) var ma *types.VolumeAttachment for _, att := range vol.Attachments { if att.InstanceID.ID == iid.ID { ma = att break } } // No mount targets were found if ma == nil { secGrpIDs := d.secGroups if v, ok := iid.Fields[efs.InstanceIDFieldSecurityGroups]; ok { iSecGrpIDs := strings.Split(v, ";") ctx.WithField("secGrpIDs", iSecGrpIDs).Debug( "using instance security group IDs") secGrpIDs = iSecGrpIDs } if len(secGrpIDs) == 0 { return nil, "", errInvalidSecGroups } request := &awsefs.CreateMountTargetInput{ FileSystemId: aws.String(vol.ID), SubnetId: aws.String(iid.ID), SecurityGroups: aws.StringSlice(secGrpIDs), } // TODO(mhrabovcin): Should we block here until MountTarget is in // "available" LifeCycleState? Otherwise mount could fail until creation // is completed. _, err = svc.CreateMountTarget(request) // Failed to create mount target if err != nil { return nil, "", err } } return vol, "", err }
func (m *Metric) PushMetrics(acc plugins.Accumulator) error { sess := session.New(&aws.Config{Region: aws.String(m.Region)}) svc := cloudwatch.New(sess) params := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), Namespace: aws.String(m.Namespace), Period: aws.Int64(m.Period), StartTime: aws.Time(time.Now().Add(-time.Duration(m.Duration) * time.Second)), Statistics: aws.StringSlice(m.Statistics), Dimensions: convertDimensions(m.Dimensions), // Unit: aws.String(m.Unit), } printDebug(params) for _, metricName := range m.MetricNames { params.MetricName = aws.String(metricName) printDebug("requesting metric: ", metricName) resp, err := svc.GetMetricStatistics(params) if err != nil { fmt.Println(err.Error()) return err } printDebug(resp) for _, d := range resp.Datapoints { if d.Average != nil { label := strings.Join([]string{m.Prefix, *resp.Label, "average"}, "_") acc.Add(label, *d.Average, copyDims(m.Dimensions), *d.Timestamp) } if d.Maximum != nil { label := strings.Join([]string{m.Prefix, *resp.Label, "maximum"}, "_") acc.Add(label, *d.Maximum, copyDims(m.Dimensions), *d.Timestamp) } if d.Minimum != nil { label := strings.Join([]string{m.Prefix, *resp.Label, "minimum"}, "_") acc.Add(label, *d.Minimum, copyDims(m.Dimensions), *d.Timestamp) } if d.Sum != nil { label := strings.Join([]string{m.Prefix, *resp.Label, "sum"}, "_") acc.Add(label, *d.Sum, copyDims(m.Dimensions), *d.Timestamp) } } } return nil }
func TestCloudFrontStructure_expandGeoRestriction_whitelist(t *testing.T) { data := geoRestrictionWhitelistConf() gr := expandGeoRestriction(data) if *gr.RestrictionType != "whitelist" { t.Fatalf("Expected RestrictionType to be whitelist, got %v", *gr.RestrictionType) } if *gr.Quantity != 3 { t.Fatalf("Expected Quantity to be 3, got %v", *gr.Quantity) } if reflect.DeepEqual(gr.Items, aws.StringSlice([]string{"CA", "GB", "US"})) != true { t.Fatalf("Expected Items be [CA, GB, US], got %v", gr.Items) } }
func findResourceVPCEndpoint(conn *ec2.EC2, id string) (*ec2.VpcEndpoint, error) { input := &ec2.DescribeVpcEndpointsInput{ VpcEndpointIds: aws.StringSlice([]string{id}), } log.Printf("[DEBUG] Reading VPC Endpoint: %q", id) output, err := conn.DescribeVpcEndpoints(input) if err != nil { return nil, err } return output.VpcEndpoints[0], nil }
// DeployConfigAndCode updates config and updates function code. func (f *Function) DeployConfigAndCode(zip []byte) error { f.Log.Info("updating config") _, err := f.Service.UpdateFunctionConfiguration(&lambda.UpdateFunctionConfigurationInput{ FunctionName: &f.FunctionName, MemorySize: &f.Memory, Timeout: &f.Timeout, Description: &f.Description, Role: &f.Role, Handler: &f.Handler, VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, }) if err != nil { return err } return f.Update(zip) }
// UpdateStack creates the cloudformation stack by invoking the sdk's UpdateStack API. func (c *cloudformationClient) UpdateStack(stackName string, params *CfnStackParams) (string, error) { output, err := c.client.UpdateStack(&cloudformation.UpdateStackInput{ Capabilities: aws.StringSlice([]string{cloudformation.CapabilityCapabilityIam}), StackName: aws.String(stackName), Parameters: params.Get(), UsePreviousTemplate: aws.Bool(true), }) if err != nil { return "", err } log.WithFields(log.Fields{"stackId": output.StackId}).Debug("Cloudformation update stack call succeeded") return aws.StringValue(output.StackId), nil }
// Create the function with the given `zip`. func (f *Function) Create(zip []byte) error { f.Log.Info("creating function") created, err := f.Service.CreateFunction(&lambda.CreateFunctionInput{ FunctionName: &f.FunctionName, Description: &f.Description, MemorySize: &f.Memory, Timeout: &f.Timeout, Runtime: &f.Runtime, Handler: &f.Handler, Role: &f.Role, Publish: aws.Bool(true), Code: &lambda.FunctionCode{ ZipFile: zip, }, VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, }) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *created.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *created.Version, "name": f.FunctionName, }).Info("function created") return nil }
// GetAttributes returns a list of queue attributes. All attributes are // returned if not provided. func (this *NiceSQS) GetAttributes(attrs []string) (map[string]string, error) { a := &sqs.GetQueueAttributesInput{ QueueUrl: this.queueUrl, } if len(attrs) > 0 { a.AttributeNames = aws.StringSlice(attrs) } else { a.AttributeNames = []*string{aws.String("All")} } resp, err := this.Sqs.GetQueueAttributes(a) if err != nil { return nil, err } return aws.StringValueMap(resp.Attributes), nil }
func resourceAwsLightsailInstanceCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).lightsailconn iName := d.Get("name").(string) req := lightsail.CreateInstancesInput{ AvailabilityZone: aws.String(d.Get("availability_zone").(string)), BlueprintId: aws.String(d.Get("blueprint_id").(string)), BundleId: aws.String(d.Get("bundle_id").(string)), InstanceNames: aws.StringSlice([]string{iName}), } if v, ok := d.GetOk("key_pair_name"); ok { req.KeyPairName = aws.String(v.(string)) } if v, ok := d.GetOk("user_data"); ok { req.UserData = aws.String(v.(string)) } resp, err := conn.CreateInstances(&req) if err != nil { return err } if len(resp.Operations) == 0 { return fmt.Errorf("[ERR] No operations found for CreateInstance request") } op := resp.Operations[0] d.SetId(d.Get("name").(string)) stateConf := &resource.StateChangeConf{ Pending: []string{"Started"}, Target: []string{"Completed", "Succeeded"}, Refresh: resourceAwsLightsailOperationRefreshFunc(op.Id, meta), Timeout: 10 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { // We don't return an error here because the Create call succeded log.Printf("[ERR] Error waiting for instance (%s) to become ready: %s", d.Id(), err) } return resourceAwsLightsailInstanceRead(d, meta) }
func (r *hostsList) Run() error { // Create an EC2 service object in the "eu-west-1" region // Note that you can also configure your region globally by // exporting the AWS_REGION environment variable svc := ec2.New(session.New(), &aws.Config{Region: aws.String("eu-west-1")}) // we are only concerned with running instances filterChain := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ &ec2.Filter{ Name: aws.String("instance-state-name"), Values: aws.StringSlice([]string{"running"}), }, //&ec2.Filter{ // Name: aws.String("tag:Env"), // Values: aws.StringSlice([]string{"staging"}), //}, }, } // filter by environment //Query string `cli:"arg"` // Call the DescribeInstances Operation resp, err := svc.DescribeInstances(filterChain) if err != nil { panic(err) } // id launch_time ami name ip type revision role t := gocli.NewTable() t.Header("id", "launch_time", "ami", "name", "ip", "public_ip", "type", "revision", "role") instances, _ := awsutil.ValuesAtPath(resp, "Reservations[].Instances[]") for _, instance := range instances { h := instance.(*ec2.Instance) tags := aggregateTags(h.Tags) // TODO - calculate role from tags role := gocli.Red("NONE") t.Add(h.InstanceId, h.LaunchTime.Format("2006-01-02T15:04"), h.ImageId, tags["Name"], h.PrivateIpAddress, h.PublicIpAddress, h.InstanceType, "aabbcc", role) } t.SortBy = 1 sort.Sort(sort.Reverse(t)) fmt.Println(t) return nil }
func (c *ENIClient) DescribeInstancesByIDs(instanceIDs []string) ([]*model.Instance, error) { p := &ec2.DescribeInstancesInput{ InstanceIds: aws.StringSlice(instanceIDs), } resp, err := c.svc.DescribeInstances(p) if err != nil { return nil, err } instances := make([]*model.Instance, 0) for _, r := range resp.Reservations { for _, i := range r.Instances { instances = append(instances, model.NewInstance(i)) } } return instances, nil }
func deleteDocumentPermissions(d *schema.ResourceData, meta interface{}) error { ssmconn := meta.(*AWSClient).ssmconn log.Printf("[INFO] Removing permissions from document: %s", d.Id()) permInput := &ssm.ModifyDocumentPermissionInput{ Name: aws.String(d.Get("name").(string)), PermissionType: aws.String("Share"), AccountIdsToRemove: aws.StringSlice(strings.Split("all", ",")), } _, err := ssmconn.ModifyDocumentPermission(permInput) if err != nil { return errwrap.Wrapf("[ERROR] Error removing permissions for SSM document: {{err}}", err) } return nil }