Merge pull request #1124 from cloudskiff/add_azurerm_public_ip

Add azurerm_public_ip
main
Elie 2021-10-13 16:31:24 +02:00 committed by GitHub
commit ca49fa2921
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 549 additions and 5 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 AzurermPublicIPEnumerator struct {
repository repository.NetworkRepository
factory resource.ResourceFactory
}
func NewAzurermPublicIPEnumerator(repo repository.NetworkRepository, factory resource.ResourceFactory) *AzurermPublicIPEnumerator {
return &AzurermPublicIPEnumerator{
repository: repo,
factory: factory,
}
}
func (e *AzurermPublicIPEnumerator) SupportedType() resource.ResourceType {
return azurerm.AzurePublicIPResourceType
}
func (e *AzurermPublicIPEnumerator) Enumerate() ([]*resource.Resource, error) {
resources, err := e.repository.ListAllPublicIPAddresses()
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

@ -59,6 +59,7 @@ func Init(
remoteLibrary.AddEnumerator(NewAzurermContainerRegistryEnumerator(containerRegistryRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermFirewallsEnumerator(networkRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermPostgresqlServerEnumerator(postgresqlRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermPublicIPEnumerator(networkRepo, factory))
err = resourceSchemaRepository.Init(terraform.AZURE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -35,6 +35,29 @@ func (_m *MockNetworkRepository) ListAllFirewalls() ([]*armnetwork.AzureFirewall
return r0, r1
}
// ListAllPublicIPAddresses provides a mock function with given fields:
func (_m *MockNetworkRepository) ListAllPublicIPAddresses() ([]*armnetwork.PublicIPAddress, error) {
ret := _m.Called()
var r0 []*armnetwork.PublicIPAddress
if rf, ok := ret.Get(0).(func() []*armnetwork.PublicIPAddress); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*armnetwork.PublicIPAddress)
}
}
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()

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"
)
// mockPublicIPAddressesClient is an autogenerated mock type for the publicIPAddressesClient type
type mockPublicIPAddressesClient struct {
mock.Mock
}
// ListAll provides a mock function with given fields: options
func (_m *mockPublicIPAddressesClient) ListAll(options *armnetwork.PublicIPAddressesListAllOptions) publicIPAddressesListAllPager {
ret := _m.Called(options)
var r0 publicIPAddressesListAllPager
if rf, ok := ret.Get(0).(func(*armnetwork.PublicIPAddressesListAllOptions) publicIPAddressesListAllPager); ok {
r0 = rf(options)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(publicIPAddressesListAllPager)
}
}
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"
)
// mockPublicIPAddressesListAllPager is an autogenerated mock type for the publicIPAddressesListAllPager type
type mockPublicIPAddressesListAllPager struct {
mock.Mock
}
// Err provides a mock function with given fields:
func (_m *mockPublicIPAddressesListAllPager) 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 *mockPublicIPAddressesListAllPager) 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 *mockPublicIPAddressesListAllPager) PageResponse() armnetwork.PublicIPAddressesListAllResponse {
ret := _m.Called()
var r0 armnetwork.PublicIPAddressesListAllResponse
if rf, ok := ret.Get(0).(func() armnetwork.PublicIPAddressesListAllResponse); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(armnetwork.PublicIPAddressesListAllResponse)
}
return r0
}

View File

@ -16,6 +16,24 @@ type NetworkRepository interface {
ListAllRouteTables() ([]*armnetwork.RouteTable, error)
ListAllSubnets(virtualNetwork *armnetwork.VirtualNetwork) ([]*armnetwork.Subnet, error)
ListAllFirewalls() ([]*armnetwork.AzureFirewall, error)
ListAllPublicIPAddresses() ([]*armnetwork.PublicIPAddress, error)
}
type publicIPAddressesClient interface {
ListAll(options *armnetwork.PublicIPAddressesListAllOptions) publicIPAddressesListAllPager
}
type publicIPAddressesListAllPager interface {
pager
PageResponse() armnetwork.PublicIPAddressesListAllResponse
}
type publicIPAddressesClientImpl struct {
client *armnetwork.PublicIPAddressesClient
}
func (p publicIPAddressesClientImpl) ListAll(options *armnetwork.PublicIPAddressesListAllOptions) publicIPAddressesListAllPager {
return p.client.ListAll(options)
}
type firewallsListAllPager interface {
@ -87,11 +105,12 @@ func (c routeTablesClientImpl) ListAll(options *armnetwork.RouteTablesListAllOpt
}
type networkRepository struct {
virtualNetworksClient virtualNetworksClient
routeTableClient routeTablesClient
subnetsClient subnetsClient
firewallsClient firewallsClient
cache cache.Cache
virtualNetworksClient virtualNetworksClient
routeTableClient routeTablesClient
subnetsClient subnetsClient
firewallsClient firewallsClient
publicIPAddressesClient publicIPAddressesClient
cache cache.Cache
}
func NewNetworkRepository(con *arm.Connection, config common.AzureProviderConfig, cache cache.Cache) *networkRepository {
@ -100,6 +119,7 @@ func NewNetworkRepository(con *arm.Connection, config common.AzureProviderConfig
&routeTablesClientImpl{client: armnetwork.NewRouteTablesClient(con, config.SubscriptionID)},
&subnetsClientImpl{client: armnetwork.NewSubnetsClient(con, config.SubscriptionID)},
&firewallsClientImpl{client: armnetwork.NewAzureFirewallsClient(con, config.SubscriptionID)},
&publicIPAddressesClientImpl{client: armnetwork.NewPublicIPAddressesClient(con, config.SubscriptionID)},
cache,
}
}
@ -217,3 +237,29 @@ func (s *networkRepository) ListAllFirewalls() ([]*armnetwork.AzureFirewall, err
return results, nil
}
func (s *networkRepository) ListAllPublicIPAddresses() ([]*armnetwork.PublicIPAddress, error) {
cacheKey := "ListAllPublicIPAddresses"
if v := s.cache.Get(cacheKey); v != nil {
return v.([]*armnetwork.PublicIPAddress), nil
}
pager := s.publicIPAddressesClient.ListAll(nil)
results := make([]*armnetwork.PublicIPAddress, 0)
for pager.NextPage(context.Background()) {
resp := pager.PageResponse()
if err := pager.Err(); err != nil {
return nil, err
}
results = append(results, resp.PublicIPAddressesListAllResult.PublicIPAddressListResult.Value...)
}
if err := pager.Err(); err != nil {
return nil, err
}
s.cache.Put(cacheKey, results)
return results, nil
}

View File

@ -722,3 +722,156 @@ func Test_ListAllFirewalls_Error(t *testing.T) {
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}
func Test_ListAllPublicIPAddresses_MultiplesResults(t *testing.T) {
expected := []*armnetwork.PublicIPAddress{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip2"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip3"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip4"),
},
},
}
fakeClient := &mockPublicIPAddressesClient{}
mockPager := &mockPublicIPAddressesListAllPager{}
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.PublicIPAddressesListAllResponse{
PublicIPAddressesListAllResult: armnetwork.PublicIPAddressesListAllResult{
PublicIPAddressListResult: armnetwork.PublicIPAddressListResult{
Value: expected[:2],
},
},
}).Times(1)
mockPager.On("PageResponse").Return(armnetwork.PublicIPAddressesListAllResponse{
PublicIPAddressesListAllResult: armnetwork.PublicIPAddressesListAllResult{
PublicIPAddressListResult: armnetwork.PublicIPAddressListResult{
Value: expected[2:],
},
},
}).Times(1)
fakeClient.On("ListAll", mock.Anything).Return(mockPager)
c := &cache.MockCache{}
c.On("Get", "ListAllPublicIPAddresses").Return(nil).Times(1)
c.On("Put", "ListAllPublicIPAddresses", expected).Return(true).Times(1)
s := &networkRepository{
publicIPAddressesClient: fakeClient,
cache: c,
}
got, err := s.ListAllPublicIPAddresses()
if err != nil {
t.Errorf("ListAllPublicIPAddresses() error = %v", err)
return
}
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
c.AssertExpectations(t)
if !reflect.DeepEqual(got, expected) {
t.Errorf("ListAllPublicIPAddresses() got = %v, want %v", got, expected)
}
}
func Test_ListAllPublicIPAddresses_MultiplesResults_WithCache(t *testing.T) {
expected := []*armnetwork.PublicIPAddress{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip1"),
},
},
}
fakeClient := &mockPublicIPAddressesClient{}
c := &cache.MockCache{}
c.On("Get", "ListAllPublicIPAddresses").Return(expected).Times(1)
s := &networkRepository{
publicIPAddressesClient: fakeClient,
cache: c,
}
got, err := s.ListAllPublicIPAddresses()
if err != nil {
t.Errorf("ListAllPublicIPAddresses() error = %v", err)
return
}
fakeClient.AssertExpectations(t)
c.AssertExpectations(t)
if !reflect.DeepEqual(got, expected) {
t.Errorf("ListAllPublicIPAddresses() got = %v, want %v", got, expected)
}
}
func Test_ListAllPublicIPAddresses_Error_OnPageResponse(t *testing.T) {
fakeClient := &mockPublicIPAddressesClient{}
expectedErr := errors.New("unexpected error")
mockPager := &mockPublicIPAddressesListAllPager{}
mockPager.On("Err").Return(expectedErr).Times(1)
mockPager.On("NextPage", mock.Anything).Return(true).Times(1)
mockPager.On("PageResponse").Return(armnetwork.PublicIPAddressesListAllResponse{}).Times(1)
fakeClient.On("ListAll", mock.Anything).Return(mockPager)
s := &networkRepository{
publicIPAddressesClient: fakeClient,
cache: cache.New(0),
}
got, err := s.ListAllPublicIPAddresses()
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}
func Test_ListAllPublicIPAddresses_Error(t *testing.T) {
fakeClient := &mockPublicIPAddressesClient{}
expectedErr := errors.New("unexpected error")
mockPager := &mockPublicIPAddressesListAllPager{}
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{
publicIPAddressesClient: fakeClient,
cache: cache.New(0),
}
got, err := s.ListAllPublicIPAddresses()
mockPager.AssertExpectations(t)
fakeClient.AssertExpectations(t)
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}

View File

@ -580,3 +580,96 @@ func TestAzurermFirewalls(t *testing.T) {
})
}
}
func TestAzurermPublicIP(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 public IP",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllPublicIPAddresses").Return([]*armnetwork.PublicIPAddress{}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
},
{
test: "error listing public IPs",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllPublicIPAddresses").Return(nil, dummyError)
},
wantErr: error2.NewResourceListingError(dummyError, resourceazure.AzurePublicIPResourceType),
},
{
test: "multiple public IP",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllPublicIPAddresses").Return([]*armnetwork.PublicIPAddress{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip1"), // Here we don't care to have a valid ID, it is for testing purpose only
Name: to.StringPtr("ip1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("ip2"),
Name: to.StringPtr("ip2"),
},
},
}, nil)
},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 2)
assert.Equal(t, got[0].ResourceId(), "ip1")
assert.Equal(t, got[0].ResourceType(), resourceazure.AzurePublicIPResourceType)
assert.Equal(t, got[1].ResourceId(), "ip2")
assert.Equal(t, got[1].ResourceType(), resourceazure.AzurePublicIPResourceType)
},
},
}
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.NewAzurermPublicIPEnumerator(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 AzurePublicIPResourceType = "azurerm_public_ip"
func initAzurePublicIPMetadata(resourceSchemaRepository resource.SchemaRepositoryInterface) {
resourceSchemaRepository.SetHumanReadableAttributesFunc(AzurePublicIPResourceType, 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_PublicIP(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/azurerm_public_ip"},
Args: []string{
"scan",
"--to", "azure+tf",
"--filter", "Type=='azurerm_public_ip'",
},
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

@ -10,4 +10,5 @@ func InitResourcesMetadata(resourceSchemaRepository resource.SchemaRepositoryInt
initAzureContainerRegistryMetadata(resourceSchemaRepository)
initAzureFirewallMetadata(resourceSchemaRepository)
initAzurePostgresqlServerMetadata(resourceSchemaRepository)
initAzurePublicIPMetadata(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,23 @@
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_public_ip" "example" {
name = "ip1"
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
allocation_method = "Static"
}

View File

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