github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/aws/resource_aws_cloudwatch_log_group.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/hashicorp/terraform/helper/schema"
     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/cloudwatchlogs"
    12  	"github.com/hashicorp/errwrap"
    13  )
    14  
    15  func resourceAwsCloudWatchLogGroup() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceAwsCloudWatchLogGroupCreate,
    18  		Read:   resourceAwsCloudWatchLogGroupRead,
    19  		Update: resourceAwsCloudWatchLogGroupUpdate,
    20  		Delete: resourceAwsCloudWatchLogGroupDelete,
    21  		Importer: &schema.ResourceImporter{
    22  			State: schema.ImportStatePassthrough,
    23  		},
    24  
    25  		Schema: map[string]*schema.Schema{
    26  			"name": {
    27  				Type:         schema.TypeString,
    28  				Required:     true,
    29  				ForceNew:     true,
    30  				ValidateFunc: validateLogGroupName,
    31  			},
    32  
    33  			"retention_in_days": {
    34  				Type:     schema.TypeInt,
    35  				Optional: true,
    36  				Default:  0,
    37  			},
    38  
    39  			"arn": {
    40  				Type:     schema.TypeString,
    41  				Computed: true,
    42  			},
    43  
    44  			"tags": tagsSchema(),
    45  		},
    46  	}
    47  }
    48  
    49  func resourceAwsCloudWatchLogGroupCreate(d *schema.ResourceData, meta interface{}) error {
    50  	conn := meta.(*AWSClient).cloudwatchlogsconn
    51  
    52  	log.Printf("[DEBUG] Creating CloudWatch Log Group: %s", d.Get("name").(string))
    53  
    54  	_, err := conn.CreateLogGroup(&cloudwatchlogs.CreateLogGroupInput{
    55  		LogGroupName: aws.String(d.Get("name").(string)),
    56  	})
    57  	if err != nil {
    58  		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ResourceAlreadyExistsException" {
    59  			return fmt.Errorf("Creating CloudWatch Log Group failed: %s:  The CloudWatch Log Group '%s' already exists.", err, d.Get("name").(string))
    60  		}
    61  		return fmt.Errorf("Creating CloudWatch Log Group failed: %s '%s'", err, d.Get("name"))
    62  	}
    63  
    64  	d.SetId(d.Get("name").(string))
    65  
    66  	log.Println("[INFO] CloudWatch Log Group created")
    67  
    68  	return resourceAwsCloudWatchLogGroupUpdate(d, meta)
    69  }
    70  
    71  func resourceAwsCloudWatchLogGroupRead(d *schema.ResourceData, meta interface{}) error {
    72  	conn := meta.(*AWSClient).cloudwatchlogsconn
    73  	log.Printf("[DEBUG] Reading CloudWatch Log Group: %q", d.Get("name").(string))
    74  	lg, exists, err := lookupCloudWatchLogGroup(conn, d.Id(), nil)
    75  	if err != nil {
    76  		return err
    77  	}
    78  
    79  	if !exists {
    80  		log.Printf("[DEBUG] CloudWatch Group %q Not Found", d.Id())
    81  		d.SetId("")
    82  		return nil
    83  	}
    84  
    85  	log.Printf("[DEBUG] Found Log Group: %#v", *lg)
    86  
    87  	d.Set("arn", lg.Arn)
    88  	d.Set("name", lg.LogGroupName)
    89  
    90  	if lg.RetentionInDays != nil {
    91  		d.Set("retention_in_days", lg.RetentionInDays)
    92  	}
    93  
    94  	tags, err := flattenCloudWatchTags(d, conn)
    95  	if err != nil {
    96  		return err
    97  	}
    98  	d.Set("tags", tags)
    99  
   100  	return nil
   101  }
   102  
   103  func lookupCloudWatchLogGroup(conn *cloudwatchlogs.CloudWatchLogs,
   104  	name string, nextToken *string) (*cloudwatchlogs.LogGroup, bool, error) {
   105  	input := &cloudwatchlogs.DescribeLogGroupsInput{
   106  		LogGroupNamePrefix: aws.String(name),
   107  		NextToken:          nextToken,
   108  	}
   109  	resp, err := conn.DescribeLogGroups(input)
   110  	if err != nil {
   111  		return nil, true, err
   112  	}
   113  
   114  	for _, lg := range resp.LogGroups {
   115  		if *lg.LogGroupName == name {
   116  			return lg, true, nil
   117  		}
   118  	}
   119  
   120  	if resp.NextToken != nil {
   121  		return lookupCloudWatchLogGroup(conn, name, resp.NextToken)
   122  	}
   123  
   124  	return nil, false, nil
   125  }
   126  
   127  func resourceAwsCloudWatchLogGroupUpdate(d *schema.ResourceData, meta interface{}) error {
   128  	conn := meta.(*AWSClient).cloudwatchlogsconn
   129  
   130  	name := d.Get("name").(string)
   131  	log.Printf("[DEBUG] Updating CloudWatch Log Group: %q", name)
   132  
   133  	if d.HasChange("retention_in_days") {
   134  		var err error
   135  
   136  		if v, ok := d.GetOk("retention_in_days"); ok {
   137  			input := cloudwatchlogs.PutRetentionPolicyInput{
   138  				LogGroupName:    aws.String(name),
   139  				RetentionInDays: aws.Int64(int64(v.(int))),
   140  			}
   141  			log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", name, input)
   142  			_, err = conn.PutRetentionPolicy(&input)
   143  		} else {
   144  			log.Printf("[DEBUG] Deleting retention for CloudWatch Log Group: %q", name)
   145  			_, err = conn.DeleteRetentionPolicy(&cloudwatchlogs.DeleteRetentionPolicyInput{
   146  				LogGroupName: aws.String(name),
   147  			})
   148  		}
   149  
   150  		if err != nil {
   151  			return err
   152  		}
   153  	}
   154  
   155  	if d.HasChange("tags") {
   156  		oraw, nraw := d.GetChange("tags")
   157  		o := oraw.(map[string]interface{})
   158  		n := nraw.(map[string]interface{})
   159  		create, remove := diffCloudWatchTags(o, n)
   160  
   161  		if len(remove) > 0 {
   162  			log.Printf("[DEBUG] Removing tags from %s", name)
   163  			_, err := conn.UntagLogGroup(&cloudwatchlogs.UntagLogGroupInput{
   164  				LogGroupName: aws.String(name),
   165  				Tags:         remove,
   166  			})
   167  			if err != nil {
   168  				return err
   169  			}
   170  		}
   171  
   172  		if len(create) > 0 {
   173  			log.Printf("[DEBUG] Creating tags on %s", name)
   174  			_, err := conn.TagLogGroup(&cloudwatchlogs.TagLogGroupInput{
   175  				LogGroupName: aws.String(name),
   176  				Tags:         create,
   177  			})
   178  			if err != nil {
   179  				return err
   180  			}
   181  		}
   182  	}
   183  
   184  	return resourceAwsCloudWatchLogGroupRead(d, meta)
   185  }
   186  
   187  func diffCloudWatchTags(oldTags map[string]interface{}, newTags map[string]interface{}) (map[string]*string, []*string) {
   188  	create := make(map[string]*string)
   189  	for k, v := range newTags {
   190  		create[k] = aws.String(v.(string))
   191  	}
   192  
   193  	var remove []*string
   194  	for _, t := range oldTags {
   195  		old, ok := create[t.(string)]
   196  		if !ok || *old != t.(string) {
   197  			remove = append(remove, aws.String(t.(string)))
   198  		}
   199  	}
   200  
   201  	return create, remove
   202  }
   203  
   204  func resourceAwsCloudWatchLogGroupDelete(d *schema.ResourceData, meta interface{}) error {
   205  	conn := meta.(*AWSClient).cloudwatchlogsconn
   206  	log.Printf("[INFO] Deleting CloudWatch Log Group: %s", d.Id())
   207  	_, err := conn.DeleteLogGroup(&cloudwatchlogs.DeleteLogGroupInput{
   208  		LogGroupName: aws.String(d.Get("name").(string)),
   209  	})
   210  	if err != nil {
   211  		return fmt.Errorf("Error deleting CloudWatch Log Group: %s", err)
   212  	}
   213  	log.Println("[INFO] CloudWatch Log Group deleted")
   214  
   215  	d.SetId("")
   216  
   217  	return nil
   218  }
   219  
   220  func flattenCloudWatchTags(d *schema.ResourceData, conn *cloudwatchlogs.CloudWatchLogs) (map[string]interface{}, error) {
   221  	tagsOutput, err := conn.ListTagsLogGroup(&cloudwatchlogs.ListTagsLogGroupInput{
   222  		LogGroupName: aws.String(d.Get("name").(string)),
   223  	})
   224  	if err != nil {
   225  		return nil, errwrap.Wrapf("Error Getting CloudWatch Logs Tag List: {{err}}", err)
   226  	}
   227  	if tagsOutput != nil {
   228  		output := make(map[string]interface{}, len(tagsOutput.Tags))
   229  
   230  		for i, v := range tagsOutput.Tags {
   231  			output[i] = *v
   232  		}
   233  
   234  		return output, nil
   235  	}
   236  
   237  	return make(map[string]interface{}), nil
   238  }