github.com/xsb/terraform@v0.6.13-0.20160314145438-fe415c2f09d7/builtin/providers/aws/resource_aws_lambda_function.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/aws/aws-sdk-go/aws"
    10  	"github.com/aws/aws-sdk-go/aws/awserr"
    11  	"github.com/aws/aws-sdk-go/service/lambda"
    12  	"github.com/mitchellh/go-homedir"
    13  
    14  	"errors"
    15  
    16  	"github.com/hashicorp/terraform/helper/resource"
    17  	"github.com/hashicorp/terraform/helper/schema"
    18  )
    19  
    20  func resourceAwsLambdaFunction() *schema.Resource {
    21  	return &schema.Resource{
    22  		Create: resourceAwsLambdaFunctionCreate,
    23  		Read:   resourceAwsLambdaFunctionRead,
    24  		Update: resourceAwsLambdaFunctionUpdate,
    25  		Delete: resourceAwsLambdaFunctionDelete,
    26  
    27  		Schema: map[string]*schema.Schema{
    28  			"filename": &schema.Schema{
    29  				Type:          schema.TypeString,
    30  				Optional:      true,
    31  				ConflictsWith: []string{"s3_bucket", "s3_key", "s3_object_version"},
    32  			},
    33  			"s3_bucket": &schema.Schema{
    34  				Type:          schema.TypeString,
    35  				Optional:      true,
    36  				ConflictsWith: []string{"filename"},
    37  			},
    38  			"s3_key": &schema.Schema{
    39  				Type:          schema.TypeString,
    40  				Optional:      true,
    41  				ConflictsWith: []string{"filename"},
    42  			},
    43  			"s3_object_version": &schema.Schema{
    44  				Type:          schema.TypeString,
    45  				Optional:      true,
    46  				ConflictsWith: []string{"filename"},
    47  			},
    48  			"description": &schema.Schema{
    49  				Type:     schema.TypeString,
    50  				Optional: true,
    51  			},
    52  			"function_name": &schema.Schema{
    53  				Type:     schema.TypeString,
    54  				Required: true,
    55  				ForceNew: true,
    56  			},
    57  			"handler": &schema.Schema{
    58  				Type:     schema.TypeString,
    59  				Required: true,
    60  			},
    61  			"memory_size": &schema.Schema{
    62  				Type:     schema.TypeInt,
    63  				Optional: true,
    64  				Default:  128,
    65  			},
    66  			"role": &schema.Schema{
    67  				Type:     schema.TypeString,
    68  				Required: true,
    69  			},
    70  			"runtime": &schema.Schema{
    71  				Type:     schema.TypeString,
    72  				Optional: true,
    73  				ForceNew: true,
    74  				Default:  "nodejs",
    75  			},
    76  			"timeout": &schema.Schema{
    77  				Type:     schema.TypeInt,
    78  				Optional: true,
    79  				Default:  3,
    80  			},
    81  			"vpc_config": &schema.Schema{
    82  				Type:     schema.TypeList,
    83  				Optional: true,
    84  				ForceNew: true,
    85  				Elem: &schema.Resource{
    86  					Schema: map[string]*schema.Schema{
    87  						"subnet_ids": &schema.Schema{
    88  							Type:     schema.TypeSet,
    89  							Required: true,
    90  							ForceNew: true,
    91  							Elem:     &schema.Schema{Type: schema.TypeString},
    92  							Set:      schema.HashString,
    93  						},
    94  						"security_group_ids": &schema.Schema{
    95  							Type:     schema.TypeSet,
    96  							Required: true,
    97  							ForceNew: true,
    98  							Elem:     &schema.Schema{Type: schema.TypeString},
    99  							Set:      schema.HashString,
   100  						},
   101  					},
   102  				},
   103  			},
   104  			"arn": &schema.Schema{
   105  				Type:     schema.TypeString,
   106  				Computed: true,
   107  			},
   108  			"last_modified": &schema.Schema{
   109  				Type:     schema.TypeString,
   110  				Computed: true,
   111  			},
   112  			"source_code_hash": &schema.Schema{
   113  				Type:     schema.TypeString,
   114  				Optional: true,
   115  				Computed: true,
   116  			},
   117  		},
   118  	}
   119  }
   120  
   121  // resourceAwsLambdaFunction maps to:
   122  // CreateFunction in the API / SDK
   123  func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error {
   124  	conn := meta.(*AWSClient).lambdaconn
   125  
   126  	functionName := d.Get("function_name").(string)
   127  	iamRole := d.Get("role").(string)
   128  
   129  	log.Printf("[DEBUG] Creating Lambda Function %s with role %s", functionName, iamRole)
   130  
   131  	var functionCode *lambda.FunctionCode
   132  	if v, ok := d.GetOk("filename"); ok {
   133  		file, err := loadFileContent(v.(string))
   134  		if err != nil {
   135  			return fmt.Errorf("Unable to load %q: %s", v.(string), err)
   136  		}
   137  		functionCode = &lambda.FunctionCode{
   138  			ZipFile: file,
   139  		}
   140  	} else {
   141  		s3Bucket, bucketOk := d.GetOk("s3_bucket")
   142  		s3Key, keyOk := d.GetOk("s3_key")
   143  		s3ObjectVersion, versionOk := d.GetOk("s3_object_version")
   144  		if !bucketOk || !keyOk {
   145  			return errors.New("s3_bucket and s3_key must all be set while using S3 code source")
   146  		}
   147  		functionCode = &lambda.FunctionCode{
   148  			S3Bucket: aws.String(s3Bucket.(string)),
   149  			S3Key:    aws.String(s3Key.(string)),
   150  		}
   151  		if versionOk {
   152  			functionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string))
   153  		}
   154  	}
   155  
   156  	params := &lambda.CreateFunctionInput{
   157  		Code:         functionCode,
   158  		Description:  aws.String(d.Get("description").(string)),
   159  		FunctionName: aws.String(functionName),
   160  		Handler:      aws.String(d.Get("handler").(string)),
   161  		MemorySize:   aws.Int64(int64(d.Get("memory_size").(int))),
   162  		Role:         aws.String(iamRole),
   163  		Runtime:      aws.String(d.Get("runtime").(string)),
   164  		Timeout:      aws.Int64(int64(d.Get("timeout").(int))),
   165  	}
   166  
   167  	if v, ok := d.GetOk("vpc_config"); ok {
   168  		config, err := validateVPCConfig(v)
   169  		if err != nil {
   170  			return err
   171  		}
   172  
   173  		var subnetIds []*string
   174  		for _, id := range config["subnet_ids"].(*schema.Set).List() {
   175  			subnetIds = append(subnetIds, aws.String(id.(string)))
   176  		}
   177  
   178  		var securityGroupIds []*string
   179  		for _, id := range config["security_group_ids"].(*schema.Set).List() {
   180  			securityGroupIds = append(securityGroupIds, aws.String(id.(string)))
   181  		}
   182  
   183  		params.VpcConfig = &lambda.VpcConfig{
   184  			SubnetIds:        subnetIds,
   185  			SecurityGroupIds: securityGroupIds,
   186  		}
   187  	}
   188  
   189  	// IAM profiles can take ~10 seconds to propagate in AWS:
   190  	// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
   191  	// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.
   192  	err := resource.Retry(1*time.Minute, func() *resource.RetryError {
   193  		_, err := conn.CreateFunction(params)
   194  		if err != nil {
   195  			log.Printf("[ERROR] Received %q, retrying CreateFunction", err)
   196  			if awserr, ok := err.(awserr.Error); ok {
   197  				if awserr.Code() == "InvalidParameterValueException" {
   198  					log.Printf("[DEBUG] InvalidParameterValueException creating Lambda Function: %s", awserr)
   199  					return resource.RetryableError(awserr)
   200  				}
   201  			}
   202  			log.Printf("[DEBUG] Error creating Lambda Function: %s", err)
   203  			return resource.NonRetryableError(err)
   204  		}
   205  		return nil
   206  	})
   207  	if err != nil {
   208  		return fmt.Errorf("Error creating Lambda function: %s", err)
   209  	}
   210  
   211  	d.SetId(d.Get("function_name").(string))
   212  
   213  	return resourceAwsLambdaFunctionRead(d, meta)
   214  }
   215  
   216  // resourceAwsLambdaFunctionRead maps to:
   217  // GetFunction in the API / SDK
   218  func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) error {
   219  	conn := meta.(*AWSClient).lambdaconn
   220  
   221  	log.Printf("[DEBUG] Fetching Lambda Function: %s", d.Id())
   222  
   223  	params := &lambda.GetFunctionInput{
   224  		FunctionName: aws.String(d.Get("function_name").(string)),
   225  	}
   226  
   227  	getFunctionOutput, err := conn.GetFunction(params)
   228  	if err != nil {
   229  		return err
   230  	}
   231  
   232  	// getFunctionOutput.Code.Location is a pre-signed URL pointing at the zip
   233  	// file that we uploaded when we created the resource. You can use it to
   234  	// download the code from AWS. The other part is
   235  	// getFunctionOutput.Configuration which holds metadata.
   236  
   237  	function := getFunctionOutput.Configuration
   238  	// TODO error checking / handling on the Set() calls.
   239  	d.Set("arn", function.FunctionArn)
   240  	d.Set("description", function.Description)
   241  	d.Set("handler", function.Handler)
   242  	d.Set("memory_size", function.MemorySize)
   243  	d.Set("last_modified", function.LastModified)
   244  	d.Set("role", function.Role)
   245  	d.Set("runtime", function.Runtime)
   246  	d.Set("timeout", function.Timeout)
   247  	if config := flattenLambdaVpcConfigResponse(function.VpcConfig); len(config) > 0 {
   248  		d.Set("vpc_config", config)
   249  	}
   250  	d.Set("source_code_hash", function.CodeSha256)
   251  
   252  	return nil
   253  }
   254  
   255  // resourceAwsLambdaFunction maps to:
   256  // DeleteFunction in the API / SDK
   257  func resourceAwsLambdaFunctionDelete(d *schema.ResourceData, meta interface{}) error {
   258  	conn := meta.(*AWSClient).lambdaconn
   259  
   260  	log.Printf("[INFO] Deleting Lambda Function: %s", d.Id())
   261  
   262  	params := &lambda.DeleteFunctionInput{
   263  		FunctionName: aws.String(d.Get("function_name").(string)),
   264  	}
   265  
   266  	_, err := conn.DeleteFunction(params)
   267  	if err != nil {
   268  		return fmt.Errorf("Error deleting Lambda Function: %s", err)
   269  	}
   270  
   271  	d.SetId("")
   272  
   273  	return nil
   274  }
   275  
   276  // resourceAwsLambdaFunctionUpdate maps to:
   277  // UpdateFunctionCode in the API / SDK
   278  func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) error {
   279  	conn := meta.(*AWSClient).lambdaconn
   280  
   281  	d.Partial(true)
   282  
   283  	codeReq := &lambda.UpdateFunctionCodeInput{
   284  		FunctionName: aws.String(d.Id()),
   285  	}
   286  
   287  	codeUpdate := false
   288  	if v, ok := d.GetOk("filename"); ok && d.HasChange("source_code_hash") {
   289  		file, err := loadFileContent(v.(string))
   290  		if err != nil {
   291  			return fmt.Errorf("Unable to load %q: %s", v.(string), err)
   292  		}
   293  		codeReq.ZipFile = file
   294  		codeUpdate = true
   295  	}
   296  	if d.HasChange("s3_bucket") || d.HasChange("s3_key") || d.HasChange("s3_object_version") {
   297  		codeReq.S3Bucket = aws.String(d.Get("s3_bucket").(string))
   298  		codeReq.S3Key = aws.String(d.Get("s3_key").(string))
   299  		codeReq.S3ObjectVersion = aws.String(d.Get("s3_object_version").(string))
   300  		codeUpdate = true
   301  	}
   302  
   303  	log.Printf("[DEBUG] Send Update Lambda Function Code request: %#v", codeReq)
   304  	if codeUpdate {
   305  		_, err := conn.UpdateFunctionCode(codeReq)
   306  		if err != nil {
   307  			return fmt.Errorf("Error modifying Lambda Function Code %s: %s", d.Id(), err)
   308  		}
   309  
   310  		d.SetPartial("filename")
   311  		d.SetPartial("source_code_hash")
   312  		d.SetPartial("s3_bucket")
   313  		d.SetPartial("s3_key")
   314  		d.SetPartial("s3_object_version")
   315  	}
   316  
   317  	configReq := &lambda.UpdateFunctionConfigurationInput{
   318  		FunctionName: aws.String(d.Id()),
   319  	}
   320  
   321  	configUpdate := false
   322  	if d.HasChange("description") {
   323  		configReq.Description = aws.String(d.Get("description").(string))
   324  		configUpdate = true
   325  	}
   326  	if d.HasChange("handler") {
   327  		configReq.Handler = aws.String(d.Get("handler").(string))
   328  		configUpdate = true
   329  	}
   330  	if d.HasChange("memory_size") {
   331  		configReq.MemorySize = aws.Int64(int64(d.Get("memory_size").(int)))
   332  		configUpdate = true
   333  	}
   334  	if d.HasChange("role") {
   335  		configReq.Role = aws.String(d.Get("role").(string))
   336  		configUpdate = true
   337  	}
   338  	if d.HasChange("timeout") {
   339  		configReq.Timeout = aws.Int64(int64(d.Get("timeout").(int)))
   340  		configUpdate = true
   341  	}
   342  
   343  	log.Printf("[DEBUG] Send Update Lambda Function Configuration request: %#v", configReq)
   344  	if configUpdate {
   345  		_, err := conn.UpdateFunctionConfiguration(configReq)
   346  		if err != nil {
   347  			return fmt.Errorf("Error modifying Lambda Function Configuration %s: %s", d.Id(), err)
   348  		}
   349  		d.SetPartial("description")
   350  		d.SetPartial("handler")
   351  		d.SetPartial("memory_size")
   352  		d.SetPartial("role")
   353  		d.SetPartial("timeout")
   354  	}
   355  	d.Partial(false)
   356  
   357  	return resourceAwsLambdaFunctionRead(d, meta)
   358  }
   359  
   360  // loadFileContent returns contents of a file in a given path
   361  func loadFileContent(v string) ([]byte, error) {
   362  	filename, err := homedir.Expand(v)
   363  	if err != nil {
   364  		return nil, err
   365  	}
   366  	fileContent, err := ioutil.ReadFile(filename)
   367  	if err != nil {
   368  		return nil, err
   369  	}
   370  	return fileContent, nil
   371  }
   372  
   373  func validateVPCConfig(v interface{}) (map[string]interface{}, error) {
   374  	configs := v.([]interface{})
   375  	if len(configs) > 1 {
   376  		return nil, errors.New("Only a single vpc_config block is expected")
   377  	}
   378  
   379  	config, ok := configs[0].(map[string]interface{})
   380  
   381  	if !ok {
   382  		return nil, errors.New("vpc_config is <nil>")
   383  	}
   384  
   385  	if config["subnet_ids"].(*schema.Set).Len() == 0 {
   386  		return nil, errors.New("vpc_config.subnet_ids cannot be empty")
   387  	}
   388  
   389  	if config["security_group_ids"].(*schema.Set).Len() == 0 {
   390  		return nil, errors.New("vpc_config.security_group_ids cannot be empty")
   391  	}
   392  
   393  	return config, nil
   394  }