Install Terraform

Mac system installation

1
2
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Linux system installation

  1. Ubuntu installation
1
2
3
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install terraform
  1. CentOS system
1
2
3
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform 

Verify installation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# terraform -v
Terraform v0.14.3

Your version of Terraform is out of date! The latest version
is 0.14.7. You can update by downloading from https://www.terraform.io/downloads.html
# terraform
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

Resource management of terraform commands

Resource initialization

For a terraform resource project, I created three basic files: main.tf (entry file), variables.tf (variable information), versions.tf (version information)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ls
main.tf variables.tf versions.tf
# terraform init

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of aliyun/alicloud from the dependency lock file
- Using aliyun/alicloud v1.115.1 from the shared cache directory

Terraform has been successfully initialized!

Format terraform files

fmt will format the .tf files in the current directory by default, and the format is standard tf format.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# terraform fmt 
main.tf
variables.tf
versions.tf
# terraform fmt -diff  #格式化处理
main.tf
--- old/main.tf
+++ new/main.tf
@@ -1,7 +1,7 @@
 provider "alicloud" {
   region     = var.region
   access_key = var.alicloud_access_key
-  secret_key =  var.alicloud_secret_key
+  secret_key = var.alicloud_secret_key
 }

 resource "alicloud_vpc" "vpc" {
@@ -12,7 +12,7 @@
 resource "alicloud_vswitch" "vsw" {
   vpc_id            = alicloud_vpc.vpc.id
   cidr_block        = "10.100.0.0/24"
-  availability_zone =  var.availability_zone
+  availability_zone = var.availability_zone
 }

 resource "alicloud_security_group" "default" {
variables.tf
--- old/variables.tf
+++ new/variables.tf
@@ -4,7 +4,7 @@
 }

 variable "alicloud_secret_key" {
-  default                     = "4Z4gbl3d9TGz9jWobv9MPwInvyH2Kf"
+  default     = "4Z4gbl3d9TGz9jWobv9MPwInvyH2Kf"
   description = "The Alicloud Access Secret Key to launch resources.  Support to environment 'ALICLOUD_SECRET_KEY'."
 }

Create a resource plan

terraform plan checks that a set of changes to the execution plan match your expectations without changing the actual resources or state.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# terraform  plan

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # alicloud_instance.wanzi_test will be created
  + resource "alicloud_instance" "wanzi_test" {
      + availability_zone             = "cn-hangzhou-i"
      + credit_specification          = (known after apply)
      + deletion_protection           = false
      + dry_run                       = false
      + host_name                     = (known after apply)
      + id                            = (known after apply)
      + image_id                      = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
      + instance_charge_type          = "PostPaid"
      + instance_name                 = "wanzi_tf001"
      + instance_type                 = "ecs.s6-c1m2.small"
      + internet_max_bandwidth_in     = (known after apply)
      + internet_max_bandwidth_out    = 0
      + key_name                      = (known after apply)
      + password                      = (sensitive value)
      + private_ip                    = (known after apply)
      + public_ip                     = (known after apply)
      + role_name                     = (known after apply)
      + security_groups               = (known after apply)
      + spot_strategy                 = "NoSpot"
      + status                        = "Running"
      + subnet_id                     = (known after apply)
      + system_disk_category          = "cloud_efficiency"
      + system_disk_performance_level = (known after apply)
      + system_disk_size              = 40
      + volume_tags                   = (known after apply)
      + vswitch_id                    = (known after apply)
    }

Creating cloud resources

Terraform apply will automatically generate a resource creation plan and approve the execution of the plan. At the same time, a tfstate file will be generated in the current directory.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols: + create

Terraform will perform the following actions:

# alicloud_instance.wanzi_test will be created
+ resource "alicloud_instance" "wanzi_test" {
+ availability_zone = "cn-hangzhou-i"
+ credit_specification = (known after apply)
+ deletion_protection = false
+ dry_run = false
+ host_name = (known after apply)
+ id = (known after apply)
+ image_id = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
+ instance_charge_type = "PostPaid"
+ instance_name = "wanzi_tf001"
+ instance_type = "ecs.s6-c1m2.small" + internet_max_bandwidth_in = (known after apply) + internet_max_bandwidth_out = 0 + key_name = (known after apply) + password = (sensitive value) + private_ip = (known after apply) + public_ip = (known after apply) + role_name = (known after apply) + security_groups = (known after apply) + spot_strategy = "NoSpot" + status = "Running" + subnet_id = (known after apply) + system_disk_category = "cloud_efficiency" + system_disk_performance_level = (known after apply) + system_disk_size = 40 + volume_tags = (known after apply) + vswitch_id = (known after apply) } # alicloud_security_group.default will be created + resource "alicloud_security_group" "default" { + id = (known after apply) + inner_access = (known after apply) + inner_access_policy = (known after apply) + name = "default" + security_group_type = "normal" + vpc_id = (known after apply) } ... ...... Plan: 5 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes alicloud_vpc.vpc: Creating... alicloud_vpc.vpc: Creation complete after 9s [id=vpc-bp1kulcyygsi727aay4hd] alicloud_security_group.default: Creating... alicloud_vswitch.vsw: Creating... alicloud_security_group.default: Creation complete after 1s [id=sg-bp11s5pka9pxtj6pn4xq] alicloud_security_group_rule.allow_all_tcp: Creating... alicloud_security_group_rule.allow_all_tcp: Creation complete after 1s [id=sg-bp11s5pka9pxtj6pn4xq:ingress:tcp:1/65535:intranet:0.0.0.0/0 :accept:1] alicloud_vswitch.vsw: Creation complete after 4s [id=vsw-bp1wgpgz9z8y2lfsl2beo] alicloud_instance.wanzi_test: Creating... alicloud_instance.wanzi_test: Still creating... [10s elapsed] alicloud_instance.wanzi_test: Still creating... [20s elapsed] alicloud_instance .wanzi_test: Creation completed after 22s [id=i-bp1gt9mb9asadff9r2zr]

Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

View the created resource information

terraform show will view which resource data has been created for the current project,

terraform show -json View data in json format

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# terraform show
# alicloud_instance.wanzi_test:
resource "alicloud_instance" "wanzi_test" {
availability_zone = "cn-hangzhou-i"
deletion_protection = false
dry_run = false
host_name = "iZbp1gt9mb9asadff9r2zrZ"
id = " i-bp1gt9mb9asadff9r2zr"
image_id = "ubuntu_18_04_64_20G_alibase_20190624.vhd" instance_charge_type = "PostPaid" instance_name = "wanzi_tf001" instance_type = "ecs.s6-c1m2.small" internet_charge_type = "PayByTraffic" internet_max_bandwidth_in = -1 internet_max_bandwidth_out = 0 password = (sensitive value) private_ip = "10.100.0.234" security_groups = [ "sg-bp11s5pka9pxtj6pn4xq", ] spot_price_limit = 0 spot_strategy = "NoSpot" status = "Running" subnet_id = "vsw- bp1wgpgz9z8y2lfsl2beo" system_disk_category = "cloud_efficiency" system_disk_size = 40 volume_tags = {} vswitch_id = "vsw-bp1wgpgz9z8y2lfsl2beo" } # alicloud_security_group.default: resource "alicloud_security_group" "default" { id = "sg-bp11s5pka9pxtj6pn4xq" inner_access = true inner_access_policy = "Accept" name = "default" security_group_type = "normal" vpc_id = "vpc-bp1kulcyygsi727aay4hd" } # alicloud_security_group_rule.allow_all_tcp: resource "alicloud_security_group_rule" "allow_all_tcp" { cidr_ip = "0.0.0.0 /0" id = "sg-bp11s5pka9pxtj6pn4xq:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "1/65535" priority = 1 security_group_id = "sg-bp11s5pka9pxtj6pn4xq" type = "ingress" } # alicloud_vpc.vpc: resource "alicloud_vpc" "vpc" { cidr_block = "10.100.0.0/16" id = "vpc-bp1kulcyygsi727aay4hd" name = "tf_test_foo" resource_group_id = "rg-acfm2ogp24u3rcy" route_table_id = "vtb-bp1wy8srerq12rta02r03" router_id = "vrt-bp1apvobefvhshksnnwvm" router_table_id = "vtb-bp1wy8srerq12rta02r03"
}

# alicloud_vswitch.vsw:
resource "alicloud_vswitch" "vsw" {
availability_zone = "cn-hangzhou-i"
cidr_block = "10.100.0.0/24"
id = "vsw-bp1wgpgz9z8y2lfsl2beo"
vpc_id = "vpc-bp1kulcyygsi727aay4hd "
}

Taint terrraform

The taint command is used to mark a resource as “tainted”. When the apply command is executed again, the tainted resource will be released first, and then a new one will be created. This is equivalent to deleting and then creating a new resource for this specific resource.

1
2
# terraform taint alicloud_instance.wanzi_test
Resource instance alicloud_instance.wanzi_test has been marked as tainted.

The terraform untaint command is the opposite, which is used to cancel the “tainted” mark and restore it to a normal state.

1
2
# terraform untaint alicloud_instance.wanzi_test
Resource instance alicloud_instance.wanzi_test has been successfully untainted.

Destroy cloud resource data

terraform destroy will destroy cloud resource data according to the current resource configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#terraform destroy

Plan: 0 to add, 0 to change, 5 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

alicloud_security_group_rule.allow_all_tcp: Destroying... [id=sg-bp10tup89oothxz8tny1:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1]
alicloud_instance.wanzi_test: Destroying... [id=i-bp10ukz4nlr894mhebgl]
alicloud_security_group_rule.allow_all_tcp: Destruction complete after 0s
alicloud_instance.wanzi_test: Still destroying... [id=i-bp10ukz4nlr894mhebgl, 10s elapsed]
alicloud_instance.wanzi_test: Still destroying... [id=i-bp10ukz4nlr894mhebgl, 20s elapsed]
alicloud_instance.wanzi_test: Destruction complete after 28s
alicloud_security_group.default: Destroying... [id=sg-bp10tup89oothxz8tny1]
alicloud_vswitch.vsw: Destroying... [id=vsw-bp1ap7ccst3fjxnw4pnza]
alicloud_security_group.default: Destruction complete after 9s
alicloud_vswitch.vsw: Still destroying... [id=vsw-bp1ap7ccst3fjxnw4pnza, 10s elapsed]
alicloud_vswitch.vsw: Destruction complete after 20s
alicloud_vpc.vpc: Destroying... [id=vpc-bp1obwt5ded2i0zlbu052]
alicloud_vpc.vpc: Destruction complete after 3s

Destroy complete! Resources: 5 destroyed.

Import cloud data into local projects

Terraform import generates local resource data through the cloud instance ID. The local directory will generate a terraform.tfstate file. Before importing existing data in the local project, please back up the tfstate file and .terraform directory. For the data that has been imported locally, you can use terraform show to display the terrafrom file format, copy it out and further process it to get the tf resource file content.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# cat yunduan.tf
resource "alicloud_instance" "test999" {
  # (resource arguments)
}
#
# terraform import alicloud_instance.test999 i-bp1etiv4002h9q27lb97
alicloud_instance.test999: Importing from ID "i-bp1etiv4002h9q27lb97"...
alicloud_instance.test999: Import prepared!
  Prepared alicloud_instance for import
alicloud_instance.test999: Refreshing state... [id=i-bp1etiv4002h9q27lb97]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
# cat  terraform.tfstate
{
  "version": 4,
  "terraform_version": "0.14.3",
  "serial": 1,
  "lineage": "779fad5e-b076-8cfd-6041-f6eef8c88b8a",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "alicloud_instance",
      "name": "test999",
      "provider": "provider[\"registry.terraform.io/aliyun/alicloud\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "allocate_public_ip": null,
            "auto_release_time": "",
            "auto_renew_period": null,
            "availability_zone": "cn-hangzhou-i",
            "credit_specification": "",
            "data_disks": [],
            "deletion_protection": false,
            "description": "",
            "dry_run": null,
            "force_delete": null,
            "host_name": "iZbp1etiv4002h9q27lb97Z",
            "id": "i-bp1etiv4002h9q27lb97",
            "image_id": "ubuntu_18_04_64_20G_alibase_20190624.vhd",
            "include_data_disks": null,
            "instance_charge_type": "PostPaid",
            "instance_name": "wanzi_tf001",
            "instance_type": "ecs.s6-c1m2.small",
            "internet_charge_type": "PayByTraffic",
            "internet_max_bandwidth_in": -1,
            "internet_max_bandwidth_out": 0,
            "io_optimized": null,
            "is_outdated": null,
            "key_name": "",
            "kms_encrypted_password": null,
            "kms_encryption_context": null,
            "password": "",
            "period": null,
            "period_unit": null,
            "private_ip": "10.100.0.169",
            "public_ip": "",
            "renewal_status": null,
            "resource_group_id": "",
            "role_name": "",
            "security_enhancement_strategy": null,
            "security_groups": [
              "sg-bp14pij6g7sjmn9bz92a"
            ],
            "spot_price_limit": 0,
            "spot_strategy": "NoSpot",
            "status": "Running",
            "subnet_id": "vsw-bp1c966jdtiw1qwh2tng8",
            "system_disk_auto_snapshot_policy_id": "",
            "system_disk_category": "cloud_efficiency",
            "system_disk_description": null,
            "system_disk_name": null,
            "system_disk_performance_level": "",
            "system_disk_size": 40,
            "tags": {},
            "timeouts": {
              "create": null,
              "delete": null,
              "update": null
            },
            "user_data": "",
            "volume_tags": {},
            "vswitch_id": "vsw-bp1c966jdtiw1qwh2tng8"
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo2MDAwMDAwMDAwMDAsImRlbGV0ZSI6MTIwMDAwMDAwMDAwMCwidXBkYXRlIjo2MDAwMDAwMDAwMDB9LCJzY2hlbWFfdmVyc2lvbiI6IjAifQ=="
        }
      ]
    }
  ]
}
# terraform show
# alicloud_instance.test999:
resource "alicloud_instance" "test999" {
    availability_zone          = "cn-hangzhou-i"
    deletion_protection        = false
    host_name                  = "iZbp1etiv4002h9q27lb97Z"
    id                         = "i-bp1etiv4002h9q27lb97"
    image_id                   = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
    instance_charge_type       = "PostPaid"
    instance_name              = "wanzi_tf001"
    instance_type              = "ecs.s6-c1m2.small"
    internet_charge_type       = "PayByTraffic"
    internet_max_bandwidth_in  = -1
    internet_max_bandwidth_out = 0
    private_ip                 = "10.100.0.169"
    security_groups            = [
        "sg-bp14pij6g7sjmn9bz92a",
    ]
    spot_price_limit           = 0
    spot_strategy              = "NoSpot"
    status                     = "Running"
    subnet_id                  = "vsw-bp1c966jdtiw1qwh2tng8"
    system_disk_category       = "cloud_efficiency"
    system_disk_size           = 40
    tags                       = {}
    volume_tags                = {}
    vswitch_id                 = "vsw-bp1c966jdtiw1qwh2tng8"

    timeouts {}
}

Terraform resource relationship drawing

There are different degrees of relationship between the resources defined in each template. Terraform graph can draw a large resource relationship diagram as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# terraform graph
digraph {
        compound = "true"
        newrank = "true"
        subgraph "root" {
                "[root] alicloud_instance.wanzi_test (expand)" [label = "alicloud_instance.wanzi_test", shape = "box"]
                "[root] alicloud_security_group.default (expand)" [label = "alicloud_security_group.default", shape = "box"]
                "[root] alicloud_security_group_rule.allow_all_tcp (expand)" [label = "alicloud_security_group_rule.allow_all_tcp", shape = "box"]
                "[root] alicloud_vpc.vpc (expand)" [label = "alicloud_vpc.vpc", shape = "box"]
                "[root] alicloud_vswitch.vsw (expand)" [label = "alicloud_vswitch.vsw", shape = "box"]
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"]" [label = "provider[\"registry.terraform.io/aliyun/alicloud\"]", shape = "diamond"]
                "[root] var.alicloud_access_key" [label = "var.alicloud_access_key", shape = "note"]
                "[root] var.alicloud_secret_key" [label = "var.alicloud_secret_key", shape = "note"]
                "[root] var.availability_zone" [label = "var.availability_zone", shape = "note"]
                "[root] var.disk_category" [label = "var.disk_category", shape = "note"]
                "[root] var.disk_size" [label = "var.disk_size", shape = "note"]
                "[root] var.ecs_password" [label = "var.ecs_password", shape = "note"]
                "[root] var.ecs_type" [label = "var.ecs_type", shape = "note"]
                "[root] var.image_id" [label = "var.image_id", shape = "note"]
                "[root] var.internet_charge_type" [label = "var.internet_charge_type", shape = "note"]
                "[root] var.internet_max_bandwidth_out" [label = "var.internet_max_bandwidth_out", shape = "note"]
                "[root] var.region" [label = "var.region", shape = "note"]
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] alicloud_security_group.default (expand)"
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] alicloud_vswitch.vsw (expand)"
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] var.disk_category"
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] var.ecs_password"
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] var.ecs_type"
                "[root] alicloud_instance.wanzi_test (expand)" -> "[root] var.image_id"
                "[root] alicloud_security_group.default (expand)" -> "[root] alicloud_vpc.vpc (expand)"
                "[root] alicloud_security_group_rule.allow_all_tcp (expand)" -> "[root] alicloud_security_group.default (expand)"
                "[root] alicloud_vpc.vpc (expand)" -> "[root] provider[\"registry.terraform.io/aliyun/alicloud\"]"
                "[root] alicloud_vswitch.vsw (expand)" -> "[root] alicloud_vpc.vpc (expand)"
                "[root] alicloud_vswitch.vsw (expand)" -> "[root] var.availability_zone"
                "[root] meta.count-boundary (EachMode fixup)" -> "[root] alicloud_instance.wanzi_test (expand)"
                "[root] meta.count-boundary (EachMode fixup)" -> "[root] alicloud_security_group_rule.allow_all_tcp (expand)"
                "[root] meta.count-boundary (EachMode fixup)" -> "[root] var.disk_size"
                "[root] meta.count-boundary (EachMode fixup)" -> "[root] var.internet_charge_type"
                "[root] meta.count-boundary (EachMode fixup)" -> "[root] var.internet_max_bandwidth_out"
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"] (close)" -> "[root] alicloud_instance.wanzi_test (expand)"
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"] (close)" -> "[root] alicloud_security_group_rule.allow_all_tcp (expand)"
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"]" -> "[root] var.alicloud_access_key"
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"]" -> "[root] var.alicloud_secret_key"
                "[root] provider[\"registry.terraform.io/aliyun/alicloud\"]" -> "[root] var.region"
                "[root] root" -> "[root] meta.count-boundary (EachMode fixup)"
                "[root] root" -> "[root] provider[\"registry.terraform.io/aliyun/alicloud\"] (close)"
        }
}

This command The result can also be exported directly as a picture through the command terraform graph | dot -Tsvg > graph.svg (graphviz needs to be installed in advance: brew install graphviz )

1
terraform graph | dot -Tsvg > ~/Downloads/graph.svg

By viewing graph.svg, you can see the relationship graph between various resources:

Terraform command state management

View the current state Store all resources

1
2
3
4
5
6
# terraform state list
alicloud_instance.wanzi_test
alicloud_security_group.default
alicloud_security_group_rule.allow_all_tcp
alicloud_vpc.vpc
alicloud_vswitch.vsw

View the specific data of a resource

1
2
3
4
5
6
7
8
# terraform state show alicloud_vswitch.vsw
# alicloud_vswitch.vsw:
resource "alicloud_vswitch" "vsw" {
availability_zone = "cn-hangzhou-i"
cidr_block = "10.100.0.0/24"
id = "vsw-bp1wgpgz9z8y2lfsl2beo"
vpc_id = "vpc-bp1kulcyygsi727aay4hd"
}

Remove specific resources

terraform state rm . The state rm command is used to remove a resource in a state , but the resource will not actually be deleted. You can also restore it from the cloud to the local computer through the import operation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# terraform state rm  alicloud_security_group.default
Removed alicloud_security_group.default
Successfully removed 1 resource instance(s).
# terraform state list
alicloud_instance.wanzi_test
alicloud_vpc.vpc
alicloud_vswitch.vsw
# terraform import alicloud_security_group.default sg-bp11s5pka9pxtj6pn4xq
alicloud_security_group.default: Importing from ID "sg-bp11s5pka9pxtj6pn4xq"...
alicloud_security_group.default: Import prepared!
  Prepared alicloud_security_group for import
alicloud_security_group.default: Refreshing state... [id=sg-bp11s5pka9pxtj6pn4xq]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

Refresh resources

terraform refresh Refresh the current state content, call the cloud API to pull the latest data and write it to the state file

1
2
3
4
5
# terraform refresh
alicloud_vpc.vpc: Refreshing state... [id=vpc-bp1kulcyygsi727aay4hd]
alicloud_vswitch.vsw: Refreshing state... [id=vsw-bp1wgpgz9z8y2lfsl2beo]
alicloud_security_group.default: Refreshing state... [id=sg-bp11s5pka9pxtj6pn4xq]
alicloud_instance.wanzi_test:refreshingstadt... [ID=i-not afraid 1 common 9 understand 9 Assad method 9 days 2 natural]