Skip to content

Commit

Permalink
feat: adding Azure Container Registry module (#592)
Browse files Browse the repository at this point in the history
* adding Azure Container Registry module

* misspellings fixed, unneeded TODO label removed

* misspelling for ACR fixed

* update ACR example

* update ACR readme

* Update containers module

* add containers module tests

* update acr test sample

* fix tf format

Co-authored-by: Hadwa Gaber <hadwa.gaber@hotmail.com>
Co-authored-by: Hadwa Abdelhalem <hadwaa@microsoft.com>
  • Loading branch information
3 people committed Aug 4, 2021
1 parent 0b6019a commit c66467d
Show file tree
Hide file tree
Showing 8 changed files with 334 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples/azure/terraform-azure-acr-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Terraform Azure Example

This folder contains a Terraform module that deploys resources in [Azure](https://azure.microsoft.com/) to demonstrate
how you can use Terratest to write automated tests for your Azure Terraform code. This module deploys an [Azure Container Registry](https://azure.microsoft.com/en-us/services/container-registry/).

Check out [test/azure/terraform_azure_acr_example_test.go](/test/azure/terraform_azure_acr_example_test.go) to see how you can write
automated tests for this module.

**WARNING**: This module and the automated tests for it deploy real resources into your Azure account which can cost you
money. The resources are all part of the [Azure Free Account](https://azure.microsoft.com/en-us/free/), so if you haven't used that up,
it should be free, but you are completely responsible for all Azure charges.

## Running this module manually

1. Sign up for [Azure](https://azure.microsoft.com/)
1. Configure your Azure credentials using one of the [supported methods for Azure CLI
tools](https://docs.microsoft.com/cli/azure/azure-cli-configuration?view=azure-cli-latest)
1. Install [Terraform](https://www.terraform.io/) and make sure it's on your `PATH`
1. Ensure [environment variables](../README.md#review-environment-variables) are available
1. Run `terraform init`
1. Run `terraform apply`
1. When you're done, run `terraform destroy`


## Running automated tests against this module

1. Sign up for [Azure](https://azure.microsoft.com/)
1. Configure your Azure credentials using one of the [supported methods for Azure CLI
tools](https://docs.microsoft.com/en-us/cli/azure/azure-cli-configuration?view=azure-cli-latest)
1. Install [Terraform](https://www.terraform.io/) and make sure it's on your `PATH`
1. Configure your Terratest [Go test environment](../README.md)
1. `cd test/azure`
1. `go build terraform_azure_acr_example_test.go`
1. `go test -v -timeout 60m -tags azure -run TestTerraformAzureACRExample`
40 changes: 40 additions & 0 deletions examples/azure/terraform-azure-acr-example/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# ---------------------------------------------------------------------------------------------------------------------
# DEPLOY AN AZURE CONTAINER REGISTRY
# This is an example of how to deploy an Azure Container Registry
# See test/terraform_azure_acr_example_test.go for how to write automated tests for this code.
# ---------------------------------------------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# CONFIGURE OUR AZURE CONNECTION
# ------------------------------------------------------------------------------

provider "azurerm" {
version = "~>2.29.0"
features {}
}

# ---------------------------------------------------------------------------------------------------------------------
# DEPLOY A RESOURCE GROUP
# ---------------------------------------------------------------------------------------------------------------------

resource "azurerm_resource_group" "rg" {
name = "terratest-acr-rg-${var.postfix}"
location = var.location
}

# ---------------------------------------------------------------------------------------------------------------------
# DEPLOY AN AZURE CONTAINER REGISTRY
# ---------------------------------------------------------------------------------------------------------------------

resource "azurerm_container_registry" "acr" {
name = "acr${var.postfix}"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name

sku = var.sku
admin_enabled = true

tags = {
Environment = "Development"
}
}
21 changes: 21 additions & 0 deletions examples/azure/terraform-azure-acr-example/output.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
output "resource_group_name" {
value = azurerm_resource_group.rg.name
}

output "container_registry_name" {
value = azurerm_container_registry.acr.name
}

output "login_server" {
value = azurerm_container_registry.acr.login_server
}

output "admin_username" {
value = azurerm_container_registry.acr.admin_username
sensitive = true
}

output "admin_password" {
value = azurerm_container_registry.acr.admin_password
sensitive = true
}
37 changes: 37 additions & 0 deletions examples/azure/terraform-azure-acr-example/variables.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# ---------------------------------------------------------------------------------------------------------------------
# ENVIRONMENT VARIABLES
# Define these secrets as environment variables
# ---------------------------------------------------------------------------------------------------------------------

# ARM_CLIENT_ID
# ARM_CLIENT_SECRET
# ARM_SUBSCRIPTION_ID
# ARM_TENANT_ID

# ---------------------------------------------------------------------------------------------------------------------
# REQUIRED PARAMETERS
# You must provide a value for each of these parameters.
# ---------------------------------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------------------------------
# OPTIONAL PARAMETERS
# These parameters have reasonable defaults.
# ---------------------------------------------------------------------------------------------------------------------

variable "sku" {
description = "SKU tier for the ACR."
default = "Premium"
}


variable "location" {
description = "The supported azure location where the resource exists"
type = string
default = "West US2"
}

variable "postfix" {
description = "A postfix string to centrally mitigate resource name collisions."
type = string
default = "1276"
}
22 changes: 22 additions & 0 deletions modules/azure/client_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/Azure/azure-sdk-for-go/profiles/preview/cosmos-db/mgmt/documentdb"
"github.com/Azure/azure-sdk-for-go/profiles/preview/preview/monitor/mgmt/insights"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute"
"github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-05-01/containerregistry"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2019-11-01/containerservice"
kvmng "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network"
Expand Down Expand Up @@ -664,6 +665,27 @@ func CreateAppServiceClientE(subscriptionID string) (*web.AppsClient, error) {
return &appsClient, nil
}

// CreateContainerRegistryClientE returns an ACR client instance configured with the
// correct BaseURI depending on the Azure environment that is currently setup (or "Public", if none is setup).
func CreateContainerRegistryClientE(subscriptionID string) (*containerregistry.RegistriesClient, error) {

// Validate Azure subscription ID
subscriptionID, err := getTargetAzureSubscription(subscriptionID)
if err != nil {
return nil, err
}

// Lookup environment URI
baseURI, err := getEnvironmentEndpointE(ResourceManagerEndpointName)
if err != nil {
return nil, err
}

// create client
registryClient := containerregistry.NewRegistriesClientWithBaseURI(baseURI, subscriptionID)
return &registryClient, nil
}

// GetKeyVaultURISuffixE returns the proper KeyVault URI suffix for the configured Azure environment.
// This function would fail the test if there is an error.
func GetKeyVaultURISuffixE() (string, error) {
Expand Down
79 changes: 79 additions & 0 deletions modules/azure/containers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package azure

import (
"context"
"testing"

"github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-05-01/containerregistry"
"github.com/stretchr/testify/require"
)

// ContainerRegistryExists indicates whether the specified container registry exists.
// This function would fail the test if there is an error.
func ContainerRegistryExists(t *testing.T, registryName string, resourceGroupName string, subscriptionID string) bool {
exists, err := ContainerRegistryExistsE(registryName, resourceGroupName, subscriptionID)
require.NoError(t, err)

return exists
}

// ContainerRegistryExistsE indicates whether the specified container registry exists.
func ContainerRegistryExistsE(registryName string, resourceGroupName string, subscriptionID string) (bool, error) {
_, err := GetContainerRegistryE(registryName, resourceGroupName, subscriptionID)
if err != nil {
if ResourceNotFoundErrorExists(err) {
return false, nil
}
return false, err
}
return true, nil
}

// GetContainerRegistry gets the container registry object
// This function would fail the test if there is an error.
func GetContainerRegistry(t *testing.T, registryName string, resGroupName string, subscriptionID string) *containerregistry.Registry {
resource, err := GetContainerRegistryE(registryName, resGroupName, subscriptionID)

require.NoError(t, err)

return resource
}

// GetContainerRegistryE gets the container registry object
func GetContainerRegistryE(registryName string, resGroupName string, subscriptionID string) (*containerregistry.Registry, error) {
rgName, err := getTargetAzureResourceGroupName(resGroupName)
if err != nil {
return nil, err
}

client, err := GetContainerRegistryClientE(subscriptionID)
if err != nil {
return nil, err
}

resource, err := client.Get(context.Background(), rgName, registryName)
if err != nil {
return nil, err
}

return &resource, nil
}

// GetContainerRegistryClientE is a helper function that will setup an Azure Container Registry client on your behalf
func GetContainerRegistryClientE(subscriptionID string) (*containerregistry.RegistriesClient, error) {
// Create an Apps client
registryClient, err := CreateContainerRegistryClientE(subscriptionID)
if err != nil {
return nil, err
}

// Create an authorizer
authorizer, err := NewAuthorizer()
if err != nil {
return nil, err
}

// Attach authorizer to the client
registryClient.Authorizer = *authorizer
return registryClient, nil
}
48 changes: 48 additions & 0 deletions modules/azure/containers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// +build azure

// NOTE: We use build tags to differentiate azure testing because we currently do not have azure access setup for
// CircleCI.

package azure

import (
"testing"

"github.com/stretchr/testify/require"
)

/*
The below tests are currently stubbed out, with the expectation that they will throw errors.
If/when CRUD methods are introduced for Azure MySQL server and database, these tests can be extended
*/

func TestContainerRegistryExistsE(t *testing.T) {
t.Parallel()

resGroupName := ""
registryName := ""
subscriptionID := ""

_, err := ContainerRegistryExistsE(registryName, resGroupName, subscriptionID)
require.Error(t, err)
}

func TestGetContainerRegistryE(t *testing.T) {
t.Parallel()

resGroupName := ""
registryName := ""
subscriptionID := ""

_, err := GetContainerRegistryE(registryName, resGroupName, subscriptionID)
require.Error(t, err)
}

func TestGetContainerRegistryClientE(t *testing.T) {
t.Parallel()

subscriptionID := ""

_, err := GetContainerRegistryClientE(subscriptionID)
require.NoError(t, err)
}
53 changes: 53 additions & 0 deletions test/azure/terraform_azure_acr_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// +build azure

// NOTE: We use build tags to differentiate azure testing because we currently do not have azure access setup for
// CircleCI.

package test

import (
"strings"

"testing"

"github.com/gruntwork-io/terratest/modules/azure"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)

func TestTerraformAzureACRExample(t *testing.T) {
t.Parallel()

uniquePostfix := strings.ToLower(random.UniqueId())
acrSKU := "Premium"

// website::tag::1:: Configure Terraform setting up a path to Terraform code.
terraformOptions := &terraform.Options{
TerraformDir: "../../examples/azure/terraform-azure-acr-example",
Vars: map[string]interface{}{
"postfix": uniquePostfix,
"sku": acrSKU,
},
}

// website::tag::5:: At the end of the test, run `terraform destroy` to clean up any resources that were created
defer terraform.Destroy(t, terraformOptions)

// website::tag::2:: Run `terraform init` and `terraform apply`. Fail the test if there are any errors.
terraform.InitAndApply(t, terraformOptions)

// website::tag::3:: Run `terraform output` to get the values of output variables
resourceGroupName := terraform.Output(t, terraformOptions, "resource_group_name")
acrName := terraform.Output(t, terraformOptions, "container_registry_name")
loginServer := terraform.Output(t, terraformOptions, "login_server")

// website::tag::4:: Assert
assert.True(t, azure.ContainerRegistryExists(t, acrName, resourceGroupName, ""))

actualACR := azure.GetContainerRegistry(t, acrName, resourceGroupName, "")

assert.Equal(t, loginServer, *actualACR.LoginServer)
assert.True(t, *actualACR.AdminUserEnabled)
assert.Equal(t, acrSKU, string(actualACR.Sku.Name))
}

0 comments on commit c66467d

Please sign in to comment.