Merge pull request #1128 from cloudskiff/feat/add_azurerm_network_security_group

Add azurerm_network_security_group resource
main
Elie 2021-10-19 11:15:56 +02:00 committed by GitHub
commit 5d8a127c38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 867 additions and 14 deletions

View File

@ -9,8 +9,10 @@ import (
"github.com/cloudskiff/driftctl/pkg/filter"
"github.com/cloudskiff/driftctl/pkg/output"
"github.com/cloudskiff/driftctl/pkg/remote/azurerm"
"github.com/cloudskiff/driftctl/pkg/remote/google"
resourceaws "github.com/cloudskiff/driftctl/pkg/resource/aws"
resourceazure "github.com/cloudskiff/driftctl/pkg/resource/azurerm"
resourcegithub "github.com/cloudskiff/driftctl/pkg/resource/github"
resourcegoogle "github.com/cloudskiff/driftctl/pkg/resource/google"
testresource "github.com/cloudskiff/driftctl/test/resource"
@ -410,6 +412,88 @@ func TestTerraformStateReader_Google_Resources(t *testing.T) {
}
}
func TestTerraformStateReader_Azure_Resources(t *testing.T) {
tests := []struct {
name string
dirName string
wantErr bool
}{
{name: "network security group", dirName: "azurerm_network_security_group", wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
progress := &output.MockProgress{}
progress.On("Inc").Return().Times(1)
progress.On("Stop").Return().Times(1)
shouldUpdate := tt.dirName == *goldenfile.Update
var realProvider *azurerm.AzureTerraformProvider
providerVersion := "2.71.0"
var err error
realProvider, err = azurerm.NewAzureTerraformProvider(providerVersion, progress, "")
if err != nil {
t.Fatal(err)
}
provider := terraform2.NewFakeTerraformProvider(realProvider)
if shouldUpdate {
err = realProvider.Init()
if err != nil {
t.Fatal(err)
}
provider.ShouldUpdate()
}
library := terraform.NewProviderLibrary()
library.AddProvider(terraform.AZURE, provider)
repo := testresource.InitFakeSchemaRepository(terraform.AZURE, providerVersion)
resourceazure.InitResourcesMetadata(repo)
factory := terraform.NewTerraformResourceFactory(repo)
r := &TerraformStateReader{
config: config.SupplierConfig{
Path: path.Join(goldenfile.GoldenFilePath, tt.dirName, "terraform.tfstate"),
},
library: library,
progress: progress,
deserializer: resource.NewDeserializer(factory),
}
got, err := r.Resources()
resGoldenName := goldenfile.ResultsFilename
if shouldUpdate {
unm, err := json.Marshal(got)
if err != nil {
panic(err)
}
goldenfile.WriteFile(tt.dirName, unm, resGoldenName)
}
file := goldenfile.ReadFile(tt.dirName, resGoldenName)
var want []interface{}
if err := json.Unmarshal(file, &want); err != nil {
panic(err)
}
if (err != nil) != tt.wantErr {
t.Errorf("Resources() error = %v, wantErr %v", err, tt.wantErr)
return
}
changelog, err := diff.Diff(convert(got), want)
if err != nil {
panic(err)
}
if len(changelog) > 0 {
for _, change := range changelog {
t.Errorf("%s got = %v, want %v", strings.Join(change.Path, "."), change.From, change.To)
}
}
})
}
}
func convert(got []*resource.Resource) []interface{} {
unm, err := json.Marshal(got)
if err != nil {

View File

@ -0,0 +1,48 @@
[
{
"Id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup1",
"Type": "azurerm_network_security_group",
"Attrs": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup1",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup1",
"resource_group_name": "example-resources",
"security_rule": [
{
"access": "Allow",
"description": "",
"destination_address_prefix": "*",
"destination_port_range": "*",
"direction": "Inbound",
"name": "test123",
"priority": 100,
"protocol": "Tcp",
"source_address_prefix": "*",
"source_port_range": "*"
}
],
"tags": {
"environment": "Production"
}
}
},
{
"Id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup2",
"Type": "azurerm_network_security_group",
"Attrs": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup2",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup2",
"resource_group_name": "example-resources"
}
},
{
"Id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources",
"Type": "azurerm_resource_group",
"Attrs": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources",
"location": "westeurope",
"name": "example-resources"
}
}
]

View File

@ -0,0 +1,119 @@
{
"version": 4,
"terraform_version": "0.15.5",
"serial": 362,
"lineage": "9566e18d-6080-4aa8-e9a6-4c38905cf68f",
"outputs": {},
"resources": [
{
"mode": "data",
"type": "azurerm_resource_group",
"name": "raphael-dev",
"provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/raphael-dev",
"location": "eastus",
"name": "raphael-dev",
"tags": {},
"timeouts": null
},
"sensitive_attributes": []
}
]
},
{
"mode": "managed",
"type": "azurerm_network_security_group",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup1",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup1",
"resource_group_name": "example-resources",
"security_rule": [
{
"access": "Allow",
"description": "",
"destination_address_prefix": "*",
"destination_address_prefixes": [],
"destination_application_security_group_ids": [],
"destination_port_range": "*",
"destination_port_ranges": [],
"direction": "Inbound",
"name": "test123",
"priority": 100,
"protocol": "Tcp",
"source_address_prefix": "*",
"source_address_prefixes": [],
"source_application_security_group_ids": [],
"source_port_range": "*",
"source_port_ranges": []
}
],
"tags": {
"environment": "Production"
},
"timeouts": null
},
"sensitive_attributes": [],
"private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoxODAwMDAwMDAwMDAwLCJkZWxldGUiOjE4MDAwMDAwMDAwMDAsInJlYWQiOjMwMDAwMDAwMDAwMCwidXBkYXRlIjoxODAwMDAwMDAwMDAwfX0=",
"dependencies": [
"azurerm_resource_group.example"
]
}
]
},
{
"mode": "managed",
"type": "azurerm_network_security_group",
"name": "example-1",
"provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup2",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup2",
"resource_group_name": "example-resources",
"security_rule": [],
"tags": null,
"timeouts": null
},
"sensitive_attributes": [],
"private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjoxODAwMDAwMDAwMDAwLCJkZWxldGUiOjE4MDAwMDAwMDAwMDAsInJlYWQiOjMwMDAwMDAwMDAwMCwidXBkYXRlIjoxODAwMDAwMDAwMDAwfX0=",
"dependencies": [
"azurerm_resource_group.example"
]
}
]
},
{
"mode": "managed",
"type": "azurerm_resource_group",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources",
"location": "westeurope",
"name": "example-resources",
"tags": {},
"timeouts": null
},
"sensitive_attributes": [],
"private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo1NDAwMDAwMDAwMDAwLCJkZWxldGUiOjU0MDAwMDAwMDAwMDAsInJlYWQiOjMwMDAwMDAwMDAwMCwidXBkYXRlIjo1NDAwMDAwMDAwMDAwfX0="
}
]
}
]
}

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 AzurermNetworkSecurityGroupEnumerator struct {
repository repository.NetworkRepository
factory resource.ResourceFactory
}
func NewAzurermNetworkSecurityGroupEnumerator(repo repository.NetworkRepository, factory resource.ResourceFactory) *AzurermNetworkSecurityGroupEnumerator {
return &AzurermNetworkSecurityGroupEnumerator{
repository: repo,
factory: factory,
}
}
func (e *AzurermNetworkSecurityGroupEnumerator) SupportedType() resource.ResourceType {
return azurerm.AzureNetworkSecurityGroupResourceType
}
func (e *AzurermNetworkSecurityGroupEnumerator) Enumerate() ([]*resource.Resource, error) {
securityGroups, err := e.repository.ListAllSecurityGroups()
if err != nil {
return nil, remoteerror.NewResourceListingErrorWithType(err, string(e.SupportedType()), azurerm.AzureNetworkSecurityGroupResourceType)
}
results := make([]*resource.Resource, 0, len(securityGroups))
for _, res := range securityGroups {
results = append(
results,
e.factory.CreateAbstractResource(
string(e.SupportedType()),
*res.ID,
map[string]interface{}{
"name": *res.Name,
},
),
)
}
return results, err
}

View File

@ -48,6 +48,7 @@ func Init(
postgresqlRepo := repository.NewPostgresqlRepository(con, providerConfig, c)
providerLibrary.AddProvider(terraform.AZURE, provider)
deserializer := resource.NewDeserializer(factory)
remoteLibrary.AddEnumerator(NewAzurermStorageAccountEnumerator(storageAccountRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermStorageContainerEnumerator(storageAccountRepo, factory))
@ -61,6 +62,8 @@ func Init(
remoteLibrary.AddEnumerator(NewAzurermPostgresqlServerEnumerator(postgresqlRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermPublicIPEnumerator(networkRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermPostgresqlDatabaseEnumerator(postgresqlRepo, factory))
remoteLibrary.AddEnumerator(NewAzurermNetworkSecurityGroupEnumerator(networkRepo, factory))
remoteLibrary.AddDetailsFetcher(azurerm.AzureNetworkSecurityGroupResourceType, common.NewGenericDetailsFetcher(azurerm.AzureNetworkSecurityGroupResourceType, provider, deserializer))
err = resourceSchemaRepository.Init(terraform.AZURE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -81,6 +81,29 @@ func (_m *MockNetworkRepository) ListAllRouteTables() ([]*armnetwork.RouteTable,
return r0, r1
}
// ListAllSecurityGroups provides a mock function with given fields:
func (_m *MockNetworkRepository) ListAllSecurityGroups() ([]*armnetwork.NetworkSecurityGroup, error) {
ret := _m.Called()
var r0 []*armnetwork.NetworkSecurityGroup
if rf, ok := ret.Get(0).(func() []*armnetwork.NetworkSecurityGroup); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*armnetwork.NetworkSecurityGroup)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// ListAllSubnets provides a mock function with given fields: virtualNetwork
func (_m *MockNetworkRepository) ListAllSubnets(virtualNetwork *armnetwork.VirtualNetwork) ([]*armnetwork.Subnet, error) {
ret := _m.Called(virtualNetwork)

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

View File

@ -17,6 +17,7 @@ type NetworkRepository interface {
ListAllSubnets(virtualNetwork *armnetwork.VirtualNetwork) ([]*armnetwork.Subnet, error)
ListAllFirewalls() ([]*armnetwork.AzureFirewall, error)
ListAllPublicIPAddresses() ([]*armnetwork.PublicIPAddress, error)
ListAllSecurityGroups() ([]*armnetwork.NetworkSecurityGroup, error)
}
type publicIPAddressesClient interface {
@ -104,13 +105,31 @@ func (c routeTablesClientImpl) ListAll(options *armnetwork.RouteTablesListAllOpt
return c.client.ListAll(options)
}
type networkSecurityGroupsListAllPager interface {
pager
PageResponse() armnetwork.NetworkSecurityGroupsListAllResponse
}
type networkSecurityGroupsClient interface {
ListAll(options *armnetwork.NetworkSecurityGroupsListAllOptions) networkSecurityGroupsListAllPager
}
type networkSecurityGroupsClientImpl struct {
client *armnetwork.NetworkSecurityGroupsClient
}
func (s networkSecurityGroupsClientImpl) ListAll(options *armnetwork.NetworkSecurityGroupsListAllOptions) networkSecurityGroupsListAllPager {
return s.client.ListAll(options)
}
type networkRepository struct {
virtualNetworksClient virtualNetworksClient
routeTableClient routeTablesClient
subnetsClient subnetsClient
firewallsClient firewallsClient
publicIPAddressesClient publicIPAddressesClient
cache cache.Cache
virtualNetworksClient virtualNetworksClient
routeTableClient routeTablesClient
subnetsClient subnetsClient
firewallsClient firewallsClient
publicIPAddressesClient publicIPAddressesClient
networkSecurityGroupsClient networkSecurityGroupsClient
cache cache.Cache
}
func NewNetworkRepository(con *arm.Connection, config common.AzureProviderConfig, cache cache.Cache) *networkRepository {
@ -120,6 +139,7 @@ func NewNetworkRepository(con *arm.Connection, config common.AzureProviderConfig
&subnetsClientImpl{client: armnetwork.NewSubnetsClient(con, config.SubscriptionID)},
&firewallsClientImpl{client: armnetwork.NewAzureFirewallsClient(con, config.SubscriptionID)},
&publicIPAddressesClientImpl{client: armnetwork.NewPublicIPAddressesClient(con, config.SubscriptionID)},
&networkSecurityGroupsClientImpl{client: armnetwork.NewNetworkSecurityGroupsClient(con, config.SubscriptionID)},
cache,
}
}
@ -263,3 +283,28 @@ func (s *networkRepository) ListAllPublicIPAddresses() ([]*armnetwork.PublicIPAd
return results, nil
}
func (s *networkRepository) ListAllSecurityGroups() ([]*armnetwork.NetworkSecurityGroup, error) {
cacheKey := "networkListAllSecurityGroups"
if v := s.cache.Get(cacheKey); v != nil {
return v.([]*armnetwork.NetworkSecurityGroup), nil
}
pager := s.networkSecurityGroupsClient.ListAll(nil)
results := make([]*armnetwork.NetworkSecurityGroup, 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(cacheKey, results)
return results, nil
}

View File

@ -1,6 +1,7 @@
package repository
import (
"context"
"fmt"
"reflect"
"testing"
@ -875,3 +876,96 @@ func Test_ListAllPublicIPAddresses_Error(t *testing.T) {
assert.Equal(t, expectedErr, err)
assert.Nil(t, got)
}
func Test_Network_ListAllSecurityGroups(t *testing.T) {
expectedResults := []*armnetwork.NetworkSecurityGroup{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("sgroup-1"),
Name: to.StringPtr("sgroup-1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("sgroup-2"),
Name: to.StringPtr("sgroup-2"),
},
},
}
testcases := []struct {
name string
mocks func(*mockNetworkSecurityGroupsListAllPager, *cache.MockCache)
expected []*armnetwork.NetworkSecurityGroup
wantErr string
}{
{
name: "should return security groups",
mocks: func(pager *mockNetworkSecurityGroupsListAllPager, mockCache *cache.MockCache) {
pager.On("NextPage", context.Background()).Return(true).Times(1)
pager.On("NextPage", context.Background()).Return(false).Times(1)
pager.On("PageResponse").Return(armnetwork.NetworkSecurityGroupsListAllResponse{
NetworkSecurityGroupsListAllResult: armnetwork.NetworkSecurityGroupsListAllResult{
NetworkSecurityGroupListResult: armnetwork.NetworkSecurityGroupListResult{
Value: expectedResults,
},
},
}).Times(1)
pager.On("Err").Return(nil).Times(2)
mockCache.On("Get", "networkListAllSecurityGroups").Return(nil).Times(1)
mockCache.On("Put", "networkListAllSecurityGroups", expectedResults).Return(false).Times(1)
},
expected: expectedResults,
},
{
name: "should hit cache and return security groups",
mocks: func(pager *mockNetworkSecurityGroupsListAllPager, mockCache *cache.MockCache) {
mockCache.On("Get", "networkListAllSecurityGroups").Return(expectedResults).Times(1)
},
expected: expectedResults,
},
{
name: "should return remote error",
mocks: func(pager *mockNetworkSecurityGroupsListAllPager, mockCache *cache.MockCache) {
pager.On("NextPage", context.Background()).Return(true).Times(1)
pager.On("NextPage", context.Background()).Return(false).Times(1)
pager.On("PageResponse").Return(armnetwork.NetworkSecurityGroupsListAllResponse{}).Times(1)
pager.On("Err").Return(errors.New("remote error")).Times(1)
mockCache.On("Get", "networkListAllSecurityGroups").Return(nil).Times(1)
},
wantErr: "remote error",
},
}
for _, tt := range testcases {
t.Run(tt.name, func(t *testing.T) {
fakePager := &mockNetworkSecurityGroupsListAllPager{}
fakeClient := &mockNetworkSecurityGroupsClient{}
mockCache := &cache.MockCache{}
fakeClient.On("ListAll", (*armnetwork.NetworkSecurityGroupsListAllOptions)(nil)).Return(fakePager).Maybe()
tt.mocks(fakePager, mockCache)
s := &networkRepository{
networkSecurityGroupsClient: fakeClient,
cache: mockCache,
}
got, err := s.ListAllSecurityGroups()
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.Nil(t, err)
}
fakeClient.AssertExpectations(t)
mockCache.AssertExpectations(t)
if !reflect.DeepEqual(got, tt.expected) {
t.Errorf("ListAllSecurityGroups() got = %v, want %v", got, tt.expected)
}
})
}
}

View File

@ -3,18 +3,24 @@ package remote
import (
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/network/armnetwork"
"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/cache"
"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"
"github.com/cloudskiff/driftctl/test"
"github.com/cloudskiff/driftctl/test/goldenfile"
testresource "github.com/cloudskiff/driftctl/test/resource"
terraform2 "github.com/cloudskiff/driftctl/test/terraform"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
@ -673,3 +679,113 @@ func TestAzurermPublicIP(t *testing.T) {
})
}
}
func TestAzurermSecurityGroups(t *testing.T) {
dummyError := errors.New("this is an error")
tests := []struct {
test string
dirName string
mocks func(*repository.MockNetworkRepository, *mocks.AlerterInterface)
wantErr error
}{
{
test: "no security group",
dirName: "azurerm_network_security_group_empty",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllSecurityGroups").Return([]*armnetwork.NetworkSecurityGroup{}, nil)
},
},
{
test: "error listing security groups",
dirName: "azurerm_network_security_group_empty",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllSecurityGroups").Return(nil, dummyError)
},
wantErr: error2.NewResourceListingError(dummyError, resourceazure.AzureNetworkSecurityGroupResourceType),
},
{
test: "multiple security groups",
dirName: "azurerm_network_security_group_multiple",
mocks: func(repository *repository.MockNetworkRepository, alerter *mocks.AlerterInterface) {
repository.On("ListAllSecurityGroups").Return([]*armnetwork.NetworkSecurityGroup{
{
Resource: armnetwork.Resource{
ID: to.StringPtr("/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup1"),
Name: to.StringPtr("acceptanceTestSecurityGroup1"),
},
},
{
Resource: armnetwork.Resource{
ID: to.StringPtr("/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup2"),
Name: to.StringPtr("acceptanceTestSecurityGroup2"),
},
},
}, nil)
},
},
}
providerVersion := "2.71.0"
schemaRepository := testresource.InitFakeSchemaRepository("azurerm", providerVersion)
resourceazure.InitResourcesMetadata(schemaRepository)
factory := terraform.NewTerraformResourceFactory(schemaRepository)
deserializer := resource.NewDeserializer(factory)
for _, c := range tests {
t.Run(c.test, func(tt *testing.T) {
shouldUpdate := c.dirName == *goldenfile.Update
scanOptions := ScannerOptions{Deep: true}
providerLibrary := terraform.NewProviderLibrary()
remoteLibrary := common.NewRemoteLibrary()
// Initialize mocks
alerter := &mocks.AlerterInterface{}
fakeRepo := &repository.MockNetworkRepository{}
c.mocks(fakeRepo, alerter)
var repo repository.NetworkRepository = fakeRepo
providerVersion := "2.71.0"
realProvider, err := terraform2.InitTestAzureProvider(providerLibrary, providerVersion)
if err != nil {
t.Fatal(err)
}
provider := terraform2.NewFakeTerraformProvider(realProvider)
provider.WithResponse(c.dirName)
// Replace mock by real resources if we are in update mode
if shouldUpdate {
err := realProvider.Init()
if err != nil {
t.Fatal(err)
}
provider.ShouldUpdate()
cred, err := azidentity.NewDefaultAzureCredential(&azidentity.DefaultAzureCredentialOptions{})
if err != nil {
t.Fatal(err)
}
con := arm.NewDefaultConnection(cred, nil)
repo = repository.NewNetworkRepository(con, realProvider.GetConfig(), cache.New(0))
}
remoteLibrary.AddEnumerator(azurerm.NewAzurermNetworkSecurityGroupEnumerator(repo, factory))
remoteLibrary.AddDetailsFetcher(resourceazure.AzureNetworkSecurityGroupResourceType, common.NewGenericDetailsFetcher(resourceazure.AzureNetworkSecurityGroupResourceType, provider, deserializer))
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
}
test.TestAgainstGoldenFile(got, resourceazure.AzureNetworkSecurityGroupResourceType, c.dirName, provider, deserializer, shouldUpdate, tt)
alerter.AssertExpectations(tt)
fakeRepo.AssertExpectations(tt)
})
}
}

View File

@ -0,0 +1,5 @@
{
"Typ": "WyJvYmplY3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": "eyJpZCI6Ii9zdWJzY3JpcHRpb25zLzdiZmIyYzVjLTczMDgtNDZlZC04YWU0LWZmZmEzNTZlYjQwNi9yZXNvdXJjZUdyb3Vwcy9leGFtcGxlLXJlc291cmNlcy9wcm92aWRlcnMvTWljcm9zb2Z0Lk5ldHdvcmsvbmV0d29ya1NlY3VyaXR5R3JvdXBzL2FjY2VwdGFuY2VUZXN0U2VjdXJpdHlHcm91cDIiLCJsb2NhdGlvbiI6Indlc3RldXJvcGUiLCJuYW1lIjoiYWNjZXB0YW5jZVRlc3RTZWN1cml0eUdyb3VwMiIsInJlc291cmNlX2dyb3VwX25hbWUiOiJleGFtcGxlLXJlc291cmNlcyIsInNlY3VyaXR5X3J1bGUiOltdLCJ0YWdzIjp7fSwidGltZW91dHMiOnsiY3JlYXRlIjpudWxsLCJkZWxldGUiOm51bGwsInJlYWQiOm51bGwsInVwZGF0ZSI6bnVsbH19",
"Err": null
}

View File

@ -0,0 +1,41 @@
[
{
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup2",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup2",
"resource_group_name": "example-resources",
"security_rule": null,
"tags": null,
"timeouts": null
},
{
"id": "/subscriptions/7bfb2c5c-7308-46ed-8ae4-fffa356eb406/resourceGroups/example-resources/providers/Microsoft.Network/networkSecurityGroups/acceptanceTestSecurityGroup1",
"location": "westeurope",
"name": "acceptanceTestSecurityGroup1",
"resource_group_name": "example-resources",
"security_rule": [
{
"access": "Allow",
"description": "",
"destination_address_prefix": "*",
"destination_address_prefixes": null,
"destination_application_security_group_ids": null,
"destination_port_range": "*",
"destination_port_ranges": null,
"direction": "Inbound",
"name": "test123",
"priority": 100,
"protocol": "Tcp",
"source_address_prefix": "*",
"source_address_prefixes": null,
"source_application_security_group_ids": null,
"source_port_range": "*",
"source_port_ranges": null
}
],
"tags": {
"environment": "Production"
},
"timeouts": null
}
]

View File

@ -0,0 +1,20 @@
package azurerm
import "github.com/cloudskiff/driftctl/pkg/resource"
const AzureNetworkSecurityGroupResourceType = "azurerm_network_security_group"
func initAzureNetworkSecurityGroupMetadata(resourceSchemaRepository resource.SchemaRepositoryInterface) {
resourceSchemaRepository.SetNormalizeFunc(AzureNetworkSecurityGroupResourceType, func(res *resource.Resource) {
res.Attributes().SafeDelete([]string{"timeouts"})
})
resourceSchemaRepository.SetHumanReadableAttributesFunc(AzureNetworkSecurityGroupResourceType, 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
})
resourceSchemaRepository.SetFlags(AzureNetworkSecurityGroupResourceType, resource.FlagDeepMode)
}

View File

@ -0,0 +1,32 @@
package azurerm_test
import (
"testing"
"github.com/cloudskiff/driftctl/test"
"github.com/cloudskiff/driftctl/test/acceptance"
)
func TestAcc_Azure_NetworkSecurityGroup(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/azurerm_network_security_group"},
Args: []string{
"scan",
"--to", "azure+tf",
"--filter", "contains(Id, 'acceptanceTestSecurityGroup-')",
"--deep",
},
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

@ -12,4 +12,5 @@ func InitResourcesMetadata(resourceSchemaRepository resource.SchemaRepositoryInt
initAzurePostgresqlServerMetadata(resourceSchemaRepository)
initAzurePublicIPMetadata(resourceSchemaRepository)
initAzurePostgresqlDatabaseMetadata(resourceSchemaRepository)
initAzureNetworkSecurityGroupMetadata(resourceSchemaRepository)
}

View File

@ -0,0 +1,2 @@
*
!azurerm_network_security_group

View File

@ -0,0 +1,39 @@
# 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",
]
}
provider "registry.terraform.io/hashicorp/random" {
version = "3.1.0"
hashes = [
"h1:BZMEPucF+pbu9gsPk0G0BHx7YP04+tKdq2MrRDF1EDM=",
"zh:2bbb3339f0643b5daa07480ef4397bd23a79963cc364cdfbb4e86354cb7725bc",
"zh:3cd456047805bf639fbf2c761b1848880ea703a054f76db51852008b11008626",
"zh:4f251b0eda5bb5e3dc26ea4400dba200018213654b69b4a5f96abee815b4f5ff",
"zh:7011332745ea061e517fe1319bd6c75054a314155cb2c1199a5b01fe1889a7e2",
"zh:738ed82858317ccc246691c8b85995bc125ac3b4143043219bd0437adc56c992",
"zh:7dbe52fac7bb21227acd7529b487511c91f4107db9cc4414f50d04ffc3cab427",
"zh:a3a9251fb15f93e4cfc1789800fc2d7414bbc18944ad4c5c98f466e6477c42bc",
"zh:a543ec1a3a8c20635cf374110bd2f87c07374cf2c50617eee2c669b3ceeeaa9f",
"zh:d9ab41d556a48bd7059f0810cf020500635bfc696c9fc3adab5ea8915c1d886b",
"zh:d9e13427a7d011dbd654e591b0337e6074eef8c3b9bb11b2e39eaaf257044fd7",
"zh:f7605bd1437752114baf601bdf6931debe6dc6bfe3006eb7e9bb9080931dca8a",
]
}

View File

@ -0,0 +1,40 @@
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.71.0"
}
}
}
provider "azurerm" {
features {}
}
data "azurerm_resource_group" "default" {
name = "driftctl-qa-1"
}
resource "random_string" "suffix" {
length = 12
upper = false
special = false
}
resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup-${random_string.suffix.result}"
location = data.azurerm_resource_group.default.location
resource_group_name = data.azurerm_resource_group.default.name
security_rule {
name = "test123"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}

View File

@ -151,14 +151,15 @@ var supportedTypes = map[string]ResourceTypeMeta{
"azurerm_route_table": {children: []ResourceType{
"azurerm_route",
}},
"azurerm_route": {},
"azurerm_resource_group": {},
"azurerm_subnet": {},
"azurerm_container_registry": {},
"azurerm_firewall": {},
"azurerm_postgresql_server": {},
"azurerm_postgresql_database": {},
"azurerm_public_ip": {},
"azurerm_route": {},
"azurerm_resource_group": {},
"azurerm_subnet": {},
"azurerm_container_registry": {},
"azurerm_firewall": {},
"azurerm_postgresql_server": {},
"azurerm_postgresql_database": {},
"azurerm_public_ip": {},
"azurerm_network_security_group": {},
}
func IsResourceTypeSupported(ty string) bool {