Merge pull request #1093 from cloudskiff/feat/add_azurerm_container_registry

Add azurerm_container_registry resource
main
Elie 2021-10-06 15:13:14 +02:00 committed by GitHub
commit 4578eca53a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 598 additions and 6 deletions

1
go.mod
View File

@ -7,6 +7,7 @@ require (
cloud.google.com/go/storage v1.10.0
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0
github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0
github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry v0.2.0
github.com/Azure/azure-sdk-for-go/sdk/network/armnetwork v0.3.0
github.com/Azure/azure-sdk-for-go/sdk/resources/armresources v0.3.0
github.com/Azure/azure-sdk-for-go/sdk/storage/armstorage v0.2.0

2
go.sum
View File

@ -56,6 +56,8 @@ github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbL
github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.10.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0 h1:OYa9vmRX2XC5GXRAzeggG12sF/z5D9Ahtdm9EJ00WN4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0=
github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry v0.2.0 h1:+m3oFDUMWB/WsZiKj4dAcRSJ1muXAxgsDAXcZHYf0pk=
github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry v0.2.0/go.mod h1:NLX6U3EAoo6ZyZeCeBK9r6rwcUrj63yRKWeyzzTsKDg=
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0=
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8=
github.com/Azure/azure-sdk-for-go/sdk/network/armnetwork v0.3.0 h1:3ICM5L/XRaknp4DUNqdcNtiOzs6Mc3VKeyQp81+JS2Y=

View File

@ -0,0 +1,45 @@
package azurerm
import (
"github.com/cloudskiff/driftctl/pkg/remote/azurerm/repository"
remoteerror "github.com/cloudskiff/driftctl/pkg/remote/error"
"github.com/cloudskiff/driftctl/pkg/resource"
"github.com/cloudskiff/driftctl/pkg/resource/azurerm"
)
type AzurermContainerRegistryEnumerator struct {
repository repository.ContainerRegistryRepository
factory resource.ResourceFactory
}
func NewAzurermContainerRegistryEnumerator(repo repository.ContainerRegistryRepository, factory resource.ResourceFactory) *AzurermContainerRegistryEnumerator {
return &AzurermContainerRegistryEnumerator{
repository: repo,
factory: factory,
}
}
func (e *AzurermContainerRegistryEnumerator) SupportedType() resource.ResourceType {
return azurerm.AzureContainerRegistryResourceType
}
func (e *AzurermContainerRegistryEnumerator) Enumerate() ([]*resource.Resource, error) {
registries, err := e.repository.ListAllContainerRegistries()
if err != nil {
return nil, remoteerror.NewResourceListingError(err, string(e.SupportedType()))
}
results := make([]*resource.Resource, 0)
for _, registry := range registries {
results = append(
results,
e.factory.CreateAbstractResource(
string(e.SupportedType()),
*registry.ID,
map[string]interface{}{},
),
)
}
return results, err
}

View File

@ -44,6 +44,7 @@ func Init(
storageAccountRepo := repository.NewStorageRepository(con, providerConfig, c)
networkRepo := repository.NewNetworkRepository(con, providerConfig, c)
resourcesRepo := repository.NewResourcesRepository(con, providerConfig, c)
containerRegistryRepo := repository.NewContainerRegistryRepository(con, providerConfig, c)
providerLibrary.AddProvider(terraform.AZURE, provider)
@ -53,6 +54,7 @@ func Init(
remoteLibrary.AddEnumerator(NewAzurermRouteTableEnumerator(networkRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermResourceGroupEnumerator(resourcesRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermSubnetEnumerator(networkRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermContainerRegistryEnumerator(containerRegistryRepo, factory))
err = resourceSchemaRepository.Init(terraform.AZURE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -0,0 +1,68 @@
package repository
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
"github.com/cloudskiff/driftctl/pkg/remote/azurerm/common"
"github.com/cloudskiff/driftctl/pkg/remote/cache"
)
type ContainerRegistryRepository interface {
ListAllContainerRegistries() ([]*armcontainerregistry.Registry, error)
}
type registryClient interface {
List(options *armcontainerregistry.RegistriesListOptions) registryListAllPager
}
type registryListAllPager interface {
pager
PageResponse() armcontainerregistry.RegistriesListResponse
}
type registryClientImpl struct {
client *armcontainerregistry.RegistriesClient
}
func (c registryClientImpl) List(options *armcontainerregistry.RegistriesListOptions) registryListAllPager {
return c.client.List(options)
}
type containerRegistryRepository struct {
registryClient registryClient
cache cache.Cache
}
func NewContainerRegistryRepository(con *arm.Connection, config common.AzureProviderConfig, cache cache.Cache) *containerRegistryRepository {
return &containerRegistryRepository{
&registryClientImpl{client: armcontainerregistry.NewRegistriesClient(con, config.SubscriptionID)},
cache,
}
}
func (s *containerRegistryRepository) ListAllContainerRegistries() ([]*armcontainerregistry.Registry, error) {
if v := s.cache.Get("ListAllContainerRegistries"); v != nil {
return v.([]*armcontainerregistry.Registry), nil
}
pager := s.registryClient.List(nil)
results := make([]*armcontainerregistry.Registry, 0)
for pager.NextPage(context.Background()) {
resp := pager.PageResponse()
if err := pager.Err(); err != nil {
return nil, err
}
results = append(results, resp.Value...)
}
if err := pager.Err(); err != nil {
return nil, err
}
s.cache.Put("ListAllContainerRegistries", results)
return results, nil
}

View File

@ -0,0 +1,144 @@
package repository
import (
"reflect"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
"github.com/cloudskiff/driftctl/pkg/remote/cache"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func Test_Resources_ListAllContainerRegistries(t *testing.T) {
expectedResults := []*armcontainerregistry.Registry{
{
Resource: armcontainerregistry.Resource{
ID: to.StringPtr("/subscriptions/2c361f34-30fb-47ae-a227-83a5d3a26c66/resourceGroups/my-group/providers/Microsoft.ContainerRegistry/registries/containerRegistry1"),
Name: to.StringPtr("containerRegistry1"),
},
},
{
Resource: armcontainerregistry.Resource{
ID: to.StringPtr("/subscriptions/2c361f34-30fb-47ae-a227-83a5d3a26c66/resourceGroups/my-group/providers/Microsoft.ContainerRegistry/registries/containerRegistry1"),
Name: to.StringPtr("containerRegistry2"),
},
},
{
Resource: armcontainerregistry.Resource{
ID: to.StringPtr("/subscriptions/008b5f48-1b66-4d92-a6b6-d215b4c9b473/-/resource-3"),
Name: to.StringPtr("resource-3"),
},
},
}
testcases := []struct {
name string
mocks func(*mockRegistryListAllPager, *cache.MockCache)
expected []*armcontainerregistry.Registry
wantErr string
}{
{
name: "should return container registries",
mocks: func(mockPager *mockRegistryListAllPager, mockCache *cache.MockCache) {
mockPager.On("Err").Return(nil).Times(3)
mockPager.On("NextPage", mock.Anything).Return(true).Times(2)
mockPager.On("NextPage", mock.Anything).Return(false).Times(1)
mockPager.On("PageResponse").Return(armcontainerregistry.RegistriesListResponse{
RegistriesListResult: armcontainerregistry.RegistriesListResult{
RegistryListResult: armcontainerregistry.RegistryListResult{
Value: expectedResults[:2],
},
},
}).Times(1)
mockPager.On("PageResponse").Return(armcontainerregistry.RegistriesListResponse{
RegistriesListResult: armcontainerregistry.RegistriesListResult{
RegistryListResult: armcontainerregistry.RegistryListResult{
Value: expectedResults[2:],
},
},
}).Times(1)
mockCache.On("Get", "ListAllContainerRegistries").Return(nil).Times(1)
mockCache.On("Put", "ListAllContainerRegistries", expectedResults).Return(false).Times(1)
},
expected: expectedResults,
},
{
name: "should hit cache and return container registries",
mocks: func(mockPager *mockRegistryListAllPager, mockCache *cache.MockCache) {
mockCache.On("Get", "ListAllContainerRegistries").Return(expectedResults).Times(1)
},
expected: expectedResults,
},
{
name: "should return remote error",
mocks: func(mockPager *mockRegistryListAllPager, mockCache *cache.MockCache) {
mockPager.On("NextPage", mock.Anything).Return(true).Times(1)
mockPager.On("PageResponse").Return(armcontainerregistry.RegistriesListResponse{
RegistriesListResult: armcontainerregistry.RegistriesListResult{
RegistryListResult: armcontainerregistry.RegistryListResult{
Value: []*armcontainerregistry.Registry{},
},
},
}).Times(1)
mockPager.On("Err").Return(errors.New("remote error")).Times(1)
mockCache.On("Get", "ListAllContainerRegistries").Return(nil).Times(1)
},
wantErr: "remote error",
},
{
name: "should return remote error after fetching all pages",
mocks: func(mockPager *mockRegistryListAllPager, mockCache *cache.MockCache) {
mockPager.On("NextPage", mock.Anything).Return(true).Times(1)
mockPager.On("NextPage", mock.Anything).Return(false).Times(1)
mockPager.On("PageResponse").Return(armcontainerregistry.RegistriesListResponse{
RegistriesListResult: armcontainerregistry.RegistriesListResult{
RegistryListResult: armcontainerregistry.RegistryListResult{
Value: []*armcontainerregistry.Registry{},
},
},
}).Times(1)
mockPager.On("Err").Return(nil).Times(1)
mockPager.On("Err").Return(errors.New("remote error")).Times(1)
mockCache.On("Get", "ListAllContainerRegistries").Return(nil).Times(1)
},
wantErr: "remote error",
},
}
for _, tt := range testcases {
t.Run(tt.name, func(t *testing.T) {
fakeClient := &mockRegistryClient{}
mockPager := &mockRegistryListAllPager{}
mockCache := &cache.MockCache{}
fakeClient.On("List", mock.Anything).Maybe().Return(mockPager)
tt.mocks(mockPager, mockCache)
s := &containerRegistryRepository{
registryClient: fakeClient,
cache: mockCache,
}
got, err := s.ListAllContainerRegistries()
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.Nil(t, err)
}
fakeClient.AssertExpectations(t)
mockPager.AssertExpectations(t)
mockCache.AssertExpectations(t)
if !reflect.DeepEqual(got, tt.expected) {
t.Errorf("ListAllResourceGroups() got = %v, want %v", got, tt.expected)
}
})
}
}

View File

@ -0,0 +1,36 @@
// Code generated by mockery v0.0.0-dev. DO NOT EDIT.
package repository
import (
armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
mock "github.com/stretchr/testify/mock"
)
// MockContainerRegistryRepository is an autogenerated mock type for the ContainerRegistryRepository type
type MockContainerRegistryRepository struct {
mock.Mock
}
// ListAllContainerRegistries provides a mock function with given fields:
func (_m *MockContainerRegistryRepository) ListAllContainerRegistries() ([]*armcontainerregistry.Registry, error) {
ret := _m.Called()
var r0 []*armcontainerregistry.Registry
if rf, ok := ret.Get(0).(func() []*armcontainerregistry.Registry); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*armcontainerregistry.Registry)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}

View File

@ -0,0 +1,29 @@
// Code generated by mockery v0.0.0-dev. DO NOT EDIT.
package repository
import (
armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
mock "github.com/stretchr/testify/mock"
)
// mockRegistryClient is an autogenerated mock type for the registryClient type
type mockRegistryClient struct {
mock.Mock
}
// List provides a mock function with given fields: options
func (_m *mockRegistryClient) List(options *armcontainerregistry.RegistriesListOptions) registryListAllPager {
ret := _m.Called(options)
var r0 registryListAllPager
if rf, ok := ret.Get(0).(func(*armcontainerregistry.RegistriesListOptions) registryListAllPager); ok {
r0 = rf(options)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(registryListAllPager)
}
}
return r0
}

View File

@ -0,0 +1,58 @@
// Code generated by mockery v0.0.0-dev. DO NOT EDIT.
package repository
import (
context "context"
armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
mock "github.com/stretchr/testify/mock"
)
// mockRegistryListAllPager is an autogenerated mock type for the registryListAllPager type
type mockRegistryListAllPager struct {
mock.Mock
}
// Err provides a mock function with given fields:
func (_m *mockRegistryListAllPager) Err() error {
ret := _m.Called()
var r0 error
if rf, ok := ret.Get(0).(func() error); ok {
r0 = rf()
} else {
r0 = ret.Error(0)
}
return r0
}
// NextPage provides a mock function with given fields: ctx
func (_m *mockRegistryListAllPager) NextPage(ctx context.Context) bool {
ret := _m.Called(ctx)
var r0 bool
if rf, ok := ret.Get(0).(func(context.Context) bool); ok {
r0 = rf(ctx)
} else {
r0 = ret.Get(0).(bool)
}
return r0
}
// PageResponse provides a mock function with given fields:
func (_m *mockRegistryListAllPager) PageResponse() armcontainerregistry.RegistriesListResponse {
ret := _m.Called()
var r0 armcontainerregistry.RegistriesListResponse
if rf, ok := ret.Get(0).(func() armcontainerregistry.RegistriesListResponse); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(armcontainerregistry.RegistriesListResponse)
}
return r0
}

View File

@ -0,0 +1,112 @@
package remote
import (
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/containerregistry/armcontainerregistry"
"github.com/cloudskiff/driftctl/mocks"
"github.com/cloudskiff/driftctl/pkg/filter"
"github.com/cloudskiff/driftctl/pkg/remote/azurerm"
"github.com/cloudskiff/driftctl/pkg/remote/azurerm/repository"
"github.com/cloudskiff/driftctl/pkg/remote/common"
error2 "github.com/cloudskiff/driftctl/pkg/remote/error"
"github.com/cloudskiff/driftctl/pkg/resource"
resourceazure "github.com/cloudskiff/driftctl/pkg/resource/azurerm"
"github.com/cloudskiff/driftctl/pkg/terraform"
testresource "github.com/cloudskiff/driftctl/test/resource"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestAzurermContainerRegistry(t *testing.T) {
dummyError := errors.New("this is an error")
tests := []struct {
test string
mocks func(*repository.MockContainerRegistryRepository, *mocks.AlerterInterface)
assertExpected func(t *testing.T, got []*resource.Resource)
wantErr error
}{
{
test: "no container registry",
mocks: func(repository *repository.MockContainerRegistryRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllContainerRegistries").Return([]*armcontainerregistry.Registry{}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
},
{
test: "error listing container registry",
mocks: func(repository *repository.MockContainerRegistryRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllContainerRegistries").Return(nil, dummyError)
},
wantErr: error2.NewResourceListingError(dummyError, resourceazure.AzureContainerRegistryResourceType),
},
{
test: "multiple container registries",
mocks: func(repository *repository.MockContainerRegistryRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllContainerRegistries").Return([]*armcontainerregistry.Registry{
{
Resource: armcontainerregistry.Resource{
ID: to.StringPtr("registry1"),
},
},
{
Resource: armcontainerregistry.Resource{
ID: to.StringPtr("registry2"),
},
},
}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 2)
assert.Equal(t, got[0].ResourceId(), "registry1")
assert.Equal(t, got[0].ResourceType(), resourceazure.AzureContainerRegistryResourceType)
assert.Equal(t, got[1].ResourceId(), "registry2")
assert.Equal(t, got[1].ResourceType(), resourceazure.AzureContainerRegistryResourceType)
},
},
}
providerVersion := "2.71.0"
schemaRepository := testresource.InitFakeSchemaRepository("azurerm", providerVersion)
resourceazure.InitResourcesMetadata(schemaRepository)
factory := terraform.NewTerraformResourceFactory(schemaRepository)
for _, c := range tests {
t.Run(c.test, func(tt *testing.T) {
scanOptions := ScannerOptions{}
remoteLibrary := common.NewRemoteLibrary()
// Initialize mocks
alerter := &mocks.AlerterInterface{}
fakeRepo := &repository.MockContainerRegistryRepository{}
c.mocks(fakeRepo, alerter)
var repo repository.ContainerRegistryRepository = fakeRepo
remoteLibrary.AddEnumerator(azurerm.NewAzurermContainerRegistryEnumerator(repo, factory))
testFilter := &filter.MockFilter{}
testFilter.On("IsTypeIgnored", mock.Anything).Return(false)
s := NewScanner(remoteLibrary, alerter, scanOptions, testFilter)
got, err := s.Resources()
assert.Equal(tt, c.wantErr, err)
if err != nil {
return
}
c.assertExpected(tt, got)
alerter.AssertExpectations(tt)
fakeRepo.AssertExpectations(tt)
})
}
}

View File

@ -0,0 +1,16 @@
package azurerm
import "github.com/cloudskiff/driftctl/pkg/resource"
const AzureContainerRegistryResourceType = "azurerm_container_registry"
func initAzureContainerRegistryMetadata(resourceSchemaRepository resource.SchemaRepositoryInterface) {
resourceSchemaRepository.SetHumanReadableAttributesFunc(AzureContainerRegistryResourceType, func(res *resource.Resource) map[string]string {
val := res.Attrs
attrs := make(map[string]string)
if name := val.GetString("name"); name != nil && *name != "" {
attrs["Name"] = *name
}
return attrs
})
}

View File

@ -0,0 +1,31 @@
package azurerm_test
import (
"testing"
"github.com/cloudskiff/driftctl/test"
"github.com/cloudskiff/driftctl/test/acceptance"
)
func TestAcc_Azure_ContainerRegistry(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/azurerm_container_registry"},
Args: []string{
"scan",
"--to", "azure+tf",
"--filter", "Type=='azurerm_container_registry' && contains(Id, 'containerRegistry198745268459')",
},
Checks: []acceptance.AccCheck{
{
Check: func(result *test.ScanResult, stdout string, err error) {
if err != nil {
t.Fatal(err)
}
result.AssertInfrastructureIsInSync()
result.AssertManagedCount(1)
},
},
},
})
}

View File

@ -6,4 +6,5 @@ func InitResourcesMetadata(resourceSchemaRepository resource.SchemaRepositoryInt
initAzureVirtualNetworkMetaData(resourceSchemaRepository)
initAzureRouteTableMetaData(resourceSchemaRepository)
initAzureResourceGroupMetadata(resourceSchemaRepository)
initAzureContainerRegistryMetadata(resourceSchemaRepository)
}

View File

@ -0,0 +1,21 @@
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/hashicorp/azurerm" {
version = "2.71.0"
constraints = "~> 2.71.0"
hashes = [
"h1:RiFIxNI4Yr9CqleqEdgg1ydLAZ5JiYiz6l5iTD3WcuU=",
"zh:2b9d8a703a0222f72cbceb8d2bdb580066afdcd7f28b6ad65d5ed935319b5433",
"zh:332988f4c1747bcc8ebd32734bf8de2bea4c13a6fbd08d7eb97d0c43d335b15e",
"zh:3a902470276ba48e23ad4dd6baff16a9ce3b60b29c0b07064dbe96ce4640a31c",
"zh:5eaa0d0c2c6554913421be10fbf4bb6a9ef98fbbd750d3d1f02c99798aae2c22",
"zh:67859f40ed2f770f33ace9d3911e8b9c9be505947b38a0578e6d097f5db1d4bf",
"zh:7cd9bf4899fe383fc7eeede03cad138d637244878cd295a7a1044ca20ca0652c",
"zh:afcb82c1382a1a9d63a41137321e077144aad768e4e46057a7ea604d067b4181",
"zh:c6e358759ed00a628dcfe7adb0906b2c98576ac3056fdd70930786d404e1da66",
"zh:cb3390c34f6790ad656929d0268ab3bc082678e8cbe2add0a177cf7896068844",
"zh:cc213dbf59cf41506e86b83492ccfef6ef5f34d4d00d9e49fc8a01fee253f4ee",
"zh:d1e8c9b507e2d187ea2447ae156028ba3f76db2164674761987c14217d04fee5",
]
}

View File

@ -0,0 +1,25 @@
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.71.0"
}
}
}
provider "azurerm" {
features {}
}
data "azurerm_resource_group" "qa1" {
name = "driftctl-qa-1"
}
resource "azurerm_container_registry" "acr" {
name = "containerRegistry198745268459"
resource_group_name = data.azurerm_resource_group.qa1.name
location = data.azurerm_resource_group.qa1.location
sku = "Premium"
admin_enabled = false
georeplications = []
}

View File

@ -89,6 +89,7 @@ var supportedTypes = map[string]struct{}{
"azurerm_route_table": {},
"azurerm_resource_group": {},
"azurerm_subnet": {},
"azurerm_container_registry": {},
}
func IsResourceTypeSupported(ty string) bool {