diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 0be6fd57a..9441bb147 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -524,6 +524,14 @@ "Comment": "0.2.1-3-gb1859b1", "Rev": "b1859b199a7171589445bdea9fa8c19362613f80" }, + { + "ImportPath": "github.com/jen20/riviera/azure", + "Rev": "9f0b6c6d5e35780213c3a32976b353faca958699" + }, + { + "ImportPath": "github.com/jen20/riviera/dns", + "Rev": "9f0b6c6d5e35780213c3a32976b353faca958699" + }, { "ImportPath": "github.com/jmespath/go-jmespath", "Comment": "0.2.2-2-gc01cf91", diff --git a/builtin/providers/azurerm/config.go b/builtin/providers/azurerm/config.go index cbc3784b2..bc795ce2a 100644 --- a/builtin/providers/azurerm/config.go +++ b/builtin/providers/azurerm/config.go @@ -16,11 +16,14 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/storage" mainStorage "github.com/Azure/azure-sdk-for-go/storage" "github.com/hashicorp/terraform/terraform" + riviera "github.com/jen20/riviera/azure" ) // ArmClient contains the handles to all the specific Azure Resource Manager // resource classes' respective clients. type ArmClient struct { + rivieraClient *riviera.Client + availSetClient compute.AvailabilitySetsClient usageOpsClient compute.UsageOperationsClient vmExtensionImageClient compute.VirtualMachineExtensionImagesClient @@ -110,6 +113,18 @@ func (c *Config) getArmClient() (*ArmClient, error) { // client declarations: client := ArmClient{} + rivieraClient, err := riviera.NewClient(&riviera.AzureResourceManagerCredentials{ + ClientID: c.ClientID, + ClientSecret: c.ClientSecret, + TenantID: c.TenantID, + SubscriptionID: c.SubscriptionID, + }) + if err != nil { + return nil, fmt.Errorf("Error creating Riviera client: %s", err) + } + + client.rivieraClient = rivieraClient + // NOTE: these declarations should be left separate for clarity should the // clients be wished to be configured with custom Responders/PollingModess etc... asc := compute.NewAvailabilitySetsClient(c.SubscriptionID) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 0f8733ec1..78850dfc5 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -60,6 +60,7 @@ func Provider() terraform.ResourceProvider { "azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_queue": resourceArmStorageQueue(), + "azurerm_dns_zone": resourceArmDnsZone(), }, ConfigureFunc: providerConfigure, } diff --git a/builtin/providers/azurerm/resource_arm_dns_zone.go b/builtin/providers/azurerm/resource_arm_dns_zone.go new file mode 100644 index 000000000..2571e761c --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_dns_zone.go @@ -0,0 +1,126 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/jen20/riviera/dns" +) + +func resourceArmDnsZone() *schema.Resource { + return &schema.Resource{ + Create: resourceArmDnsZoneCreate, + Read: resourceArmDnsZoneRead, + Update: resourceArmDnsZoneCreate, + Delete: resourceArmDnsZoneDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "number_of_record_sets": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "max_number_of_record_sets": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourceArmDnsZoneCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + rivieraClient := client.rivieraClient + + createRequest := rivieraClient.NewRequest() + createRequest.Command = &dns.CreateDNSZone{ + Name: d.Get("name").(string), + Location: "global", + ResourceGroupName: d.Get("resource_group_name").(string), + } + + createResponse, err := createRequest.Execute() + if err != nil { + return fmt.Errorf("Error creating DNS Zone: %s", err) + } + if !createResponse.IsSuccessful() { + return fmt.Errorf("Error creating DNS Zone: %s", createResponse.Error) + } + + readRequest := rivieraClient.NewRequest() + readRequest.Command = &dns.GetDNSZone{ + Name: d.Get("name").(string), + ResourceGroupName: d.Get("resource_group_name").(string), + } + + readResponse, err := readRequest.Execute() + if err != nil { + return fmt.Errorf("Error reading DNS Zone: %s", err) + } + if !readResponse.IsSuccessful() { + return fmt.Errorf("Error reading DNS Zone: %s", readResponse.Error) + } + + resp := readResponse.Parsed.(*dns.GetDNSZoneResponse) + d.SetId(*resp.ID) + + return resourceArmDnsZoneRead(d, meta) +} + +func resourceArmDnsZoneRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + rivieraClient := client.rivieraClient + + readRequest := rivieraClient.NewRequestForURI(d.Id()) + readRequest.Command = &dns.GetDNSZone{} + + readResponse, err := readRequest.Execute() + if err != nil { + return fmt.Errorf("Error reading DNS Zone: %s", err) + } + if !readResponse.IsSuccessful() { + log.Printf("[INFO] Error reading DNS Zone %q - removing from state", d.Id()) + d.SetId("") + return fmt.Errorf("Error reading DNS Zone: %s", readResponse.Error) + } + + resp := readResponse.Parsed.(*dns.GetDNSZoneResponse) + + d.Set("number_of_record_sets", resp.NumberOfRecordSets) + d.Set("max_number_of_record_sets", resp.MaxNumberOfRecordSets) + + return nil +} + +func resourceArmDnsZoneDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + rivieraClient := client.rivieraClient + + deleteRequest := rivieraClient.NewRequestForURI(d.Id()) + deleteRequest.Command = &dns.DeleteDNSZone{} + + deleteResponse, err := deleteRequest.Execute() + if err != nil { + return fmt.Errorf("Error deleting DNS Zone: %s", err) + } + if !deleteResponse.IsSuccessful() { + return fmt.Errorf("Error deleting DNS Zone: %s", deleteResponse.Error) + } + + return nil +} diff --git a/builtin/providers/azurerm/resource_arm_dns_zone_test.go b/builtin/providers/azurerm/resource_arm_dns_zone_test.go new file mode 100644 index 000000000..87b7b8758 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_dns_zone_test.go @@ -0,0 +1,90 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/jen20/riviera/dns" +) + +func TestAccAzureRMDnsZone_basic(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMDnsZone_basic, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMDnsZoneDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMDnsZoneExists("azurerm_dns_zone.test"), + ), + }, + }, + }) +} + +func testCheckAzureRMDnsZoneExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).rivieraClient + + readRequest := conn.NewRequestForURI(rs.Primary.ID) + readRequest.Command = &dns.GetDNSZone{} + + readResponse, err := readRequest.Execute() + if err != nil { + return fmt.Errorf("Bad: GetDNSZone: %s", err) + } + if !readResponse.IsSuccessful() { + return fmt.Errorf("Bad: GetDNSZone: %s", readResponse.Error) + } + + return nil + } +} + +func testCheckAzureRMDnsZoneDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).rivieraClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_dns_zone" { + continue + } + + readRequest := conn.NewRequestForURI(rs.Primary.ID) + readRequest.Command = &dns.GetDNSZone{} + + readResponse, err := readRequest.Execute() + if err != nil { + return fmt.Errorf("Bad: GetDNSZone: %s", err) + } + + if readResponse.IsSuccessful() { + return fmt.Errorf("Bad: DNS zone still exists: %s", readResponse.Error) + } + } + + return nil +} + +var testAccAzureRMDnsZone_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctest_rg_%d" + location = "West US" +} +resource "azurerm_dns_zone" "test" { + name = "acctestzone%d.com" + resource_group_name = "${azurerm_resource_group.test.name}" +} +` diff --git a/vendor/github.com/jen20/riviera/LICENSE.md b/vendor/github.com/jen20/riviera/LICENSE.md new file mode 100644 index 000000000..7be07fff1 --- /dev/null +++ b/vendor/github.com/jen20/riviera/LICENSE.md @@ -0,0 +1,180 @@ +##Mozilla Public License +###Version 2.0 + +1. Definitions + +1.1. “Contributor” +means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. + +1.2. “Contributor Version” +means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” +means Covered Software of a particular Contributor. + +1.4. “Covered Software” +means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. + +1.5. “Incompatible With Secondary Licenses” +means + +that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or + +that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. + +1.6. “Executable Form” +means any form of the work other than Source Code Form. + +1.7. “Larger Work” +means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. + +1.8. “License” +means this document. + +1.9. “Licensable” +means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. + +1.10. “Modifications” +means any of the following: + +any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or + +any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor +means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. + +1.12. “Secondary License” +means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” +means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) +means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants and Conditions + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + +under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and + +under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: + +for any code that a Contributor has removed from Covered Software; or + +for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or + +under Patent Claims infringed by Covered Software in the absence of its Contributions. + +This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. + +3. Responsibilities + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and + +You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + +If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. + +6. Disclaimer of Warranty + +Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. + +7. Limitation of Liability + +Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + +Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + +This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. + +10. Versions of the License + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + +If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + +This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + +This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/jen20/riviera/azure/api.go b/vendor/github.com/jen20/riviera/azure/api.go new file mode 100644 index 000000000..c0c132c79 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/api.go @@ -0,0 +1,11 @@ +package azure + +import "fmt" + +const resourceGroupAPIVersion = "2015-01-01" + +func resourceGroupDefaultURLFunc(resourceGroupName string) func() string { + return func() string { + return fmt.Sprintf("resourceGroups/%s", resourceGroupName) + } +} diff --git a/vendor/github.com/jen20/riviera/azure/apicall.go b/vendor/github.com/jen20/riviera/azure/apicall.go new file mode 100644 index 000000000..9b38b63cc --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/apicall.go @@ -0,0 +1,26 @@ +package azure + +// ApiCall must be implemented by structures which represent requests to the +// ARM API in order that the generic request handling layer has sufficient +// information to execute requests. +type ApiCall interface { + ApiInfo() ApiInfo +} + +// ApiInfo contains information about a request to the ARM API - which API +// version is required, the HTTP method to use, and a factory function for +// responses. +type ApiInfo struct { + ApiVersion string + Method string + SkipArmBoilerplate bool + URLPathFunc func() string + ResponseTypeFunc func() interface{} +} + +// HasBody returns true if the API Request should have a body. This is usually +// the case for PUT, PATCH or POST operations, but is not the case for GET operations. +// TODO(jen20): This may need revisiting at some point. +func (apiInfo ApiInfo) HasBody() bool { + return apiInfo.Method == "POST" || apiInfo.Method == "PUT" || apiInfo.Method == "PATCH" +} diff --git a/vendor/github.com/jen20/riviera/azure/azureerror.go b/vendor/github.com/jen20/riviera/azure/azureerror.go new file mode 100644 index 000000000..30715c087 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/azureerror.go @@ -0,0 +1,16 @@ +package azure + +import "fmt" + +// Error represents the body of an error response which is often returned +// by the Azure ARM API. +type Error struct { + StatusCode int + ErrorCode string `mapstructure:"code"` + Message string `mapstructure:"message"` +} + +// Error implements interface error on AzureError structures +func (e Error) Error() string { + return fmt.Sprintf("%s (%d) - %s", e.ErrorCode, e.StatusCode, e.Message) +} diff --git a/vendor/github.com/jen20/riviera/azure/client.go b/vendor/github.com/jen20/riviera/azure/client.go new file mode 100644 index 000000000..b632c30cd --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/client.go @@ -0,0 +1,53 @@ +package azure + +import ( + "io/ioutil" + "log" + + "github.com/hashicorp/go-retryablehttp" +) + +type Client struct { + logger *log.Logger + + BaseUrl string + subscriptionID string + + tokenRequester *tokenRequester + httpClient *retryablehttp.Client +} + +func NewClient(creds *AzureResourceManagerCredentials) (*Client, error) { + defaultLogger := log.New(ioutil.Discard, "", 0) + + httpClient := retryablehttp.NewClient() + httpClient.Logger = defaultLogger + + tr := newTokenRequester(httpClient, creds.ClientID, creds.ClientSecret, creds.TenantID) + + return &Client{ + BaseUrl: "https://management.azure.com", + subscriptionID: creds.SubscriptionID, + httpClient: httpClient, + tokenRequester: tr, + logger: defaultLogger, + }, nil +} + +func (c *Client) SetLogger(newLogger *log.Logger) { + c.logger = newLogger + c.httpClient.Logger = newLogger +} + +func (c *Client) NewRequest() *Request { + return &Request{ + client: c, + } +} + +func (c *Client) NewRequestForURI(resourceURI string) *Request { + return &Request{ + URI: &resourceURI, + client: c, + } +} diff --git a/vendor/github.com/jen20/riviera/azure/create_resource_group.go b/vendor/github.com/jen20/riviera/azure/create_resource_group.go new file mode 100644 index 000000000..48f9b8a63 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/create_resource_group.go @@ -0,0 +1,25 @@ +package azure + +type CreateResourceGroupResponse struct { + ID *string `mapstructure:"id"` + Name *string `mapstructure:"name"` + Location *string `mapstructure:"location"` + ProvisioningState *string `mapstructure:"provisioningState"` +} + +type CreateResourceGroup struct { + Name string `json:"-"` + Location string `json:"-" riviera:"location"` + Tags map[string]*string `json:"-" riviera:"tags"` +} + +func (command CreateResourceGroup) ApiInfo() ApiInfo { + return ApiInfo{ + ApiVersion: resourceGroupAPIVersion, + Method: "PUT", + URLPathFunc: resourceGroupDefaultURLFunc(command.Name), + ResponseTypeFunc: func() interface{} { + return &CreateResourceGroupResponse{} + }, + } +} diff --git a/vendor/github.com/jen20/riviera/azure/credentials.go b/vendor/github.com/jen20/riviera/azure/credentials.go new file mode 100644 index 000000000..7b3c8543b --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/credentials.go @@ -0,0 +1,8 @@ +package azure + +type AzureResourceManagerCredentials struct { + ClientID string + ClientSecret string + TenantID string + SubscriptionID string +} diff --git a/vendor/github.com/jen20/riviera/azure/delete_resource_group.go b/vendor/github.com/jen20/riviera/azure/delete_resource_group.go new file mode 100644 index 000000000..61bc72dad --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/delete_resource_group.go @@ -0,0 +1,16 @@ +package azure + +type DeleteResourceGroup struct { + Name string `json:"-"` +} + +func (s DeleteResourceGroup) ApiInfo() ApiInfo { + return ApiInfo{ + ApiVersion: resourceGroupAPIVersion, + Method: "DELETE", + URLPathFunc: resourceGroupDefaultURLFunc(s.Name), + ResponseTypeFunc: func() interface{} { + return nil + }, + } +} diff --git a/vendor/github.com/jen20/riviera/azure/locations.go b/vendor/github.com/jen20/riviera/azure/locations.go new file mode 100644 index 000000000..fb72bb357 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/locations.go @@ -0,0 +1,26 @@ +package azure + +const ( + Global = "global" + CentralUS = "centralus" + EastUS = "eastus" + EastUS2 = "eastus2" + USGovIowa = "usgoviowa" + USGovVirginia = "usgovvirginia" + NorthCentralUS = "northcentralus" + SouthCentralUS = "southcentralus" + WestUS = "westus" + NorthEurope = "northeurope" + WestEurope = "westeurope" + EastAsia = "eastasia" + SoutheastAsia = "southeastasia" + JapanEast = "japaneast" + JapanWest = "japanwest" + BrazilSouth = "brazilsouth" + AustraliaEast = "australiaeast" + Australia = "australia" + CentralIndia = "centralindia" + SouthIndia = "southindia" + WestIndia = "westindia" + ChinaEast = "chinaeast" +) diff --git a/vendor/github.com/jen20/riviera/azure/register_resource_provider.go b/vendor/github.com/jen20/riviera/azure/register_resource_provider.go new file mode 100644 index 000000000..bab7922af --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/register_resource_provider.go @@ -0,0 +1,28 @@ +package azure + +import "fmt" + +type RegisterResourceProviderResponse struct { + ID *string `mapstructure:"id"` + Namespace *string `mapstructure:"namespace"` + RegistrationState *string `mapstructure:"registrationState"` + ApplicationID *string `mapstructure:"applicationId"` +} + +// TODO: Investigate RegistrationState response polling +type RegisterResourceProvider struct { + Namespace string `json:"-"` +} + +func (command RegisterResourceProvider) ApiInfo() ApiInfo { + return ApiInfo{ + ApiVersion: resourceGroupAPIVersion, + Method: "POST", + URLPathFunc: func() string { + return fmt.Sprintf("providers/%s/register", command.Namespace) + }, + ResponseTypeFunc: func() interface{} { + return &RegisterResourceProviderResponse{} + }, + } +} diff --git a/vendor/github.com/jen20/riviera/azure/request.go b/vendor/github.com/jen20/riviera/azure/request.go new file mode 100644 index 000000000..c41a44f19 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/request.go @@ -0,0 +1,216 @@ +package azure + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "reflect" + "strconv" + "strings" + "time" + + "github.com/hashicorp/go-retryablehttp" + "github.com/mitchellh/mapstructure" +) + +type Request struct { + URI *string `json:"-"` + location *string `json:"location,omitempty"` + tags *map[string]*string `json:"tags,omitempty"` + etag *string `json:"etag,omitempty"` + Command ApiCall `json:"properties,omitempty"` + + client *Client +} + +func readLocation(req interface{}) (string, bool) { + var value reflect.Value + if reflect.ValueOf(req).Kind() == reflect.Ptr { + value = reflect.ValueOf(req).Elem() + } else { + value = reflect.ValueOf(req) + } + + for i := 0; i < value.NumField(); i++ { // iterates through every struct type field + tag := value.Type().Field(i).Tag // returns the tag string + if tag.Get("riviera") == "location" { + return value.Field(i).String(), true + } + } + return "", false +} + +func readTags(req interface{}) (map[string]*string, bool) { + var value reflect.Value + if reflect.ValueOf(req).Kind() == reflect.Ptr { + value = reflect.ValueOf(req).Elem() + } else { + value = reflect.ValueOf(req) + } + + for i := 0; i < value.NumField(); i++ { // iterates through every struct type field + tag := value.Type().Field(i).Tag // returns the tag string + if tag.Get("riviera") == "tags" { + tags := value.Field(i) + return tags.Interface().(map[string]*string), true + } + } + return make(map[string]*string), false +} + +func (request *Request) pollForAsynchronousResponse(acceptedResponse *http.Response) (*http.Response, error) { + var resp *http.Response = acceptedResponse + + for { + if resp.StatusCode != http.StatusAccepted { + return resp, nil + } + + if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { + retryTime, err := strconv.Atoi(strings.TrimSpace(retryAfter)) + if err != nil { + return nil, err + } + + request.client.logger.Printf("[INFO] Polling pausing for %d seconds as per Retry-After header", retryTime) + time.Sleep(time.Duration(retryTime) * time.Second) + } + + pollLocation, err := resp.Location() + if err != nil { + return nil, err + } + + request.client.logger.Printf("[INFO] Polling %q for operation completion", pollLocation.String()) + req, err := retryablehttp.NewRequest("GET", pollLocation.String(), bytes.NewReader([]byte{})) + if err != nil { + return nil, err + } + + err = request.client.tokenRequester.addAuthorizationToRequest(req) + if err != nil { + return nil, err + } + + resp, err := request.client.httpClient.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode == http.StatusAccepted { + continue + } + + return resp, err + } +} + +func (r *Request) Execute() (*Response, error) { + apiInfo := r.Command.ApiInfo() + + var urlString string + + // Base URL should already be validated by now so Parse is safe without error handling + urlObj, _ := url.Parse(r.client.BaseUrl) + + // Determine whether to use the URLPathFunc or the URI explictly set in the request + if r.URI == nil { + urlObj.Path = fmt.Sprintf("/subscriptions/%s/%s", r.client.subscriptionID, strings.TrimPrefix(apiInfo.URLPathFunc(), "/")) + urlString = urlObj.String() + } else { + urlObj.Path = *r.URI + urlString = urlObj.String() + } + + // Encode the request body if necessary + body := bytes.NewReader([]byte{}) + if apiInfo.HasBody() { + bodyStruct := struct { + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties interface{} `json:"properties"` + }{ + Properties: r.Command, + } + + if location, hasLocation := readLocation(r.Command); hasLocation { + bodyStruct.Location = &location + } + if tags, hasTags := readTags(r.Command); hasTags { + if len(tags) > 0 { + bodyStruct.Tags = &tags + } + } + + jsonEncodedRequest, err := json.Marshal(bodyStruct) + if err != nil { + return nil, err + } + body = bytes.NewReader(jsonEncodedRequest) + } + + // Create an HTTP request + req, err := retryablehttp.NewRequest(apiInfo.Method, urlString, body) + if err != nil { + return nil, err + } + + query := req.URL.Query() + query.Set("api-version", apiInfo.ApiVersion) + req.URL.RawQuery = query.Encode() + + if apiInfo.HasBody() { + req.Header.Add("Content-Type", "application/json") + } + + err = r.client.tokenRequester.addAuthorizationToRequest(req) + if err != nil { + return nil, err + } + + httpResponse, err := r.client.httpClient.Do(req) + if err != nil { + return nil, err + } + + // This is safe to use for every request: we check for it being http.StatusAccepted + httpResponse, err = r.pollForAsynchronousResponse(httpResponse) + if err != nil { + return nil, err + } + + var responseObj interface{} + var errorObj *Error + + if isSuccessCode(httpResponse.StatusCode) { + responseObj = apiInfo.ResponseTypeFunc() + // The response factory func returns nil as a signal that there is no body + if responseObj != nil { + responseMap, err := unmarshalFlattenPropertiesAndClose(httpResponse) + if err != nil { + return nil, err + } + + err = mapstructure.WeakDecode(responseMap, responseObj) + if err != nil { + return nil, err + } + } + } else { + responseMap, err := unmarshalFlattenErrorAndClose(httpResponse) + + err = mapstructure.WeakDecode(responseMap, &errorObj) + if err != nil { + return nil, err + } + + errorObj.StatusCode = httpResponse.StatusCode + } + + return &Response{ + HTTP: httpResponse, + Parsed: responseObj, + Error: errorObj, + }, nil +} diff --git a/vendor/github.com/jen20/riviera/azure/response.go b/vendor/github.com/jen20/riviera/azure/response.go new file mode 100644 index 000000000..3cc50b1fb --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/response.go @@ -0,0 +1,25 @@ +package azure + +import "net/http" + +// Response is the type returned by API operations. It provides low +// level access to the HTTP request from the operation if that is required, +// and a parsed version of the response as an interface{} which can be +// type asserted to the correct response type for the request. +type Response struct { + // HTTP provides direct access to the http.Response, though use should + // not be necessary as a matter of course + HTTP *http.Response + + // Parsed provides access the response structure of the command + Parsed interface{} + + // Error provides access to the error body if the command was unsuccessful + Error *Error +} + +// IsSuccessful returns true if the status code for the underlying +// HTTP request was a "successful" status code. +func (response *Response) IsSuccessful() bool { + return isSuccessCode(response.HTTP.StatusCode) +} diff --git a/vendor/github.com/jen20/riviera/azure/token.go b/vendor/github.com/jen20/riviera/azure/token.go new file mode 100644 index 000000000..cf99c17ab --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/token.go @@ -0,0 +1,119 @@ +package azure + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "sync" + "time" + + "github.com/hashicorp/go-retryablehttp" +) + +var expirationBase time.Time + +func init() { + expirationBase, _ = time.Parse(time.RFC3339, "1970-01-01T00:00:00Z") +} + +type tokenRequester struct { + clientID string + clientSecret string + tenantID string + + refreshWithin time.Duration + + httpClient *retryablehttp.Client + + l sync.Mutex + currentToken *token +} + +func newTokenRequester(client *retryablehttp.Client, clientID, clientSecret, tenantID string) *tokenRequester { + return &tokenRequester{ + clientID: clientID, + clientSecret: clientSecret, + tenantID: tenantID, + refreshWithin: 5 * time.Minute, + httpClient: client, + } +} + +// addAuthorizationToRequest adds an Authorization header to an http.Request, having ensured +// that the token is sufficiently fresh. This may invoke network calls, so should not be +// relied on to return quickly. +func (tr *tokenRequester) addAuthorizationToRequest(request *retryablehttp.Request) error { + token, err := tr.getUsableToken() + if err != nil { + return fmt.Errorf("Error obtaining authorization token: %s", err) + } + + request.Header.Add("Authorization", fmt.Sprintf("%s %s", token.TokenType, token.AccessToken)) + return nil +} + +func (tr *tokenRequester) getUsableToken() (*token, error) { + tr.l.Lock() + defer tr.l.Unlock() + + if tr.currentToken != nil && !tr.currentToken.willExpireIn(tr.refreshWithin) { + return tr.currentToken, nil + } + + newToken, err := tr.refreshToken() + if err != nil { + return nil, fmt.Errorf("Error refreshing token: %s", err) + } + + tr.currentToken = newToken + return newToken, nil +} + +func (tr *tokenRequester) refreshToken() (*token, error) { + oauthURL := fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/%s?api-version=1.0", tr.tenantID, "token") + + v := url.Values{} + v.Set("client_id", tr.clientID) + v.Set("client_secret", tr.clientSecret) + v.Set("grant_type", "client_credentials") + v.Set("resource", "https://management.azure.com/") + + var newToken token + response, err := tr.httpClient.PostForm(oauthURL, v) + if err != nil { + return nil, err + } + + defer response.Body.Close() + + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&newToken) + if err != nil { + return nil, err + } + + return &newToken, nil +} + +// Token encapsulates the access token used to authorize Azure requests. +type token struct { + AccessToken string `json:"access_token"` + ExpiresIn string `json:"expires_in"` + ExpiresOn string `json:"expires_on"` + NotBefore string `json:"not_before"` + Resource string `json:"resource"` + TokenType string `json:"token_type"` +} + +// willExpireIn returns true if the Token will expire after the passed time.Duration interval +// from now, false otherwise. +func (t token) willExpireIn(d time.Duration) bool { + s, err := strconv.Atoi(t.ExpiresOn) + if err != nil { + s = -3600 + } + expiryTime := expirationBase.Add(time.Duration(s) * time.Second).UTC() + + return !expiryTime.After(time.Now().Add(d)) +} diff --git a/vendor/github.com/jen20/riviera/azure/utils.go b/vendor/github.com/jen20/riviera/azure/utils.go new file mode 100644 index 000000000..c2cfc0980 --- /dev/null +++ b/vendor/github.com/jen20/riviera/azure/utils.go @@ -0,0 +1,61 @@ +package azure + +import ( + "encoding/json" + "net/http" +) + +// String returns a pointer to the input string. This is useful when initializing +// structures. +func String(input string) *string { + return &input +} + +// isSuccessCode returns true for 200-range numbers which usually denote +// that an HTTP request was successful +func isSuccessCode(statusCode int) bool { + if statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices { + return true + } + + return false +} + +// unmarshalFlattenPropertiesAndClose returns a map[string]interface{} with the +// "properties" key flattened for use with mapstructure. It closes the Body reader of +// the http.Response passed in. +func unmarshalFlattenPropertiesAndClose(response *http.Response) (map[string]interface{}, error) { + return unmarshalNested(response, "properties") +} + +// unmarshalFlattenErrorAndClose returns a map[string]interface{} with the +// "error" key flattened for use with mapstructure. It closes the Body reader of +// the http.Response passed in. +func unmarshalFlattenErrorAndClose(response *http.Response) (map[string]interface{}, error) { + return unmarshalNested(response, "error") +} + +func unmarshalNested(response *http.Response, key string) (map[string]interface{}, error) { + defer response.Body.Close() + + var unmarshalled map[string]interface{} + decoder := json.NewDecoder(response.Body) + + err := decoder.Decode(&unmarshalled) + if err != nil { + return nil, err + } + + if properties, hasProperties := unmarshalled[key]; hasProperties { + if propertiesMap, ok := properties.(map[string]interface{}); ok { + for k, v := range propertiesMap { + unmarshalled[k] = v + } + + delete(propertiesMap, key) + } + } + + return unmarshalled, nil + +} diff --git a/vendor/github.com/jen20/riviera/dns/api.go b/vendor/github.com/jen20/riviera/dns/api.go new file mode 100644 index 000000000..b983060d5 --- /dev/null +++ b/vendor/github.com/jen20/riviera/dns/api.go @@ -0,0 +1,12 @@ +package dns + +import "fmt" + +const apiVersion = "2015-05-04-preview" +const apiProvider = "Microsoft.Network" + +func dnsZoneDefaultURLPathFunc(resourceGroupName, dnsZoneName string) func() string { + return func() string { + return fmt.Sprintf("resourceGroups/%s/providers/%s/dnsZones/%s", resourceGroupName, apiProvider, dnsZoneName) + } +} diff --git a/vendor/github.com/jen20/riviera/dns/create_dns_zone.go b/vendor/github.com/jen20/riviera/dns/create_dns_zone.go new file mode 100644 index 000000000..f8ddfe1e4 --- /dev/null +++ b/vendor/github.com/jen20/riviera/dns/create_dns_zone.go @@ -0,0 +1,22 @@ +package dns + +import "github.com/jen20/riviera/azure" + +type CreateDNSZone struct { + Name string `json:"-"` + ResourceGroupName string `json:"-"` + Location string `json:"-" riviera:"location"` + Tags map[string]*string `json:"-" riviera:"tags"` +} + +func (command CreateDNSZone) ApiInfo() azure.ApiInfo { + return azure.ApiInfo{ + ApiVersion: apiVersion, + Method: "PUT", + URLPathFunc: dnsZoneDefaultURLPathFunc(command.ResourceGroupName, command.Name), + SkipArmBoilerplate: true, + ResponseTypeFunc: func() interface{} { + return nil + }, + } +} diff --git a/vendor/github.com/jen20/riviera/dns/delete_dns_zone.go b/vendor/github.com/jen20/riviera/dns/delete_dns_zone.go new file mode 100644 index 000000000..e421768ca --- /dev/null +++ b/vendor/github.com/jen20/riviera/dns/delete_dns_zone.go @@ -0,0 +1,20 @@ +package dns + +import "github.com/jen20/riviera/azure" + +type DeleteDNSZone struct { + Name string `json:"-"` + ResourceGroupName string `json:"-"` +} + +func (command DeleteDNSZone) ApiInfo() azure.ApiInfo { + return azure.ApiInfo{ + ApiVersion: apiVersion, + Method: "DELETE", + URLPathFunc: dnsZoneDefaultURLPathFunc(command.ResourceGroupName, command.Name), + SkipArmBoilerplate: true, + ResponseTypeFunc: func() interface{} { + return nil + }, + } +} diff --git a/vendor/github.com/jen20/riviera/dns/get_dns_zone.go b/vendor/github.com/jen20/riviera/dns/get_dns_zone.go new file mode 100644 index 000000000..c2888cd49 --- /dev/null +++ b/vendor/github.com/jen20/riviera/dns/get_dns_zone.go @@ -0,0 +1,28 @@ +package dns + +import "github.com/jen20/riviera/azure" + +type GetDNSZoneResponse struct { + ID *string `mapstructure:"id"` + Name *string `mapstructure:"name"` + Location *string `mapstructure:"location"` + Tags *map[string]*string `mapstructure:"tags"` + NumberOfRecordSets *string `mapstructure:"numberOfRecordSets"` + MaxNumberOfRecordSets *string `mapstructure:"maxNumberOfRecordSets"` +} + +type GetDNSZone struct { + Name string `json:"-"` + ResourceGroupName string `json:"-"` +} + +func (s GetDNSZone) ApiInfo() azure.ApiInfo { + return azure.ApiInfo{ + ApiVersion: apiVersion, + Method: "GET", + URLPathFunc: dnsZoneDefaultURLPathFunc(s.ResourceGroupName, s.Name), + ResponseTypeFunc: func() interface{} { + return &GetDNSZoneResponse{} + }, + } +} diff --git a/website/source/docs/providers/azurerm/r/dns_zone.html.markdown b/website/source/docs/providers/azurerm/r/dns_zone.html.markdown new file mode 100644 index 000000000..81997faaf --- /dev/null +++ b/website/source/docs/providers/azurerm/r/dns_zone.html.markdown @@ -0,0 +1,41 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_dns_zone" +sidebar_current: "docs-azurerm-resource-dns-zone" +description: |- + Create a DNS Zone. +--- + +# azurerm\_dns\_zone + +Enables you to manage DNS zones within Azure DNS. These zones are hosted on Azure's name servers to which you can delegate the zone from the parent domain. + +## Example Usage + +``` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} +resource "azurerm_dns_zone" "test" { + name = "mydomain.com" + resource_group_name = "${azurerm_resource_group.test.name}" +} +``` +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the DNS Zone. Must be a valid domain name. + +* `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The DNS Zone ID. +* `max_number_of_record_sets` - (Optional) Maximum number of Records in the zone. Defaults to `1000`. +* `number_of_record_sets` - (Optional) The number of records already in the zone. diff --git a/website/source/layouts/azurerm.erb b/website/source/layouts/azurerm.erb index 73e42e537..d34099280 100644 --- a/website/source/layouts/azurerm.erb +++ b/website/source/layouts/azurerm.erb @@ -30,6 +30,17 @@ +