feat: add google_compute_instance_group_manager

main
sundowndev-snyk 2022-03-24 15:25:50 +04:00
parent c3bc383be5
commit 9f4cf99e32
19 changed files with 718 additions and 34 deletions

View File

@ -126,6 +126,7 @@ func (d DriftCTL) Run() (*analyser.Analysis, error) {
middlewares.NewGoogleIAMBindingTransformer(d.resourceFactory),
middlewares.NewGoogleIAMPolicyTransformer(d.resourceFactory),
middlewares.NewGoogleComputeInstanceGroupManagerInstances(),
middlewares.NewAzurermRouteExpander(d.resourceFactory),
middlewares.NewAzurermSubnetExpander(d.resourceFactory),

View File

@ -378,6 +378,7 @@ func TestTerraformStateReader_Google_Resources(t *testing.T) {
{name: "cloudrun service", dirName: "google_cloudrun_service", wantErr: false},
{name: "compute node group", dirName: "google_compute_node_group", wantErr: false},
{name: "compute forwarding rule", dirName: "google_compute_forwarding_rule", wantErr: false},
{name: "compute instance group manager", dirName: "google_compute_instance_group_manager", wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

View File

@ -0,0 +1,70 @@
[
{
"Id": "projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-igm",
"Type": "google_compute_instance_group_manager",
"Attrs": {
"auto_healing_policies": [
{
"health_check": "https://www.googleapis.com/compute/beta/projects/cloudskiff-dev-raphael/global/healthChecks/autohealing-health-check",
"initial_delay_sec": 300
}
],
"base_instance_name": "app",
"description": "",
"fingerprint": "0ZOcDOzIVtg=",
"id": "projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-igm",
"instance_group": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroups/appserver-igm",
"name": "appserver-igm",
"named_port": [
{
"name": "customhttp",
"port": 8888
}
],
"project": "cloudskiff-dev-raphael",
"self_link": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-igm",
"status": [
{
"is_stable": false,
"stateful": [
{
"has_stateful_config": false,
"per_instance_configs": [
{
"all_effective": true
}
]
}
],
"version_target": [
{
"is_reached": true
}
]
}
],
"target_size": 2,
"update_policy": [
{
"max_surge_fixed": 1,
"max_surge_percent": 0,
"max_unavailable_fixed": 1,
"max_unavailable_percent": 0,
"min_ready_sec": 0,
"minimal_action": "REPLACE",
"replacement_method": "SUBSTITUTE",
"type": "OPPORTUNISTIC"
}
],
"version": [
{
"instance_template": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/global/instanceTemplates/instance-template-21879620220309131441473100000001",
"name": ""
}
],
"wait_for_instances": false,
"wait_for_instances_status": "STABLE",
"zone": "us-central1-a"
}
}
]

View File

@ -0,0 +1,95 @@
{
"version": 4,
"terraform_version": "1.0.0",
"serial": 425,
"lineage": "9566e18d-6080-4aa8-e9a6-4c38905cf68f",
"outputs": {},
"resources": [
{
"mode": "managed",
"type": "google_compute_instance_group_manager",
"name": "appserver",
"provider": "provider[\"registry.terraform.io/hashicorp/google\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"auto_healing_policies": [
{
"health_check": "https://www.googleapis.com/compute/beta/projects/cloudskiff-dev-raphael/global/healthChecks/autohealing-health-check",
"initial_delay_sec": 300
}
],
"base_instance_name": "app",
"description": "",
"fingerprint": "0ZOcDOzIVtg=",
"id": "projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-igm",
"instance_group": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroups/appserver-igm",
"name": "appserver-igm",
"named_port": [
{
"name": "customhttp",
"port": 8888
}
],
"operation": null,
"project": "cloudskiff-dev-raphael",
"self_link": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-igm",
"stateful_disk": [],
"status": [
{
"is_stable": false,
"stateful": [
{
"has_stateful_config": false,
"per_instance_configs": [
{
"all_effective": true
}
]
}
],
"version_target": [
{
"is_reached": true
}
]
}
],
"target_pools": null,
"target_size": 2,
"timeouts": null,
"update_policy": [
{
"max_surge_fixed": 1,
"max_surge_percent": 0,
"max_unavailable_fixed": 1,
"max_unavailable_percent": 0,
"min_ready_sec": 0,
"minimal_action": "REPLACE",
"replacement_method": "SUBSTITUTE",
"type": "OPPORTUNISTIC"
}
],
"version": [
{
"instance_template": "https://www.googleapis.com/compute/v1/projects/cloudskiff-dev-raphael/global/instanceTemplates/instance-template-21879620220309131441473100000001",
"name": "",
"target_size": []
}
],
"wait_for_instances": false,
"wait_for_instances_status": "STABLE",
"zone": "us-central1-a"
},
"sensitive_attributes": [],
"private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo5MDAwMDAwMDAwMDAsImRlbGV0ZSI6OTAwMDAwMDAwMDAwLCJ1cGRhdGUiOjkwMDAwMDAwMDAwMH19",
"dependencies": [
"google_compute_health_check.autohealing",
"google_compute_instance_template.appserver"
]
}
]
}
]
}

View File

@ -0,0 +1,50 @@
package middlewares
import (
"github.com/snyk/driftctl/pkg/resource"
"github.com/snyk/driftctl/pkg/resource/google"
)
type GoogleComputeInstanceGroupManagerInstances struct{}
// NewGoogleComputeInstanceGroupManagerInstances imports remote instance groups when they're managed by a managed instance group manager.
// Creating a "google_compute_instance_group_manager" resource via Terraform leads to having several unmanaged instance groups.
// This middleware adds remote instance groups to the state by matching them with managed instance group managers.
func NewGoogleComputeInstanceGroupManagerInstances() *GoogleComputeInstanceGroupManagerInstances {
return &GoogleComputeInstanceGroupManagerInstances{}
}
func (a GoogleComputeInstanceGroupManagerInstances) Execute(remoteResources, resourcesFromState *[]*resource.Resource) error {
var newStateResources []*resource.Resource
instanceGroups := make([]*resource.Resource, 0)
for _, remoteResource := range *remoteResources {
// Ignore all resources other than google_compute_instance_group
if remoteResource.ResourceType() != google.GoogleComputeInstanceGroupResourceType {
continue
}
instanceGroups = append(instanceGroups, remoteResource)
}
for _, stateResource := range *resourcesFromState {
newStateResources = append(newStateResources, stateResource)
// Ignore all resources other than google_compute_instance_group_manager
if stateResource.ResourceType() != google.GoogleComputeInstanceGroupManagerResourceType {
continue
}
name := stateResource.Attributes().GetString("name")
for _, group := range instanceGroups {
// Import instance group in the state
if n := group.Attributes().GetString("name"); n != nil && *n == *name {
newStateResources = append(newStateResources, group)
}
}
}
*resourcesFromState = newStateResources
return nil
}

View File

@ -0,0 +1,93 @@
package middlewares
import (
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/r3labs/diff/v2"
"github.com/snyk/driftctl/pkg/resource"
"github.com/snyk/driftctl/pkg/resource/google"
)
func TestGoogleComputeInstanceGroupManagerExpander_Execute(t *testing.T) {
tests := []struct {
name string
remoteResources []*resource.Resource
resourcesFromState []*resource.Resource
expected []*resource.Resource
}{
{
name: "test that we import compute instance group in the state",
remoteResources: []*resource.Resource{
{
Id: "appserver-igm",
Type: google.GoogleComputeInstanceGroupManagerResourceType,
Attrs: &resource.Attributes{
"name": "appserver-igm",
},
},
{
Id: "appserver-igm",
Type: google.GoogleComputeInstanceGroupResourceType,
Attrs: &resource.Attributes{
"name": "appserver-igm",
},
},
},
resourcesFromState: []*resource.Resource{
{
Id: "appserver-igm",
Type: google.GoogleComputeInstanceGroupManagerResourceType,
Attrs: &resource.Attributes{
"name": "appserver-igm",
},
},
{
Id: "fake",
Type: google.GoogleComputeInstanceResourceType,
Attrs: &resource.Attributes{},
},
},
expected: []*resource.Resource{
{
Id: "appserver-igm",
Type: google.GoogleComputeInstanceGroupManagerResourceType,
Attrs: &resource.Attributes{
"name": "appserver-igm",
},
},
{
Id: "appserver-igm",
Type: google.GoogleComputeInstanceGroupResourceType,
Attrs: &resource.Attributes{
"name": "appserver-igm",
},
},
{
Id: "fake",
Type: google.GoogleComputeInstanceResourceType,
Attrs: &resource.Attributes{},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := NewGoogleComputeInstanceGroupManagerInstances()
err := m.Execute(&tt.remoteResources, &tt.resourcesFromState)
if err != nil {
t.Fatal(err)
}
changelog, err := diff.Diff(tt.expected, tt.resourcesFromState)
if err != nil {
t.Fatal(err)
}
if len(changelog) > 0 {
for _, change := range changelog {
t.Errorf("%s got = %v, want %v", strings.Join(change.Path, "."), awsutil.Prettify(change.From), awsutil.Prettify(change.To))
}
}
})
}
}

View File

@ -0,0 +1,56 @@
package google
import (
"strings"
"github.com/sirupsen/logrus"
remoteerror "github.com/snyk/driftctl/pkg/remote/error"
"github.com/snyk/driftctl/pkg/remote/google/repository"
"github.com/snyk/driftctl/pkg/resource"
"github.com/snyk/driftctl/pkg/resource/google"
)
type GoogleComputeInstanceGroupManagerEnumerator struct {
repository repository.AssetRepository
factory resource.ResourceFactory
}
func NewGoogleComputeInstanceGroupManagerEnumerator(repo repository.AssetRepository, factory resource.ResourceFactory) *GoogleComputeInstanceGroupManagerEnumerator {
return &GoogleComputeInstanceGroupManagerEnumerator{
repository: repo,
factory: factory,
}
}
func (e *GoogleComputeInstanceGroupManagerEnumerator) SupportedType() resource.ResourceType {
return google.GoogleComputeInstanceGroupManagerResourceType
}
func (e *GoogleComputeInstanceGroupManagerEnumerator) Enumerate() ([]*resource.Resource, error) {
items, err := e.repository.SearchAllInstanceGroupManagers()
if err != nil {
return nil, remoteerror.NewResourceListingError(err, string(e.SupportedType()))
}
results := make([]*resource.Resource, 0, len(items))
for _, res := range items {
splittedName := strings.Split(res.GetName(), "/")
if len(splittedName) != 9 {
logrus.WithField("name", res.GetName()).Error("Unable to decode project from instance group name")
continue
}
name := splittedName[8]
results = append(
results,
e.factory.CreateAbstractResource(
string(e.SupportedType()),
trimResourceName(res.GetName()),
map[string]interface{}{
"name": name,
},
),
)
}
return results, err
}

View File

@ -100,6 +100,7 @@ func Init(version string, alerter *alerter.Alerter,
remoteLibrary.AddEnumerator(NewGoogleCloudRunServiceEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeNodeGroupEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeForwardingRuleEnumerator(assetRepository, factory))
remoteLibrary.AddEnumerator(NewGoogleComputeInstanceGroupManagerEnumerator(assetRepository, factory))
err = resourceSchemaRepository.Init(terraform.GOOGLE, provider.Version(), provider.Schema())
if err != nil {

View File

@ -35,6 +35,7 @@ const (
cloudRunServiceAssetType = "run.googleapis.com/Service"
nodeGroupAssetType = "compute.googleapis.com/NodeGroup"
computeForwardingRuleAssetType = "compute.googleapis.com/ForwardingRule"
instanceGroupManagerAssetType = "compute.googleapis.com/InstanceGroupManager"
)
type AssetRepository interface {
@ -60,6 +61,7 @@ type AssetRepository interface {
SearchAllCloudRunServices() ([]*assetpb.ResourceSearchResult, error)
SearchAllNodeGroups() ([]*assetpb.Asset, error)
SearchAllForwardingRules() ([]*assetpb.Asset, error)
SearchAllInstanceGroupManagers() ([]*assetpb.Asset, error)
}
type assetRepository struct {
@ -88,6 +90,7 @@ func (s assetRepository) listAllResources(ty string) ([]*assetpb.Asset, error) {
computeGlobalAddressAssetType,
nodeGroupAssetType,
computeForwardingRuleAssetType,
instanceGroupManagerAssetType,
},
}
var results []*assetpb.Asset
@ -266,3 +269,7 @@ func (s assetRepository) SearchAllNodeGroups() ([]*assetpb.Asset, error) {
func (s assetRepository) SearchAllForwardingRules() ([]*assetpb.Asset, error) {
return s.listAllResources(computeForwardingRuleAssetType)
}
func (s assetRepository) SearchAllInstanceGroupManagers() ([]*assetpb.Asset, error) {
return s.listAllResources(instanceGroupManagerAssetType)
}

View File

@ -334,6 +334,29 @@ func (_m *MockAssetRepository) SearchAllImages() ([]*asset.ResourceSearchResult,
return r0, r1
}
// SearchAllInstanceGroupManagers provides a mock function with given fields:
func (_m *MockAssetRepository) SearchAllInstanceGroupManagers() ([]*asset.Asset, error) {
ret := _m.Called()
var r0 []*asset.Asset
if rf, ok := ret.Get(0).(func() []*asset.Asset); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*asset.Asset)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// SearchAllInstanceGroups provides a mock function with given fields:
func (_m *MockAssetRepository) SearchAllInstanceGroups() ([]*asset.ResourceSearchResult, error) {
ret := _m.Called()

View File

@ -1542,3 +1542,113 @@ func TestGoogleComputeForwardingRule(t *testing.T) {
})
}
}
func TestGoogleComputeInstanceGroupManager(t *testing.T) {
cases := []struct {
test string
assertExpected func(t *testing.T, got []*resource.Resource)
response []*assetpb.Asset
responseErr error
setupAlerterMock func(alerter *mocks.AlerterInterface)
wantErr error
}{
{
test: "no compute instance group manager",
response: []*assetpb.Asset{},
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
},
{
test: "multiples compute instance group managers",
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 2)
assert.Equal(t, "projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-abc", got[0].ResourceId())
assert.Equal(t, "google_compute_instance_group_manager", got[0].ResourceType())
assert.Equal(t, "projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-def", got[1].ResourceId())
assert.Equal(t, "google_compute_instance_group_manager", got[1].ResourceType())
},
response: []*assetpb.Asset{
{
AssetType: "compute.googleapis.com/InstanceGroupManager",
Name: "//compute.googleapis.com/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-abc",
},
{
AssetType: "compute.googleapis.com/InstanceGroupManager",
Name: "//compute.googleapis.com/projects/cloudskiff-dev-raphael/zones/us-central1-a/instanceGroupManagers/appserver-def",
},
},
},
{
test: "cannot list compute instance group managers",
assertExpected: func(t *testing.T, got []*resource.Resource) {
assert.Len(t, got, 0)
},
responseErr: status.Error(codes.PermissionDenied, "The caller does not have permission"),
setupAlerterMock: func(alerter *mocks.AlerterInterface) {
alerter.On(
"SendAlert",
"google_compute_instance_group_manager",
alerts.NewRemoteAccessDeniedAlert(
common.RemoteGoogleTerraform,
remoteerr.NewResourceListingError(
status.Error(codes.PermissionDenied, "The caller does not have permission"),
"google_compute_instance_group_manager",
),
alerts.EnumerationPhase,
),
).Once()
},
},
}
providerVersion := "3.78.0"
schemaRepository := testresource.InitFakeSchemaRepository(terraform.GOOGLE, providerVersion)
googleresource.InitResourcesMetadata(schemaRepository)
factory := terraform.NewTerraformResourceFactory(schemaRepository)
for _, c := range cases {
t.Run(c.test, func(tt *testing.T) {
scanOptions := ScannerOptions{}
providerLibrary := terraform.NewProviderLibrary()
remoteLibrary := common.NewRemoteLibrary()
// Initialize mocks
alerter := &mocks.AlerterInterface{}
if c.setupAlerterMock != nil {
c.setupAlerterMock(alerter)
}
assetClient, err := testgoogle.NewFakeAssertServerWithList(c.response, c.responseErr)
if err != nil {
tt.Fatal(err)
}
realProvider, err := terraform2.InitTestGoogleProvider(providerLibrary, providerVersion)
if err != nil {
tt.Fatal(err)
}
repo := repository.NewAssetRepository(assetClient, realProvider.GetConfig(), cache.New(0))
remoteLibrary.AddEnumerator(google.NewGoogleComputeInstanceGroupManagerEnumerator(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, err, c.wantErr)
if err != nil {
return
}
alerter.AssertExpectations(tt)
testFilter.AssertExpectations(tt)
if c.assertExpected != nil {
c.assertExpected(t, got)
}
})
}
}

View File

@ -0,0 +1,15 @@
package google
import "github.com/snyk/driftctl/pkg/resource"
const GoogleComputeInstanceGroupManagerResourceType = "google_compute_instance_group_manager"
func initComputeInstanceGroupManagerMetadata(resourceSchemaRepository resource.SchemaRepositoryInterface) {
resourceSchemaRepository.SetHumanReadableAttributesFunc(GoogleComputeInstanceGroupManagerResourceType, func(res *resource.Resource) map[string]string {
attrs := make(map[string]string)
if v := res.Attributes().GetString("name"); v != nil && *v != "" {
attrs["Name"] = *v
}
return attrs
})
}

View File

@ -0,0 +1,33 @@
package google_test
import (
"testing"
"time"
"github.com/snyk/driftctl/test"
"github.com/snyk/driftctl/test/acceptance"
)
func TestAcc_Google_ComputeInstanceGroupManager(t *testing.T) {
acceptance.Run(t, acceptance.AccTestCase{
TerraformVersion: "0.15.5",
Paths: []string{"./testdata/acc/google_compute_instance_group_manager"},
Args: []string{
"scan",
"--to", "gcp+tf",
},
Checks: []acceptance.AccCheck{
{
// New resources are not visible immediately through GCP API after an apply operation.
ShouldRetry: acceptance.LinearBackoff(15 * time.Minute),
Check: func(result *test.ScanResult, stdout string, err error) {
if err != nil {
t.Fatal(err)
}
result.AssertInfrastructureIsInSync()
result.AssertManagedCount(1)
},
},
},
})
}

View File

@ -32,6 +32,7 @@ func TestGoogle_Metadata_Flags(t *testing.T) {
GoogleCloudRunServiceResourceType: {},
GoogleComputeNodeGroupResourceType: {},
GoogleComputeForwardingRuleResourceType: {},
GoogleComputeInstanceGroupManagerResourceType: {},
}
schemaRepository := testresource.InitFakeSchemaRepository(tf.GOOGLE, "3.78.0")

View File

@ -18,4 +18,5 @@ func InitResourcesMetadata(resourceSchemaRepository resource.SchemaRepositoryInt
initGoogleComputeDiskMetadata(resourceSchemaRepository)
initGoogleComputeImageMetadata(resourceSchemaRepository)
initGoogleComputeHealthCheckMetadata(resourceSchemaRepository)
initComputeInstanceGroupManagerMetadata(resourceSchemaRepository)
}

View File

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

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/google" {
version = "3.78.0"
constraints = "3.78.0"
hashes = [
"h1:iCyTW8BWdr6Bvd5B89wkxlrB8xLxqHvT1CPmGuKembU=",
"zh:027971c4689b6130619827fe57ce260aaca060db3446817d3a92869dba7cc07f",
"zh:0876dbecc0d441bf2479edd17fe9141d77274b5071ea5f68ac26a2994bff66f3",
"zh:2a5363ed6b1b880f5284e604567cfdabecca809584c30bbe7f19ff568d1ea4cd",
"zh:2f5af69b70654bda91199f6393253e3e479107deebfeddc3fe5850b3a1e83dfb",
"zh:52e6816ef11f5f799a6626dfff384e2153b37450d8320f1ef1eee8f71a2a87b2",
"zh:59ae534607db13db35c0015c06d1ae6d4886f01f7e8fd4e07bc120236a01c494",
"zh:65ab2ed1746ea02d0b1bbd8a22ff3a95d09dc8bdb3841fbc17e45e9feccfb327",
"zh:877a71d24ff65ede3f0c5973168acfeaea0f2fea3757cab5600efcddfd3171d5",
"zh:8b10c9643a4a53148f6758bfd60804b33c2b838482f2c39ed210b729e6b1e2e8",
"zh:ba682648d9f6c11a6d04a250ac79eec39271f615f3ff60c5ae73ebfcc2cdb450",
"zh:e946561921e0279450e9b9f705de9354ce35562ed4cc0d4cd3512aa9eb1f6486",
]
}
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,85 @@
provider "google" {}
terraform {
required_version = "~> 0.15.0"
required_providers {
google = {
version = "3.78.0"
}
}
}
resource "random_string" "net-id" {
length = 12
upper = false
special = false
}
resource "random_string" "group-id" {
length = 12
upper = false
special = false
}
resource "google_compute_network" "vpc_network" {
name = "vpc-network-${random_string.net-id.result}"
}
resource "google_compute_health_check" "autohealing" {
name = "autohealing-health-check-${random_string.group-id.result}"
check_interval_sec = 5
timeout_sec = 5
healthy_threshold = 2
unhealthy_threshold = 10 # 50 seconds
http_health_check {
request_path = "/healthz"
port = "8080"
}
}
resource "google_compute_instance_template" "appserver" {
name_prefix = "instance-template-${random_string.group-id.result}-"
machine_type = "e2-medium"
region = "us-central1"
// boot disk
disk {
source_image = "debian-cloud/debian-9"
auto_delete = true
boot = true
}
// networking
network_interface {
network = google_compute_network.vpc_network.name
}
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_instance_group_manager" "appserver" {
name = "appserver-igm-${random_string.group-id.result}"
base_instance_name = "app"
zone = "us-central1-a"
version {
instance_template = google_compute_instance_template.appserver.id
}
target_pools = []
target_size = 2
named_port {
name = "customhttp"
port = 8888
}
auto_healing_policies {
health_check = google_compute_health_check.autohealing.id
initial_delay_sec = 300
}
}

View File

@ -199,6 +199,7 @@ var supportedTypes = map[string]ResourceTypeMeta{
"google_compute_node_group": {},
"google_cloud_run_service": {},
"google_compute_forwarding_rule": {},
"google_compute_instance_group_manager": {},
"azurerm_storage_account": {},
"azurerm_storage_container": {},