Sign inSign up

bridgecrew/terraformer

By bridgecrew

โ€ขUpdated over 4 years ago

Image
1

1M+

bridgecrew/terraformer repository overview

โ Terraformer

Build Status Go Report Card AUR package

A CLI tool that generates tf/json and tfstate files based on existing infrastructure (reverse Terraform).

  • Disclaimer: This is not an official Google product
  • Created by: Waze SRE

Waze SRE logo

โ Table of Contents

โ Capabilities

  1. Generate tf/json + tfstate files from existing infrastructure for all supported objects by resource.
  2. Remote state can be uploaded to a GCS bucket.
  3. Connect between resources with terraform_remote_state (local and bucket).
  4. Save tf/json files using a custom folder tree pattern.
  5. Import by resource name and type.
  6. Support terraform 0.13 (for terraform 0.11 use v0.7.9).

Terraformer uses Terraform providers and is designed to easily support newly added resources. To upgrade resources with new fields, all you need to do is upgrade the relevant Terraform providers.

Import current state to Terraform configuration from a provider

Usage:
   import [provider] [flags]
   import [provider] [command]

Available Commands:
  list        List supported resources for a provider

Flags:
  -b, --bucket string         gs://terraform-state
  -c, --connect                (default true)
  -ะก, --compact                (default false)
  -x, --excludes strings      firewalls,networks
  -f, --filter strings        compute_firewall=id1:id2:id4
  -h, --help                  help for google
  -O, --output string         output format hcl or json (default "hcl")
  -o, --path-output string     (default "generated")
  -p, --path-pattern string   {output}/{provider}/ (default "{output}/{provider}/{service}/")
      --projects strings
  -z, --regions strings       europe-west1, (default [global])
  -r, --resources strings     firewall,networks or * for all services
  -s, --state string          local or bucket (default "local")
  -v, --verbose               verbose mode
  -n, --retry-number          number of retries to perform if refresh fails
  -m, --retry-sleep-ms        time in ms to sleep between retries

Use " import [provider] [command] --help" for more information about a command.
โ Permissions

The tool requires read-only permissions to list service resources.

โ Resources

You can use --resources parameter to tell resources from what service you want to import.

To import resources from all services, use --resources="*" . If you want to exclude certain services, you can combine the parameter with --excludes to exclude resources from services you don't want to import e.g. --resources="*" --excludes="iam".

โ Filtering

Filters are a way to choose which resources terraformer imports. It's possible to filter resources by its identifiers or attributes. Multiple filtering values are separated by :. If an identifier contains this symbol, value should be wrapped in ' e.g. --filter=resource=id1:'project:dataset_id'. Identifier based filters will be executed before Terraformer will try to refresh remote state.

โ Resource ID

Filtering is based on Terraform resource ID patterns. To find valid ID patterns for your resource, check the import part of the Terraform documentationโ .

Example usage:

terraformer import aws --resources=vpc,subnet --filter=vpc=myvpcid --regions=eu-west-1

Will only import the vpc with id myvpcid. This form of filters can help when it's necessary to select resources by its identifiers.

โ Planning

The plan command generates a planfile that contains all the resources set to be imported. By modifying the planfile before running the import command, you can rename or filter the resources you'd like to import.

The rest of subcommands and parameters are identical to the import command.

$ terraformer plan google --resources=networks,firewall --projects=my-project --regions=europe-west1-d
(snip)

Saving planfile to generated/google/my-project/terraformer/plan.json

After reviewing/customizing the planfile, begin the import by running import plan.

$ terraformer import plan generated/google/my-project/terraformer/plan.json
โ Resource structure

Terraformer by default separates each resource into a file, which is put into a given service directory.

The default path for resource files is {output}/{provider}/{service}/{resource}.tf and can vary for each provider.

It's possible to adjust the generated structure by:

  1. Using --compact parameter to group resource files within a single service into one resources.tf file
  2. Adjusting the --path-pattern parameter and passing e.g. --path-pattern {output}/{provider}/ to generate resources for all services in one directory

It's possible to combine --compact --path-pattern parameters together.

โ Installation

From source:

  1. Run git clone <terraformer repo>
  2. Run go mod download
  3. Run go build -v for all providers OR build with one provider go run build/main.go {google,aws,azure,kubernetes and etc}
  4. Run terraform init against an versions.tf file to install the plugins required for your platform. For example, if you need plugins for the google provider, versions.tf should contain:
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
  required_version = ">= 0.13"
}

Or alternatively

  • Copy your Terraform provider's plugin(s) to folder ~/.terraform.d/plugins/{darwin,linux}_amd64/, as appropriate.

From Releases:

  • Linux
export PROVIDER={all,google,aws,kubernetes}
curl -LO https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)/terraformer-${PROVIDER}-linux-amd64
chmod +x terraformer-${PROVIDER}-linux-amd64
sudo mv terraformer-${PROVIDER}-linux-amd64 /usr/local/bin/terraformer
  • MacOS
export PROVIDER={all,google,aws,kubernetes}
curl -LO https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)/terraformer-${PROVIDER}-darwin-amd64
chmod +x terraformer-${PROVIDER}-darwin-amd64
sudo mv terraformer-${PROVIDER}-darwin-amd64 /usr/local/bin/terraformer
โ Using a package manager

If you want to use a package manager:

Links to download Terraform Providers:

Information on provider plugins: https://www.terraform.io/docs/configuration/providers.htmlโ 

โ Use with GCP

asciicast

Example:

terraformer import google --resources=gcs,forwardingRules,httpHealthChecks --connect=true --regions=europe-west1,europe-west4 --projects=aaa,fff
terraformer import google --resources=gcs,forwardingRules,httpHealthChecks --filter=compute_firewall=rule1:rule2:rule3 --regions=europe-west1 --projects=aaa,fff

For google-beta provider:

terraformer import google --resources=gcs,forwardingRules,httpHealthChecks --regions=europe-west4 --projects=aaa --provider-type beta

List of supported GCP services:

  • addresses
    • google_compute_address
  • autoscalers
    • google_compute_autoscaler
  • backendBuckets
    • google_compute_backend_bucket
  • backendServices
    • google_compute_backend_service
  • bigQuery
    • google_bigquery_dataset
    • google_bigquery_table
  • cloudFunctions
    • google_cloudfunctions_function
  • cloudsql
    • google_sql_database_instance
    • google_sql_database
  • dataProc
    • google_dataproc_cluster
  • disks
    • google_compute_disk
  • externalVpnGateways
    • google_compute_external_vpn_gateway
  • dns
    • google_dns_managed_zone
    • google_dns_record_set
  • firewall
    • google_compute_firewall
  • forwardingRules
    • google_compute_forwarding_rule
  • gcs
    • google_storage_bucket
    • google_storage_bucket_acl
    • google_storage_default_object_acl
    • google_storage_bucket_iam_binding
    • google_storage_bucket_iam_member
    • google_storage_bucket_iam_policy
    • google_storage_notification
  • gke
    • google_container_cluster
    • google_container_node_pool
  • globalAddresses
    • google_compute_global_address
  • globalForwardingRules
    • google_compute_global_forwarding_rule
  • healthChecks
    • google_compute_health_check
  • httpHealthChecks
    • google_compute_http_health_check
  • httpsHealthChecks
    • google_compute_https_health_check
  • iam
    • google_project_iam_custom_role
    • google_project_iam_member
    • google_service_account
  • images
    • google_compute_image
  • instanceGroupManagers
    • google_compute_instance_group_manager
  • instanceGroups
    • google_compute_instance_group
  • instanceTemplates
    • google_compute_instance_template
  • instances
    • google_compute_instance
  • interconnectAttachments
    • google_compute_interconnect_attachment
  • kms
    • google_kms_key_ring
    • google_kms_crypto_key
  • logging
    • google_logging_metric
  • memoryStore
    • google_redis_instance
  • monitoring
    • google_monitoring_alert_policy
    • google_monitoring_group
    • google_monitoring_notification_channel
    • google_monitoring_uptime_check_config
  • networks
    • google_compute_network
  • packetMirrorings
    • google_compute_packet_mirroring
  • nodeGroups
    • google_compute_node_group
  • nodeTemplates
    • google_compute_node_template
  • project
    • google_project
  • pubsub
    • google_pubsub_subscription
    • google_pubsub_topic
  • regionAutoscalers
    • google_compute_region_autoscaler
  • regionBackendServices
    • google_compute_region_backend_service
  • regionDisks
    • google_compute_region_disk
  • regionHealthChecks
    • google_compute_region_health_check
  • regionInstanceGroups
    • google_compute_region_instance_group
  • regionSslCertificates
    • google_compute_region_ssl_certificate
  • regionTargetHttpProxies
    • google_compute_region_target_http_proxy
  • regionTargetHttpsProxies
    • google_compute_region_target_https_proxy
  • regionUrlMaps
    • google_compute_region_url_map
  • reservations
    • google_compute_reservation
  • resourcePolicies
    • google_compute_resource_policy
  • regionInstanceGroupManagers
    • google_compute_region_instance_group_manager
  • routers
    • google_compute_router
  • routes
    • google_compute_route
  • schedulerJobs
    • google_cloud_scheduler_job
  • securityPolicies
    • google_compute_security_policy
  • sslCertificates
    • google_compute_managed_ssl_certificate
  • sslPolicies
    • google_compute_ssl_policy
  • subnetworks
    • google_compute_subnetwork
  • targetHttpProxies
    • google_compute_target_http_proxy
  • targetHttpsProxies
    • google_compute_target_https_proxy
  • targetInstances
    • google_compute_target_instance
  • targetPools
    • google_compute_target_pool
  • targetSslProxies
    • google_compute_target_ssl_proxy
  • targetTcpProxies
    • google_compute_target_tcp_proxy
  • targetVpnGateways
    • google_compute_vpn_gateway
  • urlMaps
    • google_compute_url_map
  • vpnTunnels
    • google_compute_vpn_tunnel

Your tf and tfstate files are written by default to generated/gcp/zone/service.

โ Use with AWS

Example:

 terraformer import aws --resources=vpc,subnet --connect=true --regions=eu-west-1 --profile=prod
 terraformer import aws --resources=vpc,subnet --filter=vpc=vpc_id1:vpc_id2:vpc_id3 --regions=eu-west-1
โ Profiles support

AWS configuration including environmental variables, shared credentials file (~/.aws/credentials), and shared config file (~/.aws/config) will be loaded by the tool by default. To use a specific profile, you can use the following command:

terraformer import aws --resources=vpc,subnet --regions=eu-west-1 --profile=prod

You can also provide no regions when importing resources:

terraformer import aws --resources=cloudfront --profile=prod

In that case terraformer will not know with which region resources are associated with and will not assume any region. That scenario is useful in case of global resources (e.g. CloudFront distributions or Route 53 records) and when region is passed implicitly through environmental variables or metadata service.

โ Supported services
  • accessanalyzer
    • aws_accessanalyzer_analyzer
  • acm
    • aws_acm_certificate
  • alb (supports ALB and NLB)
    • aws_lb
    • aws_lb_listener
    • aws_lb_listener_rule
    • aws_lb_listener_certificate
    • aws_lb_target_group
    • aws_lb_target_group_attachment
  • api_gateway
    • aws_api_gateway_authorizer
    • aws_api_gateway_documentation_part
    • aws_api_gateway_gateway_response
    • aws_api_gateway_integration
    • aws_api_gateway_integration_response
    • aws_api_gateway_method
    • aws_api_gateway_method_response
    • aws_api_gateway_model
    • aws_api_gateway_resource
    • aws_api_gateway_rest_api
    • aws_api_gateway_stage
    • aws_api_gateway_usage_plan
    • aws_api_gateway_vpc_link
  • appsync
    • aws_appsync_graphql_api
  • auto_scaling
    • aws_autoscaling_group
    • aws_launch_configuration
    • aws_launch_template
  • budgets
    • aws_budgets_budget
  • cloud9
    • aws_cloud9_environment_ec2
  • cloudfront
    • aws_cloudfront_distribution
  • cloudformation
    • aws_cloudformation_stack
    • aws_cloudformation_stack_set
    • aws_cloudformation_stack_set_instance
  • cloudtrail
    • aws_cloudtrail
  • cloudwatch
    • aws_cloudwatch_dashboard
    • aws_cloudwatch_event_rule
    • aws_cloudwatch_event_target
    • aws_cloudwatch_metric_alarm
  • codebuild
    • aws_codebuild_project
  • codecommit
    • aws_codecommit_repository
  • codedeploy
    • aws_codedeploy_app
  • codepipeline
    • aws_codepipeline
    • aws_codepipeline_webhook
  • cognito
    • aws_cognito_identity_pool
    • aws_cognito_user_pool
  • customer_gateway
    • aws_customer_gateway
  • config
    • aws_config_config_rule
    • aws_config_configuration_recorder
    • aws_config_delivery_channel
  • datapipeline
    • aws_datapipeline_pipeline
  • devicefarm
    • aws_devicefarm_project
  • dynamodb
    • aws_dynamodb_table
  • ec2_instance
    • aws_instance
  • eip
    • aws_eip
  • elasticache
    • aws_elasticache_cluster
    • aws_elasticache_parameter_group
    • aws_elasticache_subnet_group
    • aws_elasticache_replication_group
  • ebs
    • aws_ebs_volume
    • aws_volume_attachment
  • elastic_beanstalk
    • aws_elastic_beanstalk_application
    • aws_elastic_beanstalk_environment
  • ecs
    • aws_ecs_cluster
    • aws_ecs_service
    • aws_ecs_task_definition
  • ecr
    • aws_ecr_lifecycle_policy
    • aws_ecr_repository
    • aws_ecr_repository_policy
  • efs
    • aws_efs_access_point
    • aws_efs_file_system
    • aws_efs_file_system_policy
    • aws_efs_mount_target
  • eks
    • aws_eks_cluster
  • elb
    • aws_elb
  • emr
    • aws_emr_cluster
    • aws_emr_security_configuration
  • eni
    • aws_network_interface
  • es
    • aws_elasticsearch_domain
  • firehose
    • aws_kinesis_firehose_delivery_stream
  • glue
    • glue_crawler
    • aws_glue_catalog_database
    • aws_glue_catalog_table
  • iam
    • aws_iam_group
    • aws_iam_group_policy
    • aws_iam_group_policy_attachment
    • aws_iam_instance_profile
    • aws_iam_policy
    • aws_iam_role
    • aws_iam_role_policy
    • aws_iam_role_policy_attachment
    • aws_iam_user
    • aws_iam_user_group_membership
    • aws_iam_user_policy
    • aws_iam_user_policy_attachment
  • igw
    • aws_internet_gateway
  • iot
    • aws_iot_thing
    • aws_iot_thing_type
    • aws_iot_topic_rule
    • aws_iot_role_alias
  • kinesis
    • aws_kinesis_stream
  • kms
    • aws_kms_key
    • aws_kms_alias
  • lambda
    • aws_lambda_event_source_mapping
    • aws_lambda_function
    • aws_lambda_function_event_invoke_config
    • aws_lambda_layer_version
  • logs
    • aws_cloudwatch_log_group
  • media_package
    • aws_media_package_channel
  • media_store
    • aws_media_store_container
  • msk
    • aws_msk_cluster
  • nat
    • aws_nat_gateway
  • nacl
    • aws_network_acl
  • organization
    • aws_organizations_account
    • aws_organizations_organization
    • aws_organizations_organizational_unit
    • aws_organizations_policy
    • aws_organizations_policy_attachment
  • qldb
    • aws_qldb_ledger
  • rds
    • aws_db_instance
    • aws_db_parameter_group
    • aws_db_subnet_group
    • aws_db_option_group
    • aws_db_event_subscription
  • resourcegroups
    • aws_resourcegroups_group
  • route53
    • aws_route53_zone
    • aws_route53_record
  • route_table
    • aws_route_table
    • aws_main_route_table_association
    • aws_route_table_association
  • s3
    • aws_s3_bucket
    • aws_s3_bucket_policy
  • secretsmanager
    • aws_secretsmanager_secret
  • securityhub
    • aws_securityhub_account
    • aws_securityhub_member
    • aws_securityhub_standards_subscription
  • servicecatalog
    • aws_servicecatalog_portfolio
  • ses
    • aws_ses_configuration_set
    • aws_ses_domain_identity
    • aws_ses_email_identity
    • aws_ses_receipt_rule
    • aws_ses_receipt_rule_set
    • aws_ses_template
  • sfn
    • aws_sfn_activity
    • aws_sfn_state_machine
  • sg
    • aws_security_group
    • aws_security_group_rule (if a rule cannot be inlined)
  • sns
    • aws_sns_topic
    • aws_sns_topic_subscription
  • sqs
    • aws_sqs_queue
  • subnet
    • aws_subnet
  • swf
    • aws_swf_domain
  • transit_gateway
    • aws_ec2_transit_gateway_route_table
    • aws_ec2_transit_gateway_vpc_attachment
  • waf
    • aws_waf_byte_match_set
    • aws_waf_geo_match_set
    • aws_waf_ipset
    • aws_waf_rate_based_rule
    • aws_waf_regex_match_set
    • aws_waf_regex_pattern_set
    • aws_waf_rule
    • aws_waf_rule_group
    • aws_waf_size_constraint_set
    • aws_waf_sql_injection_match_set
    • aws_waf_web_acl
    • aws_waf_xss_match_set
  • waf_regional
    • aws_wafregional_byte_match_set
    • aws_wafregional_geo_match_set
    • aws_wafregional_ipset
    • aws_wafregional_rate_based_rule
    • aws_wafregional_regex_match_set
    • aws_wafregional_regex_pattern_set
    • aws_wafregional_rule
    • aws_wafregional_rule_group
    • aws_wafregional_size_constraint_set
    • aws_wafregional_sql_injection_match_set
    • aws_wafregional_web_acl
    • aws_wafregional_xss_match_set
  • vpc
    • aws_vpc
  • vpc_peering
    • aws_vpc_peering_connection
  • vpn_connection
    • aws_vpn_connection
  • vpn_gateway
    • aws_vpn_gateway
  • workspaces
    • aws_workspaces_directory
    • aws_workspaces_ip_group
    • aws_workspaces_workspace
  • xray
    • aws_xray_sampling_rule
โ Global services

AWS services that are global will be imported without specified region even if several regions will be passed. It is to ensure only one representation of an AWS resource is imported.

List of global AWS services:

  • budgets
  • cloudfront
  • iam
  • organization
  • route53
  • waf
โ Attribute filters

Attribute filters allow filtering across different resource types by its attributes.

terraformer import aws --resources=ec2_instance,ebs --filter="Name=tags.costCenter;Value=20000:'20001:1'" --regions=eu-west-1

Will only import AWS EC2 instances along with EBS volumes annotated with tag costCenter with values 20000 or 20001:1. Attribute filters are by default applicable to all resource types although it's possible to specify to what resource type a given filter should be applicable to by providing Type=<type> parameter. For example:

terraformer import aws --resources=ec2_instance,ebs --filter=Type=ec2_instance;Name=tags.costCenter;Value=20000:'20001:1' --regions=eu-west-1

Will work as same as example above with a change the filter w

Tag summary

Content type

Image

Digest

Size

993 MB

Last updated

over 4 years ago

docker pull bridgecrew/terraformer