github.com/koding/terraform@v0.6.4-0.20170608090606-5d7e0339779d/builtin/providers/azurerm/resource_arm_container_registry.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"net/http"
     8  
     9  	"regexp"
    10  
    11  	"github.com/Azure/azure-sdk-for-go/arm/containerregistry"
    12  	"github.com/hashicorp/terraform/helper/hashcode"
    13  	"github.com/hashicorp/terraform/helper/schema"
    14  	"github.com/hashicorp/terraform/helper/validation"
    15  	"github.com/jen20/riviera/azure"
    16  )
    17  
    18  func resourceArmContainerRegistry() *schema.Resource {
    19  	return &schema.Resource{
    20  		Create: resourceArmContainerRegistryCreate,
    21  		Read:   resourceArmContainerRegistryRead,
    22  		Update: resourceArmContainerRegistryUpdate,
    23  		Delete: resourceArmContainerRegistryDelete,
    24  		Importer: &schema.ResourceImporter{
    25  			State: schema.ImportStatePassthrough,
    26  		},
    27  		MigrateState:  resourceAzureRMContainerRegistryMigrateState,
    28  		SchemaVersion: 1,
    29  
    30  		Schema: map[string]*schema.Schema{
    31  			"name": {
    32  				Type:         schema.TypeString,
    33  				Required:     true,
    34  				ForceNew:     true,
    35  				ValidateFunc: validateAzureRMContainerRegistryName,
    36  			},
    37  
    38  			"resource_group_name": {
    39  				Type:     schema.TypeString,
    40  				Required: true,
    41  				ForceNew: true,
    42  			},
    43  
    44  			"location": locationSchema(),
    45  
    46  			"sku": {
    47  				Type:             schema.TypeString,
    48  				Optional:         true,
    49  				ForceNew:         true,
    50  				Default:          string(containerregistry.Basic),
    51  				DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
    52  				ValidateFunc: validation.StringInSlice([]string{
    53  					string(containerregistry.Basic),
    54  				}, true),
    55  			},
    56  
    57  			"admin_enabled": {
    58  				Type:     schema.TypeBool,
    59  				Optional: true,
    60  				Default:  false,
    61  			},
    62  
    63  			"storage_account": {
    64  				Type:     schema.TypeSet,
    65  				Required: true,
    66  				MaxItems: 1,
    67  				Elem: &schema.Resource{
    68  					Schema: map[string]*schema.Schema{
    69  						"name": {
    70  							Type:     schema.TypeString,
    71  							Required: true,
    72  						},
    73  
    74  						"access_key": {
    75  							Type:      schema.TypeString,
    76  							Required:  true,
    77  							Sensitive: true,
    78  						},
    79  					},
    80  				},
    81  			},
    82  
    83  			"login_server": {
    84  				Type:     schema.TypeString,
    85  				Computed: true,
    86  			},
    87  
    88  			"admin_username": {
    89  				Type:     schema.TypeString,
    90  				Computed: true,
    91  			},
    92  
    93  			"admin_password": {
    94  				Type:     schema.TypeString,
    95  				Computed: true,
    96  			},
    97  
    98  			"tags": tagsSchema(),
    99  		},
   100  	}
   101  }
   102  
   103  func resourceArmContainerRegistryCreate(d *schema.ResourceData, meta interface{}) error {
   104  	client := meta.(*ArmClient).containerRegistryClient
   105  	log.Printf("[INFO] preparing arguments for AzureRM Container Registry creation.")
   106  
   107  	resourceGroup := d.Get("resource_group_name").(string)
   108  	name := d.Get("name").(string)
   109  	location := d.Get("location").(string)
   110  	sku := d.Get("sku").(string)
   111  
   112  	adminUserEnabled := d.Get("admin_enabled").(bool)
   113  	tags := d.Get("tags").(map[string]interface{})
   114  
   115  	parameters := containerregistry.RegistryCreateParameters{
   116  		Location: &location,
   117  		Sku: &containerregistry.Sku{
   118  			Name: &sku,
   119  			Tier: containerregistry.SkuTier(sku),
   120  		},
   121  		RegistryPropertiesCreateParameters: &containerregistry.RegistryPropertiesCreateParameters{
   122  			AdminUserEnabled: &adminUserEnabled,
   123  		},
   124  		Tags: expandTags(tags),
   125  	}
   126  
   127  	accounts := d.Get("storage_account").(*schema.Set).List()
   128  	account := accounts[0].(map[string]interface{})
   129  	storageAccountName := account["name"].(string)
   130  	storageAccountAccessKey := account["access_key"].(string)
   131  	parameters.RegistryPropertiesCreateParameters.StorageAccount = &containerregistry.StorageAccountParameters{
   132  		Name:      azure.String(storageAccountName),
   133  		AccessKey: azure.String(storageAccountAccessKey),
   134  	}
   135  
   136  	_, error := client.Create(resourceGroup, name, parameters, make(<-chan struct{}))
   137  	err := <-error
   138  	if err != nil {
   139  		return err
   140  	}
   141  
   142  	read, err := client.Get(resourceGroup, name)
   143  	if err != nil {
   144  		return err
   145  	}
   146  
   147  	if read.ID == nil {
   148  		return fmt.Errorf("Cannot read Container Registry %s (resource group %s) ID", name, resourceGroup)
   149  	}
   150  
   151  	d.SetId(*read.ID)
   152  
   153  	return resourceArmContainerRegistryRead(d, meta)
   154  }
   155  
   156  func resourceArmContainerRegistryUpdate(d *schema.ResourceData, meta interface{}) error {
   157  	client := meta.(*ArmClient).containerRegistryClient
   158  	log.Printf("[INFO] preparing arguments for AzureRM Container Registry update.")
   159  
   160  	resourceGroup := d.Get("resource_group_name").(string)
   161  	name := d.Get("name").(string)
   162  
   163  	accounts := d.Get("storage_account").(*schema.Set).List()
   164  	account := accounts[0].(map[string]interface{})
   165  	storageAccountName := account["name"].(string)
   166  	storageAccountAccessKey := account["access_key"].(string)
   167  
   168  	adminUserEnabled := d.Get("admin_enabled").(bool)
   169  	tags := d.Get("tags").(map[string]interface{})
   170  
   171  	parameters := containerregistry.RegistryUpdateParameters{
   172  		RegistryPropertiesUpdateParameters: &containerregistry.RegistryPropertiesUpdateParameters{
   173  			AdminUserEnabled: &adminUserEnabled,
   174  			StorageAccount: &containerregistry.StorageAccountParameters{
   175  				Name:      azure.String(storageAccountName),
   176  				AccessKey: azure.String(storageAccountAccessKey),
   177  			},
   178  		},
   179  		Tags: expandTags(tags),
   180  	}
   181  
   182  	_, err := client.Update(resourceGroup, name, parameters)
   183  	if err != nil {
   184  		return err
   185  	}
   186  
   187  	read, err := client.Get(resourceGroup, name)
   188  	if err != nil {
   189  		return err
   190  	}
   191  
   192  	if read.ID == nil {
   193  		return fmt.Errorf("Cannot read Container Registry %s (resource group %s) ID", name, resourceGroup)
   194  	}
   195  
   196  	d.SetId(*read.ID)
   197  
   198  	return resourceArmContainerRegistryRead(d, meta)
   199  }
   200  
   201  func resourceArmContainerRegistryRead(d *schema.ResourceData, meta interface{}) error {
   202  	client := meta.(*ArmClient).containerRegistryClient
   203  
   204  	id, err := parseAzureResourceID(d.Id())
   205  	if err != nil {
   206  		return err
   207  	}
   208  	resourceGroup := id.ResourceGroup
   209  	name := id.Path["registries"]
   210  
   211  	resp, err := client.Get(resourceGroup, name)
   212  	if err != nil {
   213  		return fmt.Errorf("Error making Read request on Azure Container Registry %s: %s", name, err)
   214  	}
   215  	if resp.StatusCode == http.StatusNotFound {
   216  		d.SetId("")
   217  		return nil
   218  	}
   219  
   220  	d.Set("name", resp.Name)
   221  	d.Set("resource_group_name", resourceGroup)
   222  	d.Set("location", azureRMNormalizeLocation(*resp.Location))
   223  	d.Set("admin_enabled", resp.AdminUserEnabled)
   224  	d.Set("login_server", resp.LoginServer)
   225  
   226  	if resp.Sku != nil {
   227  		d.Set("sku", string(resp.Sku.Tier))
   228  	}
   229  
   230  	if resp.StorageAccount != nil {
   231  		flattenArmContainerRegistryStorageAccount(d, resp.StorageAccount)
   232  	}
   233  
   234  	if *resp.AdminUserEnabled {
   235  		credsResp, err := client.ListCredentials(resourceGroup, name)
   236  		if err != nil {
   237  			return fmt.Errorf("Error making Read request on Azure Container Registry %s for Credentials: %s", name, err)
   238  		}
   239  
   240  		d.Set("admin_username", credsResp.Username)
   241  		for _, v := range *credsResp.Passwords {
   242  			d.Set("admin_password", v.Value)
   243  			break
   244  		}
   245  	} else {
   246  		d.Set("admin_username", "")
   247  		d.Set("admin_password", "")
   248  	}
   249  
   250  	flattenAndSetTags(d, resp.Tags)
   251  
   252  	return nil
   253  }
   254  
   255  func resourceArmContainerRegistryDelete(d *schema.ResourceData, meta interface{}) error {
   256  	client := meta.(*ArmClient).containerRegistryClient
   257  
   258  	id, err := parseAzureResourceID(d.Id())
   259  	if err != nil {
   260  		return err
   261  	}
   262  	resourceGroup := id.ResourceGroup
   263  	name := id.Path["registries"]
   264  
   265  	resp, err := client.Delete(resourceGroup, name)
   266  
   267  	if resp.StatusCode != http.StatusOK {
   268  		return fmt.Errorf("Error issuing Azure ARM delete request of Container Registry '%s': %s", name, err)
   269  	}
   270  
   271  	return nil
   272  }
   273  
   274  func flattenArmContainerRegistryStorageAccount(d *schema.ResourceData, properties *containerregistry.StorageAccountProperties) {
   275  	storageAccounts := schema.Set{
   276  		F: resourceAzureRMContainerRegistryStorageAccountHash,
   277  	}
   278  
   279  	storageAccount := map[string]interface{}{}
   280  	storageAccount["name"] = properties.Name
   281  	storageAccounts.Add(storageAccount)
   282  
   283  	d.Set("storage_account", &storageAccounts)
   284  }
   285  
   286  func resourceAzureRMContainerRegistryStorageAccountHash(v interface{}) int {
   287  	m := v.(map[string]interface{})
   288  	name := m["name"].(*string)
   289  	return hashcode.String(*name)
   290  }
   291  
   292  func validateAzureRMContainerRegistryName(v interface{}, k string) (ws []string, errors []error) {
   293  	value := v.(string)
   294  	if !regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(value) {
   295  		errors = append(errors, fmt.Errorf(
   296  			"alpha numeric characters only are allowed in %q: %q", k, value))
   297  	}
   298  
   299  	if 5 > len(value) {
   300  		errors = append(errors, fmt.Errorf("%q cannot be less than 5 characters: %q", k, value))
   301  	}
   302  
   303  	if len(value) >= 50 {
   304  		errors = append(errors, fmt.Errorf("%q cannot be longer than 50 characters: %q %d", k, value, len(value)))
   305  	}
   306  
   307  	return
   308  }