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