github.com/nevins-b/terraform@v0.3.8-0.20170215184714-bbae22007d5a/builtin/providers/google/resource_google_project.go (about)

     1  package google
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  	"strconv"
     9  
    10  	"github.com/hashicorp/terraform/helper/schema"
    11  	"google.golang.org/api/cloudresourcemanager/v1"
    12  	"google.golang.org/api/googleapi"
    13  )
    14  
    15  // resourceGoogleProject returns a *schema.Resource that allows a customer
    16  // to declare a Google Cloud Project resource.
    17  //
    18  // This example shows a project with a policy declared in config:
    19  //
    20  // resource "google_project" "my-project" {
    21  //    project = "a-project-id"
    22  //    policy = "${data.google_iam_policy.admin.policy}"
    23  // }
    24  func resourceGoogleProject() *schema.Resource {
    25  	return &schema.Resource{
    26  		SchemaVersion: 1,
    27  
    28  		Create: resourceGoogleProjectCreate,
    29  		Read:   resourceGoogleProjectRead,
    30  		Update: resourceGoogleProjectUpdate,
    31  		Delete: resourceGoogleProjectDelete,
    32  
    33  		Importer: &schema.ResourceImporter{
    34  			State: schema.ImportStatePassthrough,
    35  		},
    36  		MigrateState: resourceGoogleProjectMigrateState,
    37  
    38  		Schema: map[string]*schema.Schema{
    39  			"id": &schema.Schema{
    40  				Type:       schema.TypeString,
    41  				Optional:   true,
    42  				Computed:   true,
    43  				Deprecated: "The id field has unexpected behaviour and probably doesn't do what you expect. See https://www.terraform.io/docs/providers/google/r/google_project.html#id-field for more information. Please use project_id instead; future versions of Terraform will remove the id field.",
    44  			},
    45  			"project_id": &schema.Schema{
    46  				Type:     schema.TypeString,
    47  				Optional: true,
    48  				ForceNew: true,
    49  				DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
    50  					// This suppresses the diff if project_id is not set
    51  					if new == "" {
    52  						return true
    53  					}
    54  					return false
    55  				},
    56  			},
    57  			"skip_delete": &schema.Schema{
    58  				Type:     schema.TypeBool,
    59  				Optional: true,
    60  				Computed: true,
    61  			},
    62  			"name": &schema.Schema{
    63  				Type:     schema.TypeString,
    64  				Optional: true,
    65  				Computed: true,
    66  			},
    67  			"org_id": &schema.Schema{
    68  				Type:     schema.TypeString,
    69  				Optional: true,
    70  				Computed: true,
    71  				ForceNew: true,
    72  			},
    73  			"policy_data": &schema.Schema{
    74  				Type:             schema.TypeString,
    75  				Optional:         true,
    76  				Computed:         true,
    77  				Deprecated:       "Use the 'google_project_iam_policy' resource to define policies for a Google Project",
    78  				DiffSuppressFunc: jsonPolicyDiffSuppress,
    79  			},
    80  			"policy_etag": &schema.Schema{
    81  				Type:       schema.TypeString,
    82  				Computed:   true,
    83  				Deprecated: "Use the the 'google_project_iam_policy' resource to define policies for a Google Project",
    84  			},
    85  			"number": &schema.Schema{
    86  				Type:     schema.TypeString,
    87  				Computed: true,
    88  			},
    89  		},
    90  	}
    91  }
    92  
    93  func resourceGoogleProjectCreate(d *schema.ResourceData, meta interface{}) error {
    94  	config := meta.(*Config)
    95  
    96  	var pid string
    97  	var err error
    98  	pid = d.Get("project_id").(string)
    99  	if pid == "" {
   100  		pid, err = getProject(d, config)
   101  		if err != nil {
   102  			return fmt.Errorf("Error getting project ID: %v", err)
   103  		}
   104  		if pid == "" {
   105  			return fmt.Errorf("'project_id' must be set in the config")
   106  		}
   107  	}
   108  
   109  	// we need to check if name and org_id are set, and throw an error if they aren't
   110  	// we can't just set these as required on the object, however, as that would break
   111  	// all configs that used previous iterations of the resource.
   112  	// TODO(paddy): remove this for 0.9 and set these attributes as required.
   113  	name, org_id := d.Get("name").(string), d.Get("org_id").(string)
   114  	if name == "" {
   115  		return fmt.Errorf("`name` must be set in the config if you're creating a project.")
   116  	}
   117  	if org_id == "" {
   118  		return fmt.Errorf("`org_id` must be set in the config if you're creating a project.")
   119  	}
   120  
   121  	log.Printf("[DEBUG]: Creating new project %q", pid)
   122  	project := &cloudresourcemanager.Project{
   123  		ProjectId: pid,
   124  		Name:      d.Get("name").(string),
   125  		Parent: &cloudresourcemanager.ResourceId{
   126  			Id:   d.Get("org_id").(string),
   127  			Type: "organization",
   128  		},
   129  	}
   130  
   131  	op, err := config.clientResourceManager.Projects.Create(project).Do()
   132  	if err != nil {
   133  		return fmt.Errorf("Error creating project %s (%s): %s.", project.ProjectId, project.Name, err)
   134  	}
   135  
   136  	d.SetId(pid)
   137  
   138  	// Wait for the operation to complete
   139  	waitErr := resourceManagerOperationWait(config, op, "project to create")
   140  	if waitErr != nil {
   141  		return waitErr
   142  	}
   143  
   144  	// Apply the IAM policy if it is set
   145  	if pString, ok := d.GetOk("policy_data"); ok {
   146  		// The policy string is just a marshaled cloudresourcemanager.Policy.
   147  		// Unmarshal it to a struct.
   148  		var policy cloudresourcemanager.Policy
   149  		if err := json.Unmarshal([]byte(pString.(string)), &policy); err != nil {
   150  			return err
   151  		}
   152  		log.Printf("[DEBUG] Got policy from config: %#v", policy.Bindings)
   153  
   154  		// Retrieve existing IAM policy from project. This will be merged
   155  		// with the policy defined here.
   156  		p, err := getProjectIamPolicy(pid, config)
   157  		if err != nil {
   158  			return err
   159  		}
   160  		log.Printf("[DEBUG] Got existing bindings from project: %#v", p.Bindings)
   161  
   162  		// Merge the existing policy bindings with those defined in this manifest.
   163  		p.Bindings = mergeBindings(append(p.Bindings, policy.Bindings...))
   164  
   165  		// Apply the merged policy
   166  		log.Printf("[DEBUG] Setting new policy for project: %#v", p)
   167  		_, err = config.clientResourceManager.Projects.SetIamPolicy(pid,
   168  			&cloudresourcemanager.SetIamPolicyRequest{Policy: p}).Do()
   169  
   170  		if err != nil {
   171  			return fmt.Errorf("Error applying IAM policy for project %q: %s", pid, err)
   172  		}
   173  	}
   174  
   175  	return resourceGoogleProjectRead(d, meta)
   176  }
   177  
   178  func resourceGoogleProjectRead(d *schema.ResourceData, meta interface{}) error {
   179  	config := meta.(*Config)
   180  	pid := d.Id()
   181  
   182  	// Read the project
   183  	p, err := config.clientResourceManager.Projects.Get(pid).Do()
   184  	if err != nil {
   185  		if v, ok := err.(*googleapi.Error); ok && v.Code == http.StatusNotFound {
   186  			return fmt.Errorf("Project %q does not exist.", pid)
   187  		}
   188  		return fmt.Errorf("Error checking project %q: %s", pid, err)
   189  	}
   190  
   191  	d.Set("project_id", pid)
   192  	d.Set("number", strconv.FormatInt(int64(p.ProjectNumber), 10))
   193  	d.Set("name", p.Name)
   194  
   195  	if p.Parent != nil {
   196  		d.Set("org_id", p.Parent.Id)
   197  	}
   198  
   199  	return nil
   200  }
   201  
   202  func resourceGoogleProjectUpdate(d *schema.ResourceData, meta interface{}) error {
   203  	config := meta.(*Config)
   204  	pid := d.Id()
   205  
   206  	// Read the project
   207  	// we need the project even though refresh has already been called
   208  	// because the API doesn't support patch, so we need the actual object
   209  	p, err := config.clientResourceManager.Projects.Get(pid).Do()
   210  	if err != nil {
   211  		if v, ok := err.(*googleapi.Error); ok && v.Code == http.StatusNotFound {
   212  			return fmt.Errorf("Project %q does not exist.", pid)
   213  		}
   214  		return fmt.Errorf("Error checking project %q: %s", pid, err)
   215  	}
   216  
   217  	// Project name has changed
   218  	if ok := d.HasChange("name"); ok {
   219  		p.Name = d.Get("name").(string)
   220  		// Do update on project
   221  		p, err = config.clientResourceManager.Projects.Update(p.ProjectId, p).Do()
   222  		if err != nil {
   223  			return fmt.Errorf("Error updating project %q: %s", p.Name, err)
   224  		}
   225  	}
   226  
   227  	return updateProjectIamPolicy(d, config, pid)
   228  }
   229  
   230  func resourceGoogleProjectDelete(d *schema.ResourceData, meta interface{}) error {
   231  	config := meta.(*Config)
   232  	// Only delete projects if skip_delete isn't set
   233  	if !d.Get("skip_delete").(bool) {
   234  		pid := d.Id()
   235  		_, err := config.clientResourceManager.Projects.Delete(pid).Do()
   236  		if err != nil {
   237  			return fmt.Errorf("Error deleting project %q: %s", pid, err)
   238  		}
   239  	}
   240  	d.SetId("")
   241  	return nil
   242  }
   243  
   244  func updateProjectIamPolicy(d *schema.ResourceData, config *Config, pid string) error {
   245  	// Policy has changed
   246  	if ok := d.HasChange("policy_data"); ok {
   247  		// The policy string is just a marshaled cloudresourcemanager.Policy.
   248  		// Unmarshal it to a struct that contains the old and new policies
   249  		oldP, newP := d.GetChange("policy_data")
   250  		oldPString := oldP.(string)
   251  		newPString := newP.(string)
   252  
   253  		// JSON Unmarshaling would fail
   254  		if oldPString == "" {
   255  			oldPString = "{}"
   256  		}
   257  		if newPString == "" {
   258  			newPString = "{}"
   259  		}
   260  
   261  		log.Printf("[DEBUG]: Old policy: %q\nNew policy: %q", oldPString, newPString)
   262  
   263  		var oldPolicy, newPolicy cloudresourcemanager.Policy
   264  		if err := json.Unmarshal([]byte(newPString), &newPolicy); err != nil {
   265  			return err
   266  		}
   267  		if err := json.Unmarshal([]byte(oldPString), &oldPolicy); err != nil {
   268  			return err
   269  		}
   270  
   271  		// Find any Roles and Members that were removed (i.e., those that are present
   272  		// in the old but absent in the new
   273  		oldMap := rolesToMembersMap(oldPolicy.Bindings)
   274  		newMap := rolesToMembersMap(newPolicy.Bindings)
   275  		deleted := make(map[string]map[string]bool)
   276  
   277  		// Get each role and its associated members in the old state
   278  		for role, members := range oldMap {
   279  			// Initialize map for role
   280  			if _, ok := deleted[role]; !ok {
   281  				deleted[role] = make(map[string]bool)
   282  			}
   283  			// The role exists in the new state
   284  			if _, ok := newMap[role]; ok {
   285  				// Check each memeber
   286  				for member, _ := range members {
   287  					// Member does not exist in new state, so it was deleted
   288  					if _, ok = newMap[role][member]; !ok {
   289  						deleted[role][member] = true
   290  					}
   291  				}
   292  			} else {
   293  				// This indicates an entire role was deleted. Mark all members
   294  				// for delete.
   295  				for member, _ := range members {
   296  					deleted[role][member] = true
   297  				}
   298  			}
   299  		}
   300  		log.Printf("[DEBUG] Roles and Members to be deleted: %#v", deleted)
   301  
   302  		// Retrieve existing IAM policy from project. This will be merged
   303  		// with the policy in the current state
   304  		// TODO(evanbrown): Add an 'authoritative' flag that allows policy
   305  		// in manifest to overwrite existing policy.
   306  		p, err := getProjectIamPolicy(pid, config)
   307  		if err != nil {
   308  			return err
   309  		}
   310  		log.Printf("[DEBUG] Got existing bindings from project: %#v", p.Bindings)
   311  
   312  		// Merge existing policy with policy in the current state
   313  		log.Printf("[DEBUG] Merging new bindings from project: %#v", newPolicy.Bindings)
   314  		mergedBindings := mergeBindings(append(p.Bindings, newPolicy.Bindings...))
   315  
   316  		// Remove any roles and members that were explicitly deleted
   317  		mergedBindingsMap := rolesToMembersMap(mergedBindings)
   318  		for role, members := range deleted {
   319  			for member, _ := range members {
   320  				delete(mergedBindingsMap[role], member)
   321  			}
   322  		}
   323  
   324  		p.Bindings = rolesToMembersBinding(mergedBindingsMap)
   325  		dump, _ := json.MarshalIndent(p.Bindings, " ", "  ")
   326  		log.Printf("[DEBUG] Setting new policy for project: %#v:\n%s", p, string(dump))
   327  
   328  		_, err = config.clientResourceManager.Projects.SetIamPolicy(pid,
   329  			&cloudresourcemanager.SetIamPolicyRequest{Policy: p}).Do()
   330  
   331  		if err != nil {
   332  			return fmt.Errorf("Error applying IAM policy for project %q: %s", pid, err)
   333  		}
   334  	}
   335  	return nil
   336  }