Add azurerm_firewall

main
Elie 2021-10-07 11:17:46 +02:00
parent 7f7c239d5b
commit 6d0e5afbd5
No known key found for this signature in database
GPG Key ID: 399AF69092C727B6
14 changed files with 545 additions and 2 deletions

View File

@ -0,0 +1,48 @@
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 AzurermFirewallsEnumerator struct {
repository repository.NetworkRepository
factory resource.ResourceFactory
}
func NewAzurermFirewallsEnumerator(repo repository.NetworkRepository, factory resource.ResourceFactory) *AzurermFirewallsEnumerator {
return &AzurermFirewallsEnumerator{
repository: repo,
factory: factory,
}
}
func (e *AzurermFirewallsEnumerator) SupportedType() resource.ResourceType {
return azurerm.AzureFirewallResourceType
}
func (e *AzurermFirewallsEnumerator) Enumerate() ([]*resource.Resource, error) {
resources, err := e.repository.ListAllFirewalls()
if err != nil {
return nil, remoteerror.NewResourceListingError(err, string(e.SupportedType()))
}
results := make([]*resource.Resource, len(resources))
for _, res := range resources {
results = append(
results,
e.factory.CreateAbstractResource(
string(e.SupportedType()),
*res.ID,
map[string]interface{}{
"name": *res.Name,
},
),
)
}
return results, err
}

View File

@ -55,6 +55,7 @@ func Init(
remoteLibrary.AddEnumerator(NewAzurermResourceGroupEnumerator(resourcesRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermSubnetEnumerator(networkRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermContainerRegistryEnumerator(containerRegistryRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermFirewallsEnumerator(networkRepo, factory))
err = resourceSchemaRepository.Init(terraform.AZURE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -12,6 +12,29 @@ type MockNetworkRepository struct {
mock.Mock
}
// ListAllFirewalls provides a mock function with given fields:
func (_m *MockNetworkRepository) ListAllFirewalls() ([]*armnetwork.AzureFirewall, error) {
ret := _m.Called()
var r0 []*armnetwork.AzureFirewall
if rf, ok := ret.Get(0).(func() []*armnetwork.AzureFirewall); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*armnetwork.AzureFirewall)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListAllRouteTables provides a mock function with given fields:
func (_m *MockNetworkRepository) ListAllRouteTables() ([]*armnetwork.RouteTable, error) {
ret := _m.Called()
@ -35,7 +58,6 @@ func (_m *MockNetworkRepository) ListAllRouteTables() ([]*armnetwork.RouteTable,
return r0, r1
}
// ListAllVirtualNetworks provides a mock function with given fields:
// ListAllSubnets provides a mock function with given fields: virtualNetwork
func (_m *MockNetworkRepository) ListAllSubnets(virtualNetwork *armnetwork.VirtualNetwork) ([]*armnetwork.Subnet, error) {
ret := _m.Called(virtualNetwork)
@ -59,7 +81,7 @@ func (_m *MockNetworkRepository) ListAllSubnets(virtualNetwork *armnetwork.Virtu
return r0, r1
}
// ListAllVirtualNetwork provides a mock function with given fields:
// ListAllVirtualNetworks provides a mock function with given fields:
func (_m *MockNetworkRepository) ListAllVirtualNetworks() ([]*armnetwork.VirtualNetwork, error) {
ret := _m.Called()

View File

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

View File

@ -0,0 +1,58 @@
// Code generated by mockery v0.0.0-dev. DO NOT EDIT.
package repository
import (
context "context"
armnetwork "github.com/Azure/azure-sdk-for-go/sdk/network/armnetwork"
mock "github.com/stretchr/testify/mock"
)
// mockFirewallsListAllPager is an autogenerated mock type for the firewallsListAllPager type
type mockFirewallsListAllPager struct {
mock.Mock
}
// Err provides a mock function with given fields:
func (_m *mockFirewallsListAllPager) 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 *mockFirewallsListAllPager) 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 *mockFirewallsListAllPager) PageResponse() armnetwork.AzureFirewallsListAllResponse {
ret := _m.Called()
var r0 armnetwork.AzureFirewallsListAllResponse
if rf, ok := ret.Get(0).(func() armnetwork.AzureFirewallsListAllResponse); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(armnetwork.AzureFirewallsListAllResponse)
}
return r0
}

View File

@ -15,6 +15,24 @@ type NetworkRepository interface {
ListAllVirtualNetworks() ([]*armnetwork.VirtualNetwork, error)
ListAllRouteTables() ([]*armnetwork.RouteTable, error)
ListAllSubnets(virtualNetwork *armnetwork.VirtualNetwork) ([]*armnetwork.Subnet, error)
ListAllFirewalls() ([]*armnetwork.AzureFirewall, error)
}
type firewallsListAllPager interface {
pager
PageResponse() armnetwork.AzureFirewallsListAllResponse
}
type firewallsClient interface {
ListAll(options *armnetwork.AzureFirewallsListAllOptions) firewallsListAllPager
}
type firewallsClientImpl struct {
client *armnetwork.AzureFirewallsClient
}
func (s firewallsClientImpl) ListAll(options *armnetwork.AzureFirewallsListAllOptions) firewallsListAllPager {
return s.client.ListAll(options)
}
type subnetsListPager interface {
@ -72,6 +90,7 @@ type networkRepository struct {
virtualNetworksClient virtualNetworksClient
routeTableClient routeTablesClient
subnetsClient subnetsClient
firewallsClient firewallsClient
cache cache.Cache
}
@ -80,6 +99,7 @@ func NewNetworkRepository(con *arm.Connection, config common.AzureProviderConfig
&virtualNetworksClientImpl{client: armnetwork.NewVirtualNetworksClient(con, config.SubscriptionID)},
&routeTablesClientImpl{client: armnetwork.NewRouteTablesClient(con, config.SubscriptionID)},
&subnetsClientImpl{client: armnetwork.NewSubnetsClient(con, config.SubscriptionID)},
&firewallsClientImpl{client: armnetwork.NewAzureFirewallsClient(con, config.SubscriptionID)},
cache,
}
}
@ -164,3 +184,30 @@ func (s *networkRepository) ListAllSubnets(virtualNetwork *armnetwork.VirtualNet
return results, nil
}
func (s *networkRepository) ListAllFirewalls() ([]*armnetwork.AzureFirewall, error) {
cacheKey := "ListAllFirewalls"
if v := s.cache.Get(cacheKey); v != nil {
return v.([]*armnetwork.AzureFirewall), nil
}
pager := s.firewallsClient.ListAll(nil)
results := make([]*armnetwork.AzureFirewall, 0)
for pager.NextPage(context.Background()) {
resp := pager.PageResponse()
if err := pager.Err(); err != nil {
return nil, err
}
results = append(results, resp.AzureFirewallsListAllResult.AzureFirewallListResult.Value...)
}
if err := pager.Err(); err != nil {
return nil, err
}
s.cache.Put(cacheKey, results)
return results, nil
}

View File

@ -565,3 +565,156 @@ func Test_ListAllSubnets_ErrorOnInvalidNetworkID(t *testing.T) {
assert.Equal(t, expectedErr.Error(), err.Error())
assert.Nil(t, got)
}
func Test_ListAllFirewalls_MultiplesResults(t *testing.T) {
expected := []*armnetwork.AzureFirewall{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall2"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall3"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall4"),
},
},
}
fakeClient := &mockFirewallsClient{}
mockPager := &mockFirewallsListAllPager{}
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(armnetwork.AzureFirewallsListAllResponse{
AzureFirewallsListAllResult: armnetwork.AzureFirewallsListAllResult{
AzureFirewallListResult: armnetwork.AzureFirewallListResult{
Value: expected[:2],
},
},
}).Times(1)
mockPager.On("PageResponse").Return(armnetwork.AzureFirewallsListAllResponse{
AzureFirewallsListAllResult: armnetwork.AzureFirewallsListAllResult{
AzureFirewallListResult: armnetwork.AzureFirewallListResult{
Value: expected[2:],
},
},
}).Times(1)
fakeClient.On("ListAll", mock.Anything).Return(mockPager)
c := &cache.MockCache{}
c.On("Get", "ListAllFirewalls").Return(nil).Times(1)
c.On("Put", "ListAllFirewalls", expected).Return(true).Times(1)
s := &networkRepository{
firewallsClient: fakeClient,
cache: c,
}
got, err := s.ListAllFirewalls()
if err != nil {
t.Errorf("ListAllFirewalls() error = %v", err)
return
}
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
c.AssertExpectations(t)
if !reflect.DeepEqual(got, expected) {
t.Errorf("ListAllFirewalls() got = %v, want %v", got, expected)
}
}
func Test_ListAllFirewalls_MultiplesResults_WithCache(t *testing.T) {
expected := []*armnetwork.AzureFirewall{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall1"),
},
},
}
fakeClient := &mockFirewallsClient{}
c := &cache.MockCache{}
c.On("Get", "ListAllFirewalls").Return(expected).Times(1)
s := &networkRepository{
firewallsClient: fakeClient,
cache: c,
}
got, err := s.ListAllFirewalls()
if err != nil {
t.Errorf("ListAllFirewalls() error = %v", err)
return
}
fakeClient.AssertExpectations(t)
c.AssertExpectations(t)
if !reflect.DeepEqual(got, expected) {
t.Errorf("ListAllFirewalls() got = %v, want %v", got, expected)
}
}
func Test_ListAllFirewalls_Error_OnPageResponse(t *testing.T) {
fakeClient := &mockFirewallsClient{}
expectedErr := errors.New("unexpected error")
mockPager := &mockFirewallsListAllPager{}
mockPager.On("Err").Return(expectedErr).Times(1)
mockPager.On("NextPage", mock.Anything).Return(true).Times(1)
mockPager.On("PageResponse").Return(armnetwork.AzureFirewallsListAllResponse{}).Times(1)
fakeClient.On("ListAll", mock.Anything).Return(mockPager)
s := &networkRepository{
firewallsClient: fakeClient,
cache: cache.New(0),
}
got, err := s.ListAllFirewalls()
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}
func Test_ListAllFirewalls_Error(t *testing.T) {
fakeClient := &mockFirewallsClient{}
expectedErr := errors.New("unexpected error")
mockPager := &mockFirewallsListAllPager{}
mockPager.On("Err").Return(expectedErr).Times(1)
mockPager.On("NextPage", mock.Anything).Return(false).Times(1)
fakeClient.On("ListAll", mock.Anything).Return(mockPager)
s := &networkRepository{
firewallsClient: fakeClient,
cache: cache.New(0),
}
got, err := s.ListAllFirewalls()
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}

View File

@ -338,3 +338,96 @@ func TestAzurermSubnets(t *testing.T) {
})
}
}
func TestAzurermFirewalls(t *testing.T) {
dummyError := errors.New("this is an error")
tests := []struct {
test string
mocks func(*repository.MockNetworkRepository, *mocks.AlerterInterface)
assertExpected func(t *testing.T, got []*resource.Resource)
wantErr error
}{
{
test: "no firewall",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllFirewalls").Return([]*armnetwork.AzureFirewall{}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
},
{
test: "error listing firewalls",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllFirewalls").Return(nil, dummyError)
},
wantErr: error2.NewResourceListingError(dummyError, resourceazure.AzureFirewallResourceType),
},
{
test: "multiple firewalls",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllFirewalls").Return([]*armnetwork.AzureFirewall{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall1"), // Here we don't care to have a valid ID, it is for testing purpose only
Name: to.StringPtr("firewall1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("firewall2"),
Name: to.StringPtr("firewall2"),
},
},
}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 2)
assert.Equal(t, got[0].ResourceId(), "firewall1")
assert.Equal(t, got[0].ResourceType(), resourceazure.AzureFirewallResourceType)
assert.Equal(t, got[1].ResourceId(), "firewall2")
assert.Equal(t, got[1].ResourceType(), resourceazure.AzureFirewallResourceType)
},
},
}
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.MockNetworkRepository{}
c.mocks(fakeRepo, alerter)
var repo repository.NetworkRepository = fakeRepo
remoteLibrary.AddEnumerator(azurerm.NewAzurermFirewallsEnumerator(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 AzureFirewallResourceType = "azurerm_firewall"
func initAzureFirewallMetadata(resourceSchemaRepository resource.SchemaRepositoryInterface) {
resourceSchemaRepository.SetHumanReadableAttributesFunc(AzureFirewallResourceType, 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_Firewall(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/azurerm_firewall"},
Args: []string{
"scan",
"--to", "azure+tf",
"--filter", "Type=='azurerm_firewall'",
},
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

@ -7,4 +7,5 @@ func InitResourcesMetadata(resourceSchemaRepository resource.SchemaRepositoryInt
initAzureRouteTableMetaData(resourceSchemaRepository)
initAzureResourceGroupMetadata(resourceSchemaRepository)
initAzureContainerRegistryMetadata(resourceSchemaRepository)
initAzureFirewallMetadata(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,22 @@
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.71.0"
}
}
}
provider "azurerm" {
features {}
}
data "azurerm_resource_group" "example" {
name = "driftctl-qa-1"
}
resource "azurerm_firewall" "example" {
name = "testfirewall"
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
}

View File

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