then after i logged out i can’t connect to my droplet both via SSH and web console.
How can i fix this, and is there a better way to do this so i don’t repeat the same mistake?
]]>Although inside my droplet I’m able to call my API through the domain link with a status 200 OK using a curl command, outside the droplet (browser, Postman, PC terminal) when I call the API using curl, it never recognizes it.
So, I gave up trying to run directly with the DigitalOcean domain and started using another registration service, calling my DigitalOcean domain by ‘ns1.digitalocean.com,’ ‘ns2.digitalocean.com.’… However, to my surprise, the registration service says that the search with ns1.digitalocean.com was refused. So, would this be a DNS issue? I can’t understand why my domain on DigitalOcean never works.
PS: Requesting my API by IP and port works normally, but when it comes to the domain this never happens.
]]>After web and ssh is up, I turn on the firewall (# systemctl start firewalld) but the disconnection happenes again after few hours, I had to disable the firewall and it will work again. This just started one month ago. Please help on this.
]]>Is this possible using Digital Ocean’s firewall? I have no issue using UFW but just wanted to make it easier with DigitalOcean’s UI for our team down the road.
]]>The firewall’s inbound and outbound rules are identical, allowing SSH, HTTP, and HTTPS over the standard ports for all IPV4, IPV6.
Am I missing a setting, or is there some other issue? Many thanks in advance!
]]>Gostaria de expressar minha gratidão por ser um cliente fiel da DigitalOcean. Recentemente, criei um Docker Cluster utilizando o Traefik.io e gostaria de saber se ainda é necessário configurar um firewall através da interface gráfica do DigitalOcean.
Embora eu tenha conhecimento básico em segurança cibernética, ainda tenho algumas dúvidas em relação à segurança do meu cluster e quero garantir que todas as medidas necessárias sejam tomadas. Portanto, peço-lhes gentilmente que me informem se a configuração do firewall é necessária ou se as configurações padrão fornecidas pelo Traefik.io são suficientes.
Agradeço antecipadamente pela atenção e espero ansiosamente por sua resposta.
Atenciosamente, Edivaldo, Victor
]]>I need to write a script that
From the documentation, digitalocean_firewall
accepts droplet_ids
, a list of ids of droplets. My problem is that I should add the new droplet id without removing the others.
I’ve tried creating a
data "digitalocean_firewall" "default" {
firewall_id = var.firewall_id
}
and then using concat
resource "digitalocean_firewall" "droplet-firewall" {
name = "Default"
droplet_ids = concat(data.digitalocean_firewall.default.droplet_ids, [digitalocean_droplet.droplet.id])
}
Before running this I’ll run terraform import
to add the resource
But I get an error about data.digitalocean_firewall.default.droplet_ids is null
and I don’t know if it’s the correct method to do this.
Thank you
]]>git
on my server became a lot slower. I timed the time it takes to resolve github.com
and this is the result:
$ time dig github.com +short
140.82.121.3
real 0m2.011s
user 0m0.011s
sys 0m0.005s
Over 2 seconds! When I removed my droplet from the firewall, the result was dramatically different:
$ time dig github.com +short
140.82.121.3
real 0m0.013s
user 0m0.008s
sys 0m0.004s
Here’s the configuration of my firewall:
Why is that happening?
]]>I am completely at a loss here when I have been trying to get my load balancer firewall configured to have a public load balancer with kubernetes nodes that are not accessible outside of the VPC. I need to shut down access to all kubernetes node ports outside of DigitalOcean and only allow a single public load balancer to access a single nodeport on the kubernetes nodes, which then get routed with an Nginx ingress controller.
I have found that DigitalOcean can create and manage firewall rules but it configures things where the node ports are open to the world behind the load balancer. This won’t work for me because I put SSO and SSL termination from Cloudflare in front of the load balancer. So I have one Cloudflare proxied DNS record for root and wildcard pointing at that load balancer. Since all authentication is happening in front of the load balancer I absolutely can not have the node ports behind the load balancer exposed to the world. So from what I have found DigitalOcean’s firewall configuration management for Kubernetes won’t work.
So I tried creating the load balancer outside of kubernetes and configuring its DNS through Terraform to link to the nodeport for the Nginx service and tried creating a new firewall rule (also in Terraform) to only allow traffic from the load balancer. This does not work either, as the load balancer can not reach the nodeport anymore.
In fact when I create a firewall test (new rule) that allows all ports outside of the kubernetes configured firewall, it still doesn’t work, even if I allow full access to all ports from all ipv4 traffic. This makes no sense to me, so I am completely missing something here.
So what am I missing here? Why is it almost impossible to configure a simple firewall rule to lock down nodeports on the kubernetes nodes, except for traffic from a single load balancer?
Thanks for your help!
]]>I tried to rebuilt the Ubuntu, but it is not working because I messed up with my firewall settings.
How to remove this droplet and create a new one, but keep my IP?
]]>I have an App that uses a Droplet as a resource.
To firewall the droplet, I need to know the IP address that the app uses when it connects to the droplet.
How do I find out what the app’s IP address is so I can use it in a firewall rule?
Thanks!
]]>Any help would be beneficial. If needed I can provide further information regarding my project/droplet.
Thank you
]]>Now all traffic gets blocked - including the traffic from Droplet-W (which means that the web gets no data) Any ideas what I might be doing wrong here or forgetting … ?
]]>Sincerely thank
]]>I have updated the firewall to allow traffic from anywhere and even from my device IP address but all to no avail.
Is there anything I am missing out in my configuration?
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
18333 ALLOW IN Anywhere
18333/tcp ALLOW IN Anywhere
22/tcp ALLOW IN Anywhere
80/tcp ALLOW IN Anywhere
443/tcp ALLOW IN Anywhere
80 on eth0 ALLOW IN Anywhere
18333 on eth0 ALLOW IN Anywhere
18332 ALLOW IN Anywhere
Anywhere ALLOW IN 1x2.xx.xxx.2x2
18333 (v6) ALLOW IN Anywhere (v6)
18333/tcp (v6) ALLOW IN Anywhere (v6)
22/tcp (v6) ALLOW IN Anywhere (v6)
80/tcp (v6) ALLOW IN Anywhere (v6)
443/tcp (v6) ALLOW IN Anywhere (v6)
80 (v6) on eth0 ALLOW IN Anywhere (v6)
18333 (v6) on eth0 ALLOW IN Anywhere (v6)
18332 (v6) ALLOW IN Anywhere (v6)
]]>Date/Time Priority Message
2022-09-24 18:39:46 Z Notice Authentication attempt for unknown user admin from 151.106.116.118
2022-09-24 18:31:38 Z Notice Authentication attempt for unknown user admin from 209.182.195.110
2022-09-24 18:20:25 Z Notice Authentication attempt for unknown user admin from 167.71.234.124
2022-09-24 18:14:56 Z Notice Authentication attempt for unknown user admin from 165.22.109.42
2022-09-24 18:06:39 Z Notice Authentication attempt for unknown user admin from 202.29.236.140
Ideally is it possible the DigitalOcean Fail2Ban filters [wordpress-soft] & [wordpress-hard] permanently ban IPs that are not in the United Kingdom? Please can someone advise how to implement?
Or would it be best to block all these countries to save resources? And potentially stop the website being hacked? If yes, how? Should this be done using UFW or Fail2ban?
My concern with a blanket country ban is it might have negative SEO effects and block a genuine customer.
It’s irritating seeing so many bots trying to hack the website. Wouldn’t it just be best to blanket ban the country they are coming from?
My setup is Ubuntu 22.04.1 LTS Apache 2.4.
Any advice is much appreciated.
Thank you
]]>It looks like fw is auto-generated when k8s clusters are created. I’d like to create my own with its own rules and have them auto-assign (or manually-assign) to clusters and/or pools.
I think I can sort of do this through tags, but the cluster with the tag needs to be created first, and I’m not sure this is working at the pool-level or not. Would be great to have some clarification.
I also want to know if the firewalls will always keep getting recreated by k8s and what is needed from them. I would like to not have it open everything to the world by default.
]]>It seems like there is still only read-only and read-write scopes on tokens. This seems like a blatant overlook from a security stance, especially considering there can be multiple projects on one account.
In addition, it would be nice to disallow my CI/CD from having access to my entire server infrastructure when it only needs image repo access. I’m thinking I might need to stop using DO repos altogether and get a Docker subscription or something because it’s just too risky. I like DO because it’s one of the cheaper options, but it’s just not practical. Maybe I can integrate directly with Gitlab? But then I’m limited to one repo and I produce several projects (and tagging wouldn’t make sense for them).
For the Firewall I’m also thinking I might be able to use Cloudflare with their API. Scoping wouldn’t be a problem because it’d be isolated to that platform.
So there are solutions, but all of this seems like it could just be easily resolved by allowing more granular scopes with API tokens.
Would love to hear your thoughts on this, thanks!
]]>[09/Mar/2022:08:20:53 +0000] “GET /ap?co=42656._px&cid=342888 HTTP/1.1” 504 176 “-” “GuzzleHttp/7”
and the error log is
2022/03/09 08:20:53 [error] 2323#2323: *1232 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 11.232.0.1, server: domain.com, request: “GET /ap?co=42656._px&cid=342888 HTTP/1.1”, upstream: “fastcgi://unix:/var/run/php/php7.4-fpm.sock”,
so i think it’s something wrong on load balancer or from firewall? is using guzzlehttp / curl to outside domain to get data considering as “outbound” ?
so i am duplicate this server and put it as stand alone droplet and pointing the domain to there…when it access like that everything run ok? no error at all and run smooth even i leave for one day…this is duplicate server from snapshot so nginx config,etc should be same…the different just not behind the loadbalancer? any idea why? thank you!
]]>But After I enable DO Cloud Firewall, my keepalived not working
How to make it work?
]]>kubectl cluster-info
returns URL where the Kubernetes control plane is running at. None of my droplets / load balancers have the public IP address returned by nslookup of that URL.
My questions are:
Sincerely thank
]]>Regards.
]]>If so then I’ll set the managing server’s firewall to only accept incoming SSH from a limited number of IPs that I own elsewhere. I’ll ssh onto the manager and then ssh from there to the web servers. This way the only access to the web servers will be via HTTP/HTTPs.
If the above is possible does anyone know where I can find an example UFW configuration showing how to work with the DO private networks?
]]>freebsd-12-x64-zfs
image in the cloud with the SSH tag and wait for it to boot (verified using the console), I sometimes can’t SSH into the machine (the connection hangs trying to connect).
This happens consistently if I build the machine with Packer, and was happening consistently with just this image (it worked with other images) if I built it from the control panel (new droplet, select FreeBSD, select basic s-1vcpu-1gb
option, select NYC3, all SSH keys, add tag ssh
, hit create) yesterday, but today it seems to be fine if I go that route.
Since you can’t change the root password on FreeBSD images using the control panel I’ve been unable to run anything on these machines to try and figure out what’s going on, and contacting support has been useless because I just cannot convince them that I can’t run commands (literally every email back and forth I try to explain that I can’t run anything, then they say “okay, in that case run these other commands on the new droplet instead”). Does anyone have any ideas?
Other images seem to work (though I haven’t tried them with the packer method, so it may be that they would fail in the same way when using packer), and the same thing happens if I change the region. It does not happen if I manually apply the firewall (instead of relying on the tags) as far as I can tell, but I can’t do that from packer. At least once I’ve seen it suddenly start working after ~10 minutes and several reconnect attempts, but normally I just get this if I try to ssh in:
$ ssh -vv root@137.184.17.223
OpenSSH_8.7p1, OpenSSL 1.1.1l FIPS 24 Aug 2021
debug1: Reading configuration data /home/sam/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Reading configuration data /etc/ssh/ssh_config.d/50-redhat.conf
debug2: checking match for 'final all' host 137.184.17.223 originally 137.184.17.223
debug2: match not found
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug1: configuration requests final Match pass
debug2: resolve_canonicalize: hostname 137.184.17.223 is address
debug1: re-parsing configuration
debug1: Reading configuration data /home/sam/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Reading configuration data /etc/ssh/ssh_config.d/50-redhat.conf
debug2: checking match for 'final all' host 137.184.17.223 originally 137.184.17.223
debug2: match found
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug1: Connecting to 137.184.17.223 [137.184.17.223] port 22.
<hangs here until it times out>
EDIT: tried a different (Fedora) image with Packer and it can’t be SSHed into as well even though I can verify in the console that the firewall is applied that allows SSH. Maybe it was just a coincidence that they were working yesterday from the console while FreeBSD was not and that everything appears to be working from the console today.
]]>Terraform is an infrastructure-as-code tool created by HashiCorp that helps developers with deploying, updating, and removing different assets of their infrastructure in an efficient and more scalable way.
Developers can use Terraform to organize different environments, track changes through version control, and automate repetitive work to limit human error. It also provides a way for teams to collaborate on improving their infrastructure through shared configurations.
In this tutorial, you’ll import existing DigitalOcean infrastructure into Terraform. By the end of this tutorial you’ll be able to use Terraform for all of your existing infrastructure in addition to creating new assets.
terraform-testing
is used in this tutorial.testing-terraform-firewall
is used for purposes of this tutorial.doctl
GitHub page. For additional guidance, you can read the tutorial, How To Use Doctl, the Official DigitalOcean Command-Line Client.This tutorial was tested using Terraform 1.0.10.
In this first step, you’ll install Terraform on your local machine. This step details the installation of Terraform on the Linux distribution. If you use Windows or MacOS, you can check the Download Terraform page on the Terraform website.
Installation steps are described on HashiCorp website.
Note: It’s usually bad practice to pipe/run objects/executables downloaded from the internet directly in the same command, but as HashiCorp is trusted source, we are going to make an exception here. If you don’t feel comfortable doing this, download the object first, inspect it, and then move forward if everything looks good.
HashiCorp digitally signs their repository, so you will need to add their GNU Privacy Guard (GPG) key. This provides a reasonable guarantee that the repository is actually owned and maintained by HashiCorp:
- curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
Add the official HashiCorp repository to the system:
- sudo apt-add-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
Install Terraform:
- sudo apt update; sudo apt install terraform=1.0.10
In order to add the HashiCorp repository, you need to add it to your repository list. The core DNF plugin config-manager
is used for this purpose, and is provided by the dnf-plugins-core
package. Install the needed dnf
plugin:
- sudo dnf install -y dnf-plugins-core
Add the official HashiCorp repository to the system:
- sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
Install Terraform:
- sudo dnf install terraform-1.0.10-1
After following the installation directions for your OS, check if Terraform is installed properly by checking the version:
- terraform version
The output will look similar to this:
OutputTerraform v1.0.10
on linux_amd64
You’ve installed Terraform to your local machine. Next, you’ll prepare the configuration files.
In this step, you’ll import your existing assets into Terraform by creating a project directory and writing configuration files. Since Terraform doesn’t support generating configs from the import
command at this time, you need to create those configurations manually.
Run the following command to create your project directory:
- mkdir -p do_terraform_import
Then move into that directory:
- cd do_terraform_import
Initialize a new Terraform workspace:
- terraform workspace new do_terraform_import
Check if you’re using newly created workspace:
- terraform workspace list
The output will be similar to this:
Output default
* do_terraform_import
Within this step you’ll create three additional files that will contain the required configurations. Your directory structure for this project will look like the following:
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
├── provider.tf
├── .terraform
└── terraform.tfstate.d
To begin, you’ll create the file provider.tf
to define your DigitalOcean Access Token as an environment variable instead of hardcoding it into your configuration.
Warning: Your access token gives access to your complete infrastructure with unrestricted access, so treat it as such. Be sure that you’re the only one who has access to the machine where that token is stored.
In addition to your access token, you’ll also specify which provider you want to use. In this tutorial, that’s digitalocean
. For a full list of available Data Sources and Resources for DigitalOcean with Terraform, visit the Providers page on their website.
Create and edit provider.tf
with the following command:
- nano provider.tf
Add the following content into the provider.tf
file:
terraform {
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
version = "2.15.0"
}
}
}
variable "do_token" {}
provider "digitalocean" {
token = var.do_token
}
In this file, you add your DigitalOcean Access Token as a variable, which Terraform will use as identification for the DigitalOcean API. You also specify the version of the DigitalOcean provider plugin. Terraform recommends that you specify which version of the provider you’re using so that future updates don’t potentially break your current setup.
Save and close the file.
Now you’ll create the digitalocean_droplet.tf
file. Here you’ll specify the resource that you’re going to use, in this case: droplet
.
This file should replicate existing resources in order to successfully import it in Terraform state in later steps.
Create the file with the following command:
- nano digitalocean_droplet.tf
Add the following configuration, updating where necessary to match your pre-existing resources:
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Here, you specify four parameters that should match your pre-existing resources:
name
: The Droplet name.
region
: The region that the Droplet is located in.
tags
: A list of the tags that are applied to this Droplet.
count
: The number of resources needed for this configuration.
Save and close the file.
Next, you’ll create a configuration file for your firewall. Create the file digitalocean_firewall.tf
with the following command:
- nano digitalocean_firewall.tf
Add the following content to the file:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
}
Here you specify the name of the firewall you wish to import and the tags of the Droplets to which the firewall rules apply.
Save and close the file.
Note: You can include firewall resources in the digitalocean_droplet.tf
file as well; however, if you have multiple environments where multiple Droplets share the same firewall, it’s a good idea to separate them in case you only want to remove a single Droplet. This will then leave the firewall unaffected.
Now it’s time to initialize those changes so Terraform can download the required dependencies. You will use the terraform init
command for this, which will allow you to initialize a working directory containing Terraform configuration files.
Run this command from your project directory:
- terraform init
You’ll see the following output:
OutputTerraform has been successfully initialized!
Terraform has successfully prepared the working directory by downloading plugins, searching for modules, and so on. Next you’ll begin importing your assets to Terraform.
In this step, you’ll import your DigitalOcean assets to Terraform. You’ll use doctl
to find the ID numbers of your Droplets before importing your assets. You’ll then check the import configuration with the terraform show
and terraform plan
commands.
To begin, you’ll export your DigitalOcean Access Token as an environment variable, which you’ll then inject into Terraform during runtime.
Export it as an environment variable into your current shell session with the following command:
- export DO_TOKEN="YOUR_TOKEN"
In order to import your existing Droplet and firewall, you’ll need their ID numbers. You can use doctl
, the command line interface for the DigitalOcean API.
Run the following command to list your Droplets and access their IDs:
- doctl compute droplet list
You’ll see output similar to the following:
OutputID Name Public IPv4
DROPLET-ID DROPLET-NAME DROPLET-IPv4
DROPLET-ID DROPLET-NAME DROPLET-IPv4
DROPLET-ID DROPLET-NAME DROPLET-IPv4
Make note of the Droplet ID for the resource you want to import, as you’ll need this in a later command.
Next, run the following command to list your firewalls and access their IDs:
- doctl compute firewall list
You’ll see output similar to the following:
OutputID Name Status
FIREWALL-ID FIREWALL-NAME succeeded
Make note of the firewall ID for the resource you want to import, as you’ll need this in a later command.
Import your existing Droplet into Terraform, replacing DROPLET-ID with the ID of your Droplet:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET-ID
You use the -var
flag to specify your DigitalOcean Access Token value that you previously exported to your shell session. This is needed so the DigitalOcean API can verify who you are and apply changes to your infrastructure.
Now run the same command for your firewall, replacing FIREWALL ID with the ID of your firewall:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL-ID
You’ll check that the import was successful by using the terraform show
command. This command provides human-readable output of your infrastructure state. It can be used to inspect a plan to ensure that wanted changes are going to be executed, or to inspect the current state as Terraform sees it.
In this context, state refers to the mapping of your DigitalOcean assets to the Terraform configuration that you’ve written and the tracking of metadata. This allows you to confirm that there’s no difference between existing DigitalOcean assets that you want to import and assets that Terraform is keeping track of:
- terraform show
The output will look similar to this:
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
You’ll see two resources in the output along with their attributes.
After you import your Droplet and firewall into Terraform state, you need to make sure that configurations represent the current state of the imported assets. To do this, you’ll specify your Droplet’s image
and its size
. You can find these two values in the output of terraform show
for digitalocean_droplet.do_droplet
resource.
Open the digitalocean_droplet.tf
file:
- nano digitalocean_droplet.tf
In this tutorial:
ubuntu-20-04-x64
.fra1
.terraform-testing
.Note: Your operating system, region, size of the droplet, and other resources might differ, be sure to update file to reflect your values.
To make sure the configuration in digitalocean_droplet.tf
matches the current state of the imported Droplet, it will need to be updated to look like this:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-20-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
Where relevant, update the configuration to match your imported Droplet.
Next, you’ll add in the firewall rules. In our example, open ports for inbound traffic are 22
, 80
, and 443
. All ports are opened for outbound traffic. You can adjust this configuration accordingly to your open ports.
Open digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Add the following configuration:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
These rules replicate the state of the existing example firewall. If you’d like to limit traffic to different IP addresses, different ports, or different protocol, you can adjust the file to replicate your existing firewall.
Save and close the file.
After you’ve updated your Terraform files, you’ll use the plan
command to see if changes you made replicate the state of existing assets on DigitalOcean.
The terraform plan
command is used as a dry run. With this command, you can check whether the changes Terraform is going to make are the changes you want to make. It is a good idea to always run this command for confirmation before applying changes.
Run terraform plan
with the following:
- terraform plan -var "do_token=$DO_TOKEN"
If no changes are detected, the output will look similar to this:
OutputNo changes. Infrastructure is up-to-date.
If changes are detected, the Terraform output will display them for you to review and adjust accordingly.
You’ve successfully imported existing DigitalOcean assets in Terraform, and now you can make changes to your infrastructure through Terraform without the risk of accidentally deleting or modifying existing assets.
In this step, you’ll add two additional Droplets to your existing infrastructure. Adding assets this way to your existing infrastructure can be useful, for example, if you have a live website and don’t want to make any potentially breaking changes to that website while working on it. Instead you can add a Droplet to use as a development environment and work on your project in the same environment as the production Droplet, without any of the potential risk.
Open digitalocean_droplet.tf
to add the rules for your new Droplets:
- nano digitalocean_droplet.tf
Add the highlighted lines to your file:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-20-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-20-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
You can use the count
meta-argument to tell Terraform how many Droplets with the same specifications you want. These new Droplets will also be added to your existing firewall as you specify the same tag as per your firewall.
Apply these rules to check the changes you’re specifying in digitalocean_droplet.tf
:
- terraform plan -var "do_token=$DO_TOKEN"
Verify that the changes you want to make are replicated in the output of this command.
You’ll see output similar to the following:
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-20-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Once you’re satisfied with the output, use the terraform apply
command to apply the changes you’ve specified to the state of the configuration:
- terraform apply -var "do_token=$DO_TOKEN"
Confirm the changes by entering yes
on the command line. After successful execution, you’ll see output similar to the following:
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
You’ll see two new Droplets in your DigitalOcean web panel:
You’ll also see them attached to your existing firewall:
You’ve created new assets with Terraform using your existing assets. To learn how to destroy these assets, you can optionally complete the next step.
In this step, you’ll destroy the assets that you’ve imported and created by using Terraform’s destroy
option.
To destroy assets that are handled by Terraform, execute the following command:
- terraform destroy -var "do_token=${DO_TOKEN}"
Terraform will ask you to confirm if you wish to destroy the Droplets and firewall. This will destroy all assets you imported and created via Terraform, so be sure that you wish to proceed before typing yes
.
The output will look similar to this:
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
You’ve successfully deleted all assets managed by Terraform.
In this tutorial, you installed Terraform, imported existing assets, created new assets, and optionally destroyed those assets. You can scale this workflow to a larger project, such as deploying a production-ready Kubernetes cluster. Using Terraform you could manage all of the nodes, DNS entries, firewalls, storage, and other assets, as well as use version control to track changes and collaborate with a team.
To explore additional Terraform features, read their documentation. You can also read DigitalOcean’s Terraform content for further tutorials and Q&A.
]]>I am using the app platform the first time and for some additional components like elasticsearch I have set up a droplet. Now I want to secure up my droplet, that only my application from the app platform can access it over defined ports.
How can I add the app platform as trusted source?
]]>The problem is I see suspicious connection that is blocked in UFW, there are a lot of unknown IP trying to connect to various port. It should be blocked by digitalocean firewall because the port is not 1194. Why this is happen. Does the cloud firewall got bypassed?
Note:
This is some part of my ufw.log
Oct 31 04:56:09 MY_DROPLET kernel: [924707.027218] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=221.201.98.177 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=112 ID=12128 PROTO=UDP SPT=56455 DPT=53787 LEN=112 Oct 31 04:56:26 MY_DROPLET kernel: [924723.287569] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=41.44.59.128 DST=MY_DROPLET_IP LEN=48 TOS=0x00 PREC=0x00 TTL=115 ID=48741 PROTO=UDP SPT=18956 DPT=53787 LEN=28 Oct 31 04:56:49 MY_DROPLET kernel: [924746.844549] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=77.38.77.61 DST=MY_DROPLET_IP LEN=132 TOS=0x08 PREC=0x00 TTL=38 ID=63816 PROTO=UDP SPT=39392 DPT=53787 LEN=112 Oct 31 04:57:15 MY_DROPLET kernel: [924772.753821] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=65.18.122.158 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=116 ID=31446 PROTO=UDP SPT=29123 DPT=53787 LEN=112 Oct 31 04:57:26 MY_DROPLET kernel: [924783.550471] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=67.193.145.94 DST=MY_DROPLET_IP LEN=132 TOS=0x08 PREC=0x00 TTL=107 ID=40566 PROTO=UDP SPT=6881 DPT=53787 LEN=112 Oct 31 04:57:43 MY_DROPLET kernel: [924800.297427] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=65.18.122.158 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=116 ID=31449 PROTO=UDP SPT=29123 DPT=53787 LEN=112 Oct 31 04:58:04 MY_DROPLET kernel: [924821.994170] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=86.238.133.0 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=114 ID=51877 PROTO=UDP SPT=64183 DPT=53787 LEN=112 Oct 31 04:58:27 MY_DROPLET kernel: [924844.552135] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=77.38.77.61 DST=MY_DROPLET_IP LEN=48 TOS=0x08 PREC=0x00 TTL=38 ID=63824 PROTO=UDP SPT=39392 DPT=53787 LEN=28 Oct 31 04:58:51 MY_DROPLET kernel: [924868.149509] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=221.201.98.177 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=112 ID=12132 PROTO=UDP SPT=56455 DPT=53787 LEN=112 Oct 31 04:59:04 MY_DROPLET kernel: [924881.277987] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=67.193.145.94 DST=MY_DROPLET_IP LEN=132 TOS=0x08 PREC=0x00 TTL=107 ID=40568 PROTO=UDP SPT=6881 DPT=53787 LEN=112 Oct 31 04:59:25 MY_DROPLET kernel: [924902.829542] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=65.18.122.158 DST=MY_DROPLET_IP LEN=132 TOS=0x00 PREC=0x00 TTL=116 ID=31452 PROTO=UDP SPT=29123 DPT=53787 LEN=112 Oct 31 04:59:50 MY_DROPLET kernel: [924927.312663] [UFW BLOCK] IN=eth0 OUT= MAC=MAC_ADDRESS SRC=77.38.77.61 DST=MY_DROPLET_IP LEN=132 TOS=0x08 PREC=0x00 TTL=38 ID=63826 PROTO=UDP SPT=39392 DPT=53787 LEN=112
]]>As a Cloudflare user, I whitelist their IPs fairly often, and it’s a tedious process to create and update IP’s in a rule (15 IPv4 CIDR’s, 7 IPv6 CIDR’s), as well as in multiple rules in multiple Cloud Firewalls. It would be great if I could just create an object with all the Cloudflare IP’s, and then whitelist that object. It would save so much time and hassle, and isn’t specific to just CF users. Anyone creating multiple rules with the same IP’s would benefit.
Thanks! Chloe
]]>However when i tried to telnet the port to see if it works. it returned connection refused .
i haven’t use ufw or any other firewall .
Would you please advice ?
]]>Also I can’t post a question from a iPhone. The tag selector doesn’t work.
]]>I have a droplet for which I recently introduced a firewall and I have a hosted redis server on digital ocean.
Lately I started getting and error: No connection is available to service this operation: EVAL; It was not possible to connect to the redis server(s)
My first thought might be that its the firewall but to be honest, I actually had a the firewall for a while before this error occurred but might be related. I did however try and set the outbound port to that of my redis server without it doing anything.
After I started seeing this error, I set the eviction policy to allkeys-lru on my redis server and also added security so only my droplet and home(dev) pc can connect.
Locally in my Dev env I am not getting any errors. only from my two .Net apps on my droplet.
I am not sure what might be causing this?
]]>I know how to create a rule for TCP port 5432. However I still want to connect using pgadmin.
How can I only allow local connections, and two connections from the IP address of a couple of specific computers?
]]>screenshot- https://prnt.sc/11va5c2
]]>PS: I’m still learning how to use DigitalOcean Components and environment setup.
]]>ufw disable
ufw reset
ufw default deny incoming
ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 25
And then sudo ufw status verbose
…
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN Anywhere
25 ALLOW IN Anywhere
22/tcp (v6) ALLOW IN Anywhere (v6)
25 (v6) ALLOW IN Anywhere (v6)
However, one cursory glance of sudo netstat -tulpn | grep LISTEN
and…
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 512/systemd-resolve
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 664/sshd: /usr/sbin
tcp6 0 0 :::22 :::* LISTEN 664/sshd: /usr/sbin
and telnet [my server IP] 25
:
telnet: Unable to connect to remote host: Connection refused
What gives? How can I open up my ports?
]]>It doesn’t seem to be an option from what I could tell, but was wondering if I am missing something? If it’s not an option is this something that would be a candidate for a future feature?
]]>I can now log in to phpmyadmin, only it is barely usable because the page information is glitching, some of the top row menu buttons are doubled and not in-line, and the text in the left panel where the databases are is jumbled up with overlaid duplicated text, and the text is not even of the databases. There are also no phpmyadmin logos anywhere, including the index page, or any button images whatsoever for that matter.
I say barely usable above because I was able to import a database, although I couldn’t edit it at all, and the databases are functional on the front end.
My guess is this is due to the firewall not letting in all of the information, currently I have:
All TCP | All ports | (one IP) SSH | 22 | All IPv4, All IPv6 MySQL | 3306 | All IPv4, All IPv6
]]>But I cant get access to my wordpress website ( I get error 500), and wp-admin is not working.
This is a mail I got from Digital Ocean… (NetCraft abuse Report)
Hello,
We have detected a cryptocurrency investment scam site hosted on your network:
hxxps://domain[.]com/wp-includes/index.html?jhBgVdSEAQZSXDRcFvgHBnjMOmmKIjnHBUgyVtFCcRESXRDCfVGBH
Would it be possible to have the fraudulent content, and any other associated fraudulent content, taken down as soon as you are able to?
Cryptocurrency investment scams are sites that promote fraudulent cryptocurrency trading platforms, either directly or by mimicking well-known news sites. These platforms suggest high financial returns, but do not pay out the amounts promised. They often tailor the content served based on the visitor’s country to provide a more convincing scam.
More information about the detected issue is provided at https://incident.netcraft.com/7123cde2b8d9/
Many thanks,
I have a droplet with CyberPanel-ubuntu… and tried to fix this with a security module called Imunify 360, but I cant install it because I need to convert Cyberpanel to Cloudlinux.
So I tried tutorial(https://cyberpanel.net/docs/1-convert-cyberpanel-server-to-cloudlinux-os/) but Terminal in CyberPanel is not working. I get this image http://prntscr.com/wb4hwt
What if I delete my droplet? the problem could be fixed?
Thanks for your help…
]]>As the title suggests, I can only connect to my managed database if I enable all Outbound TCP Ports in DO Firewall.
I have tried to only allow port 25060 with no success.
Both the droplet and the managed database are in the same region (NYC3).
The error I’m getting if I remove all TCP ports from the firewall: Unknown MySQL server host
Any suggestions?
]]>Even though there’s no Firewall running that I know of it looks like Port 25 is blocked preventing the server from sending email.
Is this something Digital Ocean do at a higher level or could there be another explanation?
]]>sudo apt-get update
fails with
Err:1 http://mirrors.digitalocean.com/ubuntu focal InRelease Temporary failure resolving ‘mirrors.digitalocean.com’
but is ok when the firewall is disabled
What rules would I add to the firewall to allow ‘apt-get update’ ?
]]>is it possible to set up the firewall for the database in a way that only the app has access to it while public access is blocked?
Some providers (incl. Heroku) don’t offer that functionality in their non-enterprise tiers.
You can’t configure it via a regular static IP whitelist rule because the app doesn’t have a static IP unless it does for Digital Ocean?
]]>I have setup cloud firewall to “SSH Sources: my ipaddress” I imagined it would only allow my ip to connect to ssh.
However in my log I can see bots spamming my ssh port, shouldn`t other ips be blocked?
]]>What logging features are available for those?
]]>So let’s say that some IP addresses are causing too much load on the server by putting so many requests and I block them through the Digital Ocean Cloud Firewall, but it does not mean that those IPs will stop sending the requests. So now after they are blocked, are those requests still be counted towards the 5000 requests per hour limit?
]]>My docker container also has the ports exposed:
root@docker-***:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b1243cbeb471 idoop/zentao:latest "docker-entrypoint" 34 minutes ago Up 2 minutes (healthy) 80/tcp, 3306/tcp, 0.0.0.0:11443-11444->11443-11444/tcp zentao
The ports are set to be allowed in ufw
:
root@docker-***:~# ufw status
Status: active
To Action From
-- ------ ----
22/tcp LIMIT Anywhere
2375/tcp ALLOW Anywhere
2376/tcp ALLOW Anywhere
11443/tcp ALLOW Anywhere
11444/tcp ALLOW Anywhere
22/tcp (v6) LIMIT Anywhere (v6)
2375/tcp (v6) ALLOW Anywhere (v6)
2376/tcp (v6) ALLOW Anywhere (v6)
11443/tcp (v6) ALLOW Anywhere (v6)
11444/tcp (v6) ALLOW Anywhere (v6)
Some additional info:
root@docker-***:~# netstat -plunt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 951/sshd
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 699/systemd-resolve
tcp6 0 0 :::22 :::* LISTEN 951/sshd
tcp6 0 0 :::443 :::* LISTEN 1441/docker-proxy
tcp6 0 0 :::80 :::* LISTEN 1581/docker-proxy
tcp6 0 0 :::11443 :::* LISTEN 2349/docker-proxy
tcp6 0 0 :::11444 :::* LISTEN 1899/docker-proxy
udp 0 0 127.0.0.53:53 0.0.0.0:* 699/systemd-resolve
root@docker-***:~# iptables-save
# Generated by iptables-save v1.6.1 on Thu Jun 18 12:11:09 2020
*nat
:PREROUTING ACCEPT [88:5244]
:INPUT ACCEPT [50:2964]
:OUTPUT ACCEPT [82:6072]
:POSTROUTING ACCEPT [161:10036]
:DOCKER - [0:0]
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.21.0.0/16 ! -o br-beef654e1741 -j MASQUERADE
-A POSTROUTING -s 172.19.0.0/16 ! -o br-a7d9c45b68cc -j MASQUERADE
-A POSTROUTING -s 172.19.0.17/32 -d 172.19.0.17/32 -p tcp -m tcp --dport 443 -j MASQUERADE
-A POSTROUTING -s 172.19.0.17/32 -d 172.19.0.17/32 -p tcp -m tcp --dport 80 -j MASQUERADE
-A POSTROUTING -s 172.19.0.22/32 -d 172.19.0.22/32 -p tcp -m tcp --dport 11444 -j MASQUERADE
-A POSTROUTING -s 172.19.0.22/32 -d 172.19.0.22/32 -p tcp -m tcp --dport 11443 -j MASQUERADE
-A DOCKER -i docker0 -j RETURN
-A DOCKER -i br-beef654e1741 -j RETURN
-A DOCKER -i br-a7d9c45b68cc -j RETURN
-A DOCKER ! -i br-a7d9c45b68cc -p tcp -m tcp --dport 443 -j DNAT --to-destination 172.19.0.17:443
-A DOCKER ! -i br-a7d9c45b68cc -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.19.0.17:80
-A DOCKER ! -i br-a7d9c45b68cc -p tcp -m tcp --dport 11444 -j DNAT --to-destination 172.19.0.22:11444
-A DOCKER ! -i br-a7d9c45b68cc -p tcp -m tcp --dport 11443 -j DNAT --to-destination 172.19.0.22:11443
COMMIT
# Completed on Thu Jun 18 12:11:09 2020
# Generated by iptables-save v1.6.1 on Thu Jun 18 12:11:09 2020
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [2:128]
:DOCKER - [0:0]
:DOCKER-ISOLATION-STAGE-1 - [0:0]
:DOCKER-ISOLATION-STAGE-2 - [0:0]
:DOCKER-USER - [0:0]
:ufw-after-forward - [0:0]
:ufw-after-input - [0:0]
:ufw-after-logging-forward - [0:0]
:ufw-after-logging-input - [0:0]
:ufw-after-logging-output - [0:0]
:ufw-after-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-before-input - [0:0]
:ufw-before-logging-forward - [0:0]
:ufw-before-logging-input - [0:0]
:ufw-before-logging-output - [0:0]
:ufw-before-output - [0:0]
:ufw-logging-allow - [0:0]
:ufw-logging-deny - [0:0]
:ufw-not-local - [0:0]
:ufw-reject-forward - [0:0]
:ufw-reject-input - [0:0]
:ufw-reject-output - [0:0]
:ufw-skip-to-policy-forward - [0:0]
:ufw-skip-to-policy-input - [0:0]
:ufw-skip-to-policy-output - [0:0]
:ufw-track-forward - [0:0]
:ufw-track-input - [0:0]
:ufw-track-output - [0:0]
:ufw-user-forward - [0:0]
:ufw-user-input - [0:0]
:ufw-user-limit - [0:0]
:ufw-user-limit-accept - [0:0]
:ufw-user-logging-forward - [0:0]
:ufw-user-logging-input - [0:0]
:ufw-user-logging-output - [0:0]
:ufw-user-output - [0:0]
-A INPUT -j ufw-before-logging-input
-A INPUT -j ufw-before-input
-A INPUT -j ufw-after-input
-A INPUT -j ufw-after-logging-input
-A INPUT -j ufw-reject-input
-A INPUT -j ufw-track-input
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-ISOLATION-STAGE-1
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A FORWARD -o br-beef654e1741 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o br-beef654e1741 -j DOCKER
-A FORWARD -i br-beef654e1741 ! -o br-beef654e1741 -j ACCEPT
-A FORWARD -i br-beef654e1741 -o br-beef654e1741 -j ACCEPT
-A FORWARD -o br-a7d9c45b68cc -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o br-a7d9c45b68cc -j DOCKER
-A FORWARD -i br-a7d9c45b68cc ! -o br-a7d9c45b68cc -j ACCEPT
-A FORWARD -i br-a7d9c45b68cc -o br-a7d9c45b68cc -j ACCEPT
-A FORWARD -j ufw-before-logging-forward
-A FORWARD -j ufw-before-forward
-A FORWARD -j ufw-after-forward
-A FORWARD -j ufw-after-logging-forward
-A FORWARD -j ufw-reject-forward
-A FORWARD -j ufw-track-forward
-A OUTPUT -j ufw-before-logging-output
-A OUTPUT -j ufw-before-output
-A OUTPUT -j ufw-after-output
-A OUTPUT -j ufw-after-logging-output
-A OUTPUT -j ufw-reject-output
-A OUTPUT -j ufw-track-output
-A DOCKER -d 172.19.0.17/32 ! -i br-a7d9c45b68cc -o br-a7d9c45b68cc -p tcp -m tcp --dport 443 -j ACCEPT
-A DOCKER -d 172.19.0.17/32 ! -i br-a7d9c45b68cc -o br-a7d9c45b68cc -p tcp -m tcp --dport 80 -j ACCEPT
-A DOCKER -d 172.19.0.22/32 ! -i br-a7d9c45b68cc -o br-a7d9c45b68cc -p tcp -m tcp --dport 11444 -j ACCEPT
-A DOCKER -d 172.19.0.22/32 ! -i br-a7d9c45b68cc -o br-a7d9c45b68cc -p tcp -m tcp --dport 11443 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -i br-beef654e1741 ! -o br-beef654e1741 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -i br-a7d9c45b68cc ! -o br-a7d9c45b68cc -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -j RETURN
-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -o br-beef654e1741 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -o br-a7d9c45b68cc -j DROP
-A DOCKER-ISOLATION-STAGE-2 -j RETURN
-A DOCKER-USER -j RETURN
-A ufw-after-input -p udp -m udp --dport 137 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 138 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp -m tcp --dport 139 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp -m tcp --dport 445 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 67 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 68 -j ufw-skip-to-policy-input
-A ufw-after-input -m addrtype --dst-type BROADCAST -j ufw-skip-to-policy-input
-A ufw-after-logging-input -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW BLOCK] "
-A ufw-before-forward -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 4 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 12 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A ufw-before-forward -j ufw-user-forward
-A ufw-before-input -i lo -j ACCEPT
-A ufw-before-input -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-input -m conntrack --ctstate INVALID -j ufw-logging-deny
-A ufw-before-input -m conntrack --ctstate INVALID -j DROP
-A ufw-before-input -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 4 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 12 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A ufw-before-input -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A ufw-before-input -j ufw-not-local
-A ufw-before-input -d 224.0.0.251/32 -p udp -m udp --dport 5353 -j ACCEPT
-A ufw-before-input -d 239.255.255.250/32 -p udp -m udp --dport 1900 -j ACCEPT
-A ufw-before-input -j ufw-user-input
-A ufw-before-output -o lo -j ACCEPT
-A ufw-before-output -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-output -j ufw-user-output
-A ufw-logging-allow -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW ALLOW] "
-A ufw-logging-deny -m conntrack --ctstate INVALID -m limit --limit 3/min --limit-burst 10 -j RETURN
-A ufw-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW BLOCK] "
-A ufw-not-local -m addrtype --dst-type LOCAL -j RETURN
-A ufw-not-local -m addrtype --dst-type MULTICAST -j RETURN
-A ufw-not-local -m addrtype --dst-type BROADCAST -j RETURN
-A ufw-not-local -m limit --limit 3/min --limit-burst 10 -j ufw-logging-deny
-A ufw-not-local -j DROP
-A ufw-skip-to-policy-forward -j ACCEPT
-A ufw-skip-to-policy-input -j DROP
-A ufw-skip-to-policy-output -j ACCEPT
-A ufw-track-forward -p tcp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-forward -p udp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-output -p tcp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-output -p udp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-user-input -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name DEFAULT --mask 255.255.255.255 --rsource
-A ufw-user-input -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 30 --hitcount 6 --name DEFAULT --mask 255.255.255.255 --rsource -j ufw-user-limit
-A ufw-user-input -p tcp -m tcp --dport 22 -j ufw-user-limit-accept
-A ufw-user-input -p tcp -m tcp --dport 2375 -j ACCEPT
-A ufw-user-input -p tcp -m tcp --dport 2376 -j ACCEPT
-A ufw-user-input -p tcp -m tcp --dport 11443 -j ACCEPT
-A ufw-user-input -p tcp -m tcp --dport 11444 -j ACCEPT
-A ufw-user-limit -m limit --limit 3/min -j LOG --log-prefix "[UFW LIMIT BLOCK] "
-A ufw-user-limit -j REJECT --reject-with icmp-port-unreachable
-A ufw-user-limit-accept -j ACCEPT
COMMIT
# Completed on Thu Jun 18 12:11:09 2020
My DigitalOcean firewall settings look like this:
I’m also using Cloudflare, but I do not have the firewall enabled there.
Could anyone point me in the right direction on how to open the ports I need, because I’m out of ideas at that point?
Thanks!
]]>ufw shows port 3306 open iptables is not configured and the droplet firewall shows that it should be allowed. I have confirmed that my ip address is correct.
Please advise.
from droplet: user@host:~$ sudo ufw status [sudo] password for user: Status: active
To Action From
22 ALLOW Anywhere Apache Full ALLOW Anywhere 21/tcp ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 3306 ALLOW Anywhere 22 (v6) ALLOW Anywhere (v6) Apache Full (v6) ALLOW Anywhere (v6) 21/tcp (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) 3306 (v6) ALLOW Anywhere (v6)
user@host:~$ sudo iptables -nL -V iptables v1.6.1
from DO interface:
Firewalls Default Inbound Type Protocol Port Range Sources SSH TCP 22 x.x.x.x HTTP TCP 80 All IPv4 All IPv6 HTTPS TCP 443 All IPv4 All IPv6 MySQL TCP 3306 x.x.x.x Outbound Type Protocol Port Range Destinations ICMP ICMP All IPv4 All IPv6 All TCP TCP All ports All IPv4 All IPv6 MySQL TCP 3306 All IPv4 All IPv6 All UDP UDP All ports All IPv4 All IPv6
]]>How to configure this?
I am looking for a detailed answer as I am new here on DigitalOcean.
Thanks.
]]>sudo netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 692/systemd-resolve
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 877/sshd
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 937/postgres
tcp 0 0 0.0.0.0:9000 0.0.0.0:* LISTEN 1184/python3.6
tcp6 0 0 :::22 :::* LISTEN 877/sshd
tcp6 0 0 :::5432 :::* LISTEN 937/postgres
sudo ufw status
Status: active
To Action From
-- ------ ----
9000/tcp ALLOW Anywhere
9001/tcp ALLOW Anywhere
10001/tcp ALLOW Anywhere
10000/tcp ALLOW Anywhere
5432/tcp ALLOW Anywhere
22/tcp ALLOW Anywhere
22 ALLOW Anywhere
9000/tcp (v6) ALLOW Anywhere (v6)
9001/tcp (v6) ALLOW Anywhere (v6)
10001/tcp (v6) ALLOW Anywhere (v6)
10000/tcp (v6) ALLOW Anywhere (v6)
5432/tcp (v6) ALLOW Anywhere (v6)
22/tcp (v6) ALLOW Anywhere (v6)
22 (v6) ALLOW Anywhere (v6)
Can someone help me, please?
]]>I have checked the ufw firewall and flushed ‘Iptable’ rules but still the ping result is unsatisfactory. I need to check the network latency to the droplet.
$ ping 159.65.148.241 PING 159.65.148.241 (159.65.148.241): 56 data bytes Request timeout for icmp_seq 0 Request timeout for icmp_seq 1 Request timeout for icmp_seq 2
Am able to ping the box using the private.
$ ping 10.122.0.2 PING 10.122.0.2 (10.122.0.2) 56(84) bytes of data. 64 bytes from 10.122.0.2: icmp_seq=1 ttl=64 time=3.10 ms 64 bytes from 10.122.0.2: icmp_seq=2 ttl=64 time=1.39 ms 64 bytes from 10.122.0.2: icmp_seq=3 ttl=64 time=0.824 ms
Upon searching this error on Google, there were some suggestions that it could be a hosting issue where the host has blocked Facebook access to my site.
Could this be true? If not, kindly assist with whatever solution.
]]>However, how many IPs (or IP ranges) I can insert in a firewall rule?
For example, if I want to block a list of hundreds/thousands of IPs (blacklist), can I do that?
Probably you should also clarify that in the official docs if a limit exists.
]]>I need to a client to connect to specific service inside my kubernetes cluster. I try using a load balancer and work, the problem whit this approach is security. I cant restrict access to the service to a single IP in the load balancer, so is published to all internet. Also dont what to user ingress (i want to block at TCP level), so, what are my alternatives ?
thank you
]]>Terraform ist ein von HashiCorp entwickeltes Infrastruktur-als-Code-Tool, das Entwicklern bei der Bereitstellung, Aktualisierung und Entfernung verschiedener Assets ihrer Infrastruktur auf effiziente und skalierbare Weise hilft.
Entwickler können Terraform verwenden, um verschiedene Umgebungen zu organisieren, Änderungen durch Versionskontrolle zu verfolgen und sich wiederholende Arbeiten zu automatisieren, um menschliche Fehler einzuschränken. Es bietet auch eine Möglichkeit für Teams, gemeinsam an der Verbesserung ihrer Infrastruktur durch freigegebene Konfigurationen zu arbeiten.
In diesem Tutorial werden Sie die bestehende DigitalOcean-Infrastruktur in Terraform importieren. Am Ende dieses Tutorials werden Sie in der Lage sein, Terraform für Ihre gesamte bestehende Infrastruktur zu verwenden und zusätzlich neue Assets zu erstellen.
doctl
GitHub-Seite befolgen. Sie können das folgende Tutorial als Anleitung zur Verwendung von So verwenden Sie Doctl, den offiziellen DigitalOcean Comand-Line Client lesen.In diesem ersten Schritt installieren Sie Terraform auf Ihrem lokalen Rechner. Dieser Schritt beschreibt die Installation der Linux-Binary. Wenn Sie Windows oder Mac verwenden, können Sie die Seite Terraform herunterladen auf der Terraform-Website aufrufen.
Gehen Sie zu dem Ordner, in den Sie Terraform auf Ihrem lokalen Rechner herunterladen möchten, und verwenden Sie dann das Tool wget
, um die Terraform 0.12.12
Binary herunterzuladen:
- cd /tmp
- wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Zur Überprüfung, ob die sha256
-Prüfsumme mit dem auf der Terraform-Website angegebenen Wert übereinstimmt, laden Sie die Prüfsummendatei mit dem folgenden Befehl herunter:
- wget -q https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_SHA256SUMS
Führen Sie dann den folgenden Befehl zur Verifizierung der Prüfsummen aus:
- sha256sum -c --ignore-missing terraform_0.12.12_SHA256SUMS
Die heruntergeladene SHA256SUMS
-Datei listet die Dateinamen und ihre Hashes auf. Dieser Befehl sucht lokal nach der gleichen Datei terraform_0.12.12_SHA256SUMS
und prüft dann die Übereinstimmung der Hashes it dem Flag -c
. Da in dieser Datei mehr als ein Dateiname und seine Plattform aufgeführt sind, verwenden Sie das Flag --ignore-missing
, um Fehler in Ihrer Ausgabe zu vermeiden, da Sie keine Kopie der anderen Dateien haben.
Sie werden eine Ausgabe wie die folgende sehen:
Outputterraform_0.12.12_linux_amd64.zip: OK
Verwenden Sie unzip
, um die Binary zu extrahieren:
- sudo unzip terraform_0.12.12_linux_amd64.zip -d /usr/local/bin/
Überprüfen Sie nun, ob Terraform korrekt installiert ist, indem Sie die Version überprüfen:
- terraform version
Sie sehen eine Ausgabe, die der folgenden ähnelt:
OutputTerraform v0.12.12
Nachdem Sie Terraform auf Ihrem lokalen Rechner installiert haben, werden Sie nun die Konfigurationsdateien vorbereiten.
In diesem Schritt importieren Sie Ihre vorhandenen Assets in Terraform, indem Sie ein Projektverzeichnis erstellen und Konfigurationsdateien schreiben. Da Terraform derzeit die Erstellung von Konfigurationen aus dem Befehl import
nicht unterstützt, müssen Sie diese Konfigurationen manuell erstellen.
Führen Sie den folgenden Befehl aus, um Ihr Projektverzeichnis zu erstellen:
- mkdir -p do_terraform_import
Wechseln Sie dann in dieses Verzeichnis mit:
- cd do_terraform_import
In diesem Schritt erstellen Sie drei zusätzliche Dateien, die die erforderlichen Konfigurationen enthalten. Ihre Verzeichnisstruktur für dieses Projekt wird wie folgt aussehen:
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
└── provider.tf
Zu Beginn erstellen Sie die Datei provider.tf
, um Ihr DigitalOcean Zugangs-Token als Umgebungsvariable zu definieren, anstatt es fest in Ihre Konfiguration zu kodieren.
Warnung: Ihr Zugangs-Token ermöglicht den Zugriff auf Ihre komplette Infrastruktur mit uneingeschränktem Zugriff, behandeln Sie es also als solches. Stellen Sie sicher, dass Sie die einzige Person mit Zugriff auf den Rechner sind, auf dem dieses Token gespeichert ist.
Neben Ihrem Zugangs-Token geben Sie auch an, welchen Provider Sie verwenden möchten. In diesem Tutorial ist das digitalocean
. Eine vollständige Liste der verfügbaren Datenquellen und Ressourcen für DigitalOcean mit Terraform finden Sie auf der Seite der Provider auf deren Website.
Erstellen und bearbeiten Sie provider.tf
mit dem folgenden Befehl:
- nano provider.tf
Fügen Sie den folgenden Inhalt in die Datei provider.tf
ein:
variable "do_token" {}
provider "digitalocean" {
token = "${var.do_token}"
version = "1.9.1"
}
In dieser Datei fügen Sie Ihr DigitalOcean Zugangs-Token als Variable hinzu, die Terraform als Identifikation für die DigitalOcean-API verwendet. Darüber hinaus geben Sie die Version des DigitalOcean-Provider-Plugins an. Terraform empfiehlt, dass Sie die Version des von Ihnen verwendeten Providers angeben, damit zukünftige Aktualisierungen Ihre aktuelle Einrichtung nicht potenziell beeinträchtigen.
Jetzt erstellen Sie die Datei digitalocean_droplet.tf
. Hier geben Sie die Ressource an, die Sie verwenden werden, in diesem Fall: droplet
.
Erstellen Sie die Datei mit dem folgenden Befehl:
- nano digitalocean_droplet.tf
Fügen Sie die folgende Konfiguration hinzu:
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Hier geben Sie vier Parameter an:
name
: Der Droplet-Name.
region
: Der Bereich, in dem sich das Droplet befindet.
tags
: Eine Liste der Tags, die auf dieses Droplet angewendet werden.
count
: die Anzahl der für diese Konfiguration erforderlichen Ressourcen.
Als Nächstes erstellen Sie eine Konfigurationsdatei für Ihre Firewall. Erstellen Sie die Datei digitalocean_firewall.tf
mit dem folgenden Befehl:
- nano digitalocean_firewall.tf
Fügen Sie der Datei folgenden Inhalt hinzu:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
}
Hier geben Sie den Namen der zu importierenden Firewall und die Tags der Droplets an, für die die Firewall-Regeln gelten sollen. Schließlich definiert der Wert count
von 1
die erforderliche Anzahl der jeweiligen Ressource.
Anmerkung: Sie können Firewall-Ressourcen auch in die Datei digitalocean_droplet.tf
aufnehmen. Aber wenn Sie mehrere Umgebungen haben, in denen sich mehrere Droplets dieselbe Firewall teilen, wird empfohlen, sie zu trennen, falls Sie nur ein einziges Droplet entfernen möchten. Die Firewall wird dann nicht beeinträchtigt.
Jetzt ist es an der Zeit, diese Änderungen zu initialisieren, damit Terraform die erforderlichen Abhängigkeiten herunterladen kann. Dazu verwenden Sie den Befehl terraform init
, der es Ihnen ermöglicht, ein Arbeitsverzeichnis zu initialisieren, das Terraform-Konfigurationsdateien enthält.
Führen Sie diesen Befehl von Ihrem Projektverzeichnis aus:
- terraform init
Sie sehen die folgende Ausgabe:
OutputTerraform has been successfully initialized!
Terraform hat das Arbeitsverzeichnis durch das Herunterladen von Plugins, die Suche nach Modulen usw. erfolgreich vorbereitet. Als Nächstes beginnen Sie damit, Ihre Assets in Terraform zu importieren.
In diesem Schritt importieren Sie Ihre DigitalOcean-Assets in Terraform. Sie verwenden doctl
, um die ID-Nummern Ihrer Droplets zu finden, bevor Sie Ihre Assets importieren. Anschließend überprüfen Sie die Importkonfiguration mit den Befehlen terraform show
und terraform plan
.
Zu Beginn exportieren Sie Ihr DigitalOcean Zugangs-Token als Umgebungsvariable, die Sie dann während der Laufzeit in Terraform injizieren.
Exportieren Sie es als Umgebungsvariable in Ihre aktuelle Shell-Sitzung mit dem folgenden Befehl:
- export DO_TOKEN="YOUR_TOKEN"
Um Ihre vorhandenen Droplets und Firewalls zu importieren, benötigen Sie deren ID-Nummern. Sie können doctl
, die Befehlszeilenschnittstelle für die DigitalOcean-API, verwenden. Führen Sie den folgenden Befehl aus, um Ihre Droplets aufzulisten und auf ihre IDs zuzugreifen:
- doctl compute droplet list
Sie sehen eine Ausgabe, die der folgenden ähnelt:
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags Features Volumes
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 2048 1 50 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64
Jetzt importieren Sie Ihr vorhandenes Droplet und Ihre Firewall in Terraform:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET_ID
Sie verwenden das Flag -var
, um den Wert Ihres DigitalOcean Zugangs-Tokens anzugeben, den Sie zuvor in Ihre Shell-Sitzung exportiert haben. Dies ist erforderlich, damit die DigitalOcean-API überprüfen kann, wer Sie sind, und Änderungen an Ihrer Infrastruktur vornehmen kann.
Führen Sie nun denselben Befehl für Ihre Firewall aus:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL_ID
Mit dem Befehl terraform show
können Sie überprüfen, ob der Import erfolgreich war. Dieser Befehl liefert eine von Menschen lesbare Ausgabe Ihres Infrastrukturstatus. Er kann verwendet werden, um einen Plan zu überprüfen und sicherzustellen, dass die gewünschten Änderungen ausgeführt werden, oder um den aktuellen Zustand aus Sicht von Terraform zu inspizieren.
In diesem Zusammenhang bezieht sich state auf die Zuordnung Ihrer DigitalOcean-Assets zur Terraform-Konfiguration, die Sie geschrieben haben, und auf die Verfolgung von Metadaten. Auf diese Weise können Sie bestätigen, dass es keinen Unterschied zwischen den vorhandenen DigitalOcean-Assets, die Sie importieren möchten, und den Assets, die Terraform nachverfolgt, gibt:
- terraform show
Sie sehen eine Ausgabe, die dieser ähnelt:
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
Sie werden in der Ausgabe zwei Ressourcen zusammen mit ihren Attributen sehen.
Nachdem Sie Ihr Droplet und Ihre Firewall in den Terraform-Status importiert haben, müssen Sie sicherstellen, dass die Konfigurationen den aktuellen Status der importierten Assets repräsentieren. Dazu müssen Sie das image
Ihres Droplets und dessen size
angeben. Diese beiden Werte finden Sie in der Ausgabe von terraform show
für die Ressource digitalocean_droplet.do_droplet
.
Öffnen Sie die Datei digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
In diesem Tutorial:
ubuntu-16-04-x64
.fra1
.terraform-testing
.Das Droplet, das Sie mit der Konfiguration in digitalocean_droplet.tf
importiert haben, sieht wie folgt aus:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
Als Nächstes fügen Sie die Firewall-Regeln hinzu. In unserem Beispiel sind die offenen Ports für eingehenden Datenverkehr 22
, 80
und 443
. Alle Ports sind für ausgehenden Datenverkehr geöffnet. Sie können diese Konfiguration entsprechend Ihrer offenen Ports anpassen.
Öffnen Sie digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Fügen Sie die folgende Konfiguration hinzu:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Diese Regeln replizieren den Status der vorhandenen Beispiel-Firewall. Wenn Sie den Datenverkehr auf andere IP-Adressen, Ports oder ein anderes Protokoll beschränken möchten, können Sie die Datei so anpassen, dass sie Ihre vorhandene Firewall repliziert.
Nachdem Sie Ihre Terraform-Dateien aktualisiert haben, verwenden Sie den Befehl plan
, um zu sehen, ob die von Ihnen vorgenommenen Änderungen den Status der vorhandenen Assets auf DigitalOcean replizieren.
Der Befehl terraform plan
wird als Testlauf verwendet. Mit diesem Befehl können Sie überprüfen, ob die Änderungen, die Terraform vornehmen wird, die Änderungen sind, die Sie vornehmen möchten. Es wird empfohlen, diesen Befehl immer zur Bestätigung auszuführen, bevor Änderungen vorgenommen werden.
Führen Sie terraform plan
wie folgt aus:
- terraform plan -var "do_token=$DO_TOKEN"
Sie sehen eine Ausgabe, die der folgenden Ausgabe ähnelt:
OutputNo changes. Infrastructure is up-to-date.
Sie haben vorhandene DigitalOcean-Assets erfolgreich in Terraform importiert und können jetzt über Terraform Änderungen an Ihrer Infrastruktur vornehmen, ohne das Risiko einzugehen, bestehende Assets versehentlich zu löschen oder zu modifizieren.
In diesem Schritt fügen Sie Ihrer bestehenden Infrastruktur zwei zusätzliche Droplets hinzu. Das Hinzufügen von Assets zu Ihrer bestehenden Infrastruktur kann z. B. dann sinnvoll sein, wenn Sie eine Live-Website haben und während der Arbeit an dieser Website keine potenziell schädlichen Änderungen vornehmen wollen. Stattdessen können Sie ein weiteres Droplet als Entwicklungsumgebung hinzufügen und an Ihrem Projekt in derselben Umgebung wie das Produktions-Droplet arbeiten, ohne dass Sie dabei ein potenzielles Risiko eingehen.
Öffnen Sie jetzt digitalocean_droplet.tf
, um die Regeln für Ihre neuen Droplets hinzuzufügen:
- nano digitalocean_droplet.tf
Fügen Sie in Ihrer Datei die folgenden Zeilen hinzu:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
Mit dem Meta-Argument count
teilen Sie Terraform mit, wie viele Droplets mit den gleichen Spezifikationen Sie erstellen möchten. Diese neuen Droplets werden ebenfalls zu Ihrer bestehenden Firewall hinzugefügt, da Sie das gleiche Tag wie bei Ihrer Firewall angeben.
Wenden Sie diese Regeln an, um die Änderungen zu überprüfen, die Sie in digitalocean_droplet.tf
angeben:
- terraform plan -var "do_token=$DO_TOKEN"
Vergewissern Sie sich, dass die Änderungen, die Sie vornehmen möchten, in der Ausgabe dieses Befehls repliziert werden.
Sie sehen eine Ausgabe, die der folgenden ähnelt:
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-18-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Wenn Sie mit der Ausgabe zufrieden sind, verwenden Sie den Befehl terraform apply
, um die von Ihnen angegebenen Änderungen auf den Status der Konfiguration anzuwenden:
- terraform apply -var "do_token=$DO_TOKEN"
Bestätigen Sie die Änderungen, indem Sie in der Befehlszeile yes
eingeben. Nach erfolgreicher Ausführung sehen Sie eine Ausgabe, die der folgenden ähnelt:
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
Sie sehen zwei neue Droplets in Ihrem DigitalOcean Web-Panel:
Sie sehen sie auch an Ihre bestehende Firewall angebunden:
Sie haben mit Terraform unter Verwendung Ihrer bereits vorhandenen Assets neue Assets erstellt. Um zu erfahren, wie man diese Assets vernichtet, können Sie optional den nächsten Schritt durchführen.
In diesem Schritt vernichten Sie Assets, die Sie importiert und erstellt haben, indem Sie die Konfiguration anpassen.
Beginnen Sie, indem Sie digitalocean_droplet.tf
öffnen:
- nano digitalocean_droplet.tf
Setzen Sie in der Datei den count
auf 0, wie im Folgenden gezeigt:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
Speichern und schließen Sie die Datei.
Öffnen Sie Ihre Firewall-Konfigurationsdatei, um count
auch dort zu ändern:
- nano digitalocean_firewall.tf
Setzten Sie count
auf 0
, wie in der folgenden hervorgehobenen Zeile.
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "0"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Speichern und schließen Sie die Datei.
Wenden Sie nun diese Änderungen mit dem folgenden Befehl an:
- terraform apply -var "do_token=${DO_TOKEN}"
Terraform wird Sie zu der Bestätigung auffordern, dass diese Droplets und die Firewall vernichtet werden sollen. Dadurch werden alle über Terraform importierten und erstellten Assets vernichtet. Stellen Sie daher vor der Eingabe von yes
sicher, dass Sie fortfahren möchten.
Sie sehen eine Ausgabe, die der folgenden ähnelt:
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
Sie haben alle von Terraform verwalteten Assets gelöscht. Dies ist ein nützlicher Workflow, wenn Sie ein Asset nicht länger benötigen oder herunterskalieren möchten.
In diesem Tutorial haben Sie Terraform installiert, vorhandene Assets importiert, neue Assets erstellt und diese optional vernichtet. Sie können diesen Workflow auf ein größeres Projekt skalieren, wie z. B. auf die Bereitstellung eines produktionsbereiten Kubernetes-Clusters. Mit Terraform könnten Sie alle Knoten, DNS-Einträge, Firewalls, Speicher und andere Assets verwalten sowie die Versionskontrolle zur Verfolgung von Änderungen und zur Zusammenarbeit mit einem Team nutzen.
Um weitere Funktionen von Terraform zu erkunden, lesen Sie deren Dokumentation. Sie können auch den Terraform-Inhalt von DigitalOcean für weitere Tutorials sowie Fragen und Antworten lesen.
]]>Terraform est un outil d’infrastructure as code (infrastructure en tant que code) créé par HashiCorp qui aide les développeurs à déployer, mettre à jour et supprimer les différentes ressources de leur infrastructure d’une manière efficace et plus évolutive.
Les développeurs peuvent utiliser Terraform pour organiser différents environnements, suivre les changements par le contrôle des versions et automatiser les travaux répétitifs pour limiter les erreurs humaines. Il offre également aux équipes un moyen de collaborer pour améliorer leur infrastructure grâce à des configurations partagées.
Dans ce tutoriel, vous allez importer les infrastructures DigitalOcean existantes dans Terraform. Au terme de ce tutoriel, vous serez en mesure d’utiliser Terraform pour toute votre infrastructure existante en plus de créer de nouvelles ressources.
doctl
. Vous pouvez lire le tutoriel Comment utiliser Doctl, le client de ligne de commande DigitalOcean officiel.Au cours de cette première étape, vous allez installer Terraform sur votre machine locale. Cette étape détaille l’installation du binaire Linux. Si vous utilisez Windows ou Mac, vous pouvez consulter la page de téléchargement de Terraform sur le site web de Terraform.
Déplacez-vous vers le dossier dans lequel vous souhaitez télécharger Terraform sur votre machine locale, puis utilisez l’outil wget
pour télécharger le binaire Terraform 0.12.12
:
- cd /tmp
- wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Pour vérifier si la somme de contrôle du sha256
est la même que celle fournie sur le site web de Terraform, vous téléchargerez le fichier de la somme de contrôle avec la commande suivante :
- wget -q https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_SHA256SUMS
Ensuite, exécutez la commande suivante pour vérifier les sommes de contrôle :
- sha256sum -c --ignore-missing terraform_0.12.12_SHA256SUMS
Le fichier SHA256SUMS
que vous avez téléchargé énumère les noms de fichiers et leurs hachages. Cette commande recherchera le même fichier terraform_0.12.12_SHA256SUMS
localement, puis vérifiera que les hachages correspondent à l’aide de l’indicateur-c
. Comme ce fichier a plus d’un nom de fichier et que sa plate-forme est répertoriée, vous utilisez l’indicateur--ignore-missing
pour éviter les erreurs dans votre sortie parce que vous n’avez pas de copie des autres fichiers
Vous verrez une sortie semblable à ceci :
Outputterraform_0.12.12_linux_amd64.zip: OK
Utilisez unzip
pour extraire le binaire :
- sudo unzip terraform_0.12.12_linux_amd64.zip -d /usr/local/bin/
Vérifiez maintenant si Terraform est installé correctement en vérifiant la version :
- terraform version
Vous verrez une sortie semblable à ce qui suit :
OutputTerraform v0.12.12
Vous avez installé Terraform sur votre machine locale, vous allez maintenant préparer les fichiers de configuration.
Dans cette étape, vous allez importer vos ressources existantes dans Terraform en créant un répertoire de projet et en écrivant des fichiers de configuration. Puisque Terraform ne supporte pas la génération de configurations à partir de la commande import
pour le moment, vous devez créer ces configurations manuellement.
Exécutez la commande suivante pour créer votre répertoire de projet :
- mkdir -p do_terraform_import
Ensuite, entrez dans ce répertoire avec :
- cd do_terraform_import
Dans cette étape, vous allez créer trois fichiers supplémentaires qui contiendront les configurations requises. La structure de votre répertoire pour ce projet ressemblera à ceci :
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
└── provider.tf
Pour commencer, vous allez créer le fichier provider.tf
pour définir votre jeton d’accès DigitalOcean comme une variable d’environnement au lieu de le coder en dur dans votre configuration.
Attention : votre jeton d’accès donne accès à l’ensemble de votre infrastructure avec un accès illimité, traitez-le donc comme tel. Assurez-vous que vous êtes le seul à avoir accès à la machine où ce jeton est stocké.
Outre votre jeton d’accès, vous allez également spécifier quel fournisseur vous souhaitez utiliser. Dans ce tutoriel, ce sera digitalocean
. Pour une liste complète des sources de données et des ressources disponibles pour DigitalOcean avec Terraform, visitez la page des fournisseurs sur leur site web.
Créez et modifiez provider.tf
avec la commande suivante :
- nano provider.tf
Ajoutez le contenu suivant dans le fichier provider.tf
:
variable "do_token" {}
provider "digitalocean" {
token = "${var.do_token}"
version = "1.9.1"
}
Dans ce fichier, vous ajoutez votre jeton d’accès DigitalOcean comme variable, que Terraform utilisera comme identification pour l’API DigitalOcean. Vous spécifiez également la version du plugin du fournisseur DigitalOcean. Terraform vous recommande de spécifier la version du fournisseur que vous utilisez afin que les futures mises à jour n’abiment pas votre configuration actuelle.
Vous allez maintenant créer le fichier digitalocean_droplet.tf
. Ici, vous allez spécifier la ressource que vous allez utiliser, dans ce cas : droplet
.
Créez le fichier avec la commande suivante :
- nano digitalocean_droplet.tf
Ajoutez la configuration suivante :
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Ici, vous spécifiez quatre paramètres :
name
: le nom de la Droplet.
region
: la région dans laquelle est située la Droplet.
tags
: une liste des étiquettes qui sont appliquées à cette Droplet.
count
: le nombre de ressources nécessaires pour cette configuration.
Ensuite, vous allez créer un fichier de configuration pour votre pare-feu. Créez le fichier digitalocean_firewall.tf
avec la commande suivante :
- nano digitalocean_firewall.tf
Ajoutez le contenu suivant au fichier :
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
}
Ici, vous spécifiez le nom du pare-feu que vous souhaitez importer et les étiquettes des Droplets auxquelles les règles du pare-feu s’appliquent. Enfin, la valeur count
de 1
définit le nombre requis de la ressource particulière.
Remarque : vous pouvez également inclure des ressources de pare-feu dans le fichier digitalocean_droplet.tf
. Cependant, si vous avez plusieurs environnements où plusieurs Droplets partagent le même pare-feu, il est conseillé de les séparer au cas où vous ne voudriez supprimer qu’une seule Droplet. Le pare-feu ne sera alors pas affecté.
Maintenant, il est temps d’initialiser ces modifications afin que Terraform puisse télécharger les dépendances requises. Pour cela, vous allez utiliser la commande terraform init
, ce qui vous permettra d’initialiser un répertoire de travail contenant les fichiers de configuration de Terraform.
Exécutez cette commande depuis votre répertoire de projet :
- terraform init
Vous verrez la sortie suivante :
OutputTerraform has been successfully initialized!
Terraform a préparé avec succès le répertoire de travail en téléchargeant des plugins, en recherchant des modules, etc. Ensuite, vous allez commencer à importer vos ressources dans Terraform.
Dans cette étape, vous allez importer vos ressources DigitalOcean dans Terraform. Vous allez utiliser doctl
pour trouver les numéros d’identification de vos Droplets avant d’importer vos ressources. Ensuite, vous allez vérifier la configuration d’importation avec les commandes terraform show
et terraform plan
.
Pour commencer, vous allez exporter votre jeton d’accès DigitalOcean comme variable d’environnement, que vous allez ensuite injecter dans Terraform pendant l’exécution.
Exportez-le comme une variable d’environnement dans votre session shell en cours avec la commande suivante :
- export DO_TOKEN="YOUR_TOKEN"
Pour importer votre Droplet et votre pare-feu existants, vous aurez besoin de leurs numéros d’identification. Vous pouvez utiliser doctl
, l’interface en ligne de commande de l’API DigitalOcean. Exécutez la commande suivante pour énumérer vos Droplets et accéder à leurs ID :
- doctl compute droplet list
Vous verrez une sortie semblable à ce qui suit :
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags Features Volumes
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 2048 1 50 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64
Maintenant, vous allez importer votre Droplet et votre pare-feu existants dans Terraform :
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET_ID
Vous utilisez l’indicateur -var
pour spécifier la valeur de votre jeton d’accès DigitalOcean que vous avez précédemment exporté vers votre session shell. Cela est nécessaire pour que l’API DigitalOcean puisse vérifier qui vous êtes et appliquer les changements à votre infrastructure.
Maintenant, exécutez la même commande pour votre pare-feu :
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL_ID
Vous allez vérifier que l’importation a réussi en utilisant la commande terraform show
. Cette commande fournit un résultat lisible par l’homme de l’état de votre infrastructure. Elle peut être utilisée pour inspecter un plan afin de s’assurer que les changements souhaités vont être exécutés, ou pour inspecter l’état actuel tel que Terraform le voit.
Dans ce contexte, state fait référence à la mise en correspondance de vos ressources DigitalOcean avec la configuration Terraform que vous avez écrite et le suivi des métadonnées. Cela vous permet de confirmer qu’il n’y a aucune différence entre les ressources DigitalOcean existantes que vous souhaitez importer et les ressources dont Terraform assure le suivi :
- terraform show
Vous verrez une sortie semblable à celle-ci :
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
Vous verrez deux ressources dans la sortie avec leurs attributs.
Après avoir importé votre Droplet et votre pare-feu dans l’état Terraform, vous devez vous assurer que les configurations représentent l’état actuel des ressources importées. Pour ce faire, vous allez spécifier les valeurs image
et size
de votre Droplet. Vous pouvez trouver ces deux valeurs dans la sortie de terraform show
pour la ressource digitalocean_droplet.do_droplet
.
Ouvrez le fichier digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
Dans ce tutoriel :
ubuntu-16-04-x64
.fra1
.terraform-testing
.La Droplet que vous avez importée en utilisant la configuration dans digitalocean_droplet.tf
ressemblera à ceci :
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
Ensuite, vous allez ajouter dans les règles du pare-feu. Dans notre exemple, les ports ouverts pour le trafic entrant sont 22
, 80
et 443
. Tous les ports sont ouverts pour le trafic sortant. Vous pouvez adapter cette configuration en fonction de vos ports ouverts.
Ouvrez digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Ajoutez la configuration suivante :
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Ces règles reproduisent l’état de l’exemple de pare-feu existant. Si vous souhaitez limiter le trafic à différentes adresses IP, différents ports ou différents protocoles, vous pouvez ajuster le fichier pour reproduire votre pare-feu existant.
Après avoir mis à jour vos fichiers Terraform, vous utiliserez la commande plan
pour voir si les modifications que vous avez apportées reproduisent l’état des ressources existantes sur DigitalOcean.
La commande terraform plan
est utilisée à titre d’essai. Avec cette commande, vous pouvez vérifier si les changements que Terraform va apporter sont bien ceux que vous voulez faire. Il est conseillé de toujours exécuter cette commande pour confirmation avant d’appliquer des modifications.
Exécutez terraform plan
avec ce qui suit :
- terraform plan -var "do_token=$DO_TOKEN"
Vous verrez une sortie semblable à la sortie qui suit :
OutputNo changes. Infrastructure is up-to-date.
Vous avez réussi à importer des ressources DigitalOcean existantes dans Terraform, et vous pouvez maintenant apporter des modifications à votre infrastructure grâce à Terraform sans risquer de supprimer ou de modifier accidentellement des ressources existantes.
Dans cette étape, vous allez ajouter deux Droplets supplémentaires à votre infrastructure existante. Il peut être utile d’ajouter des ressources de cette manière à votre infrastructure existante, par exemple si vous avez un site web en ligne et que vous ne voulez pas y apporter de modifications susceptibles de le casser pendant que vous y travaillez. Au lieu de cela, vous pouvez ajouter une Droplet supplémentaire à utiliser comme environnement de développement et travailler sur votre projet dans le même environnement que la Droplet de production, sans aucun risque.
Maintenant, ouvrez digitalocean_droplet.tf
pour ajouter les règles de vos nouvelles Droplets :
- nano digitalocean_droplet.tf
Ajoutez les lignes suivantes à votre fichier :
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
Vous utilisez le méta-argument count
pour dire à Terraform combien de Droplets ayant les mêmes spécifications vous voulez. Ces nouvelles Droplets seront également ajoutées à votre pare-feu existant, car vous spécifiez la même étiquette que celle de votre pare-feu.
Appliquez ces règles pour vérifier les modifications que vous spécifiez dans digitalocean_droplet.tf
:
- terraform plan -var "do_token=$DO_TOKEN"
Vérifiez que les modifications que vous souhaitez apporter sont reproduites dans la sortie de cette commande.
Vous verrez une sortie semblable à ce qui suit :
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-18-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Une fois que vous êtes satisfait de la sortie, utilisez la commande terraform apply
pour appliquer les changements que vous avez spécifiés à l’état de la configuration :
- terraform apply -var "do_token=$DO_TOKEN"
Confirmez les changements en entrant yes
sur la ligne de commande. Une fois l’exécution réussie, vous verrez une sortie semblable à ce qui suit :
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
Vous verrez deux nouvelles Droplets dans votre panneau web DigitalOcean :
Vous les verrez également attachés à votre pare-feu existant :
Vous avez créé de nouvelles ressources avec Terraform en utilisant vos ressources existantes. Pour apprendre comment détruire ces ressources, vous pouvez éventuellement suivre l’étape suivante.
Dans cette étape, vous allez détruire les ressources que vous avez importées et créées en ajustant la configuration.
Commencez par ouvrir digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
Dans le fichier, définissez count
sur 0 comme suit :
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
Enregistrez et quittez le fichier.
Ouvrez le fichier de configuration de votre pare-feu pour également y modifier count
:
- nano digitalocean_firewall.tf
Définissez count
sur 0
comme dans la ligne surlignée suivante :
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "0"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Enregistrez et quittez le fichier.
Appliquez maintenant ces changements avec la commande suivante :
- terraform apply -var "do_token=${DO_TOKEN}"
Terraform va vous demander de confirmer si vous souhaitez détruire les Droplets et le pare-feu. Cela détruira toutes les ressources que vous avez importées et créées via Terraform. Assurez-vous donc de vérifier que vous souhaitez poursuivre avant de taper yes
.
Vous verrez un résultat semblable à :
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
Vous avez supprimé toutes les ressources gérées par Terraform. Il s’agit d’un flux de travail utile si vous n’avez plus besoin d’une ressource ou si vous réduisez vos capacités.
Dans ce tutoriel, vous avez installé Terraform, importé des ressources existantes, créé de nouvelles ressources et éventuellement détruit ces ressources. Vous pouvez adapter ce flux de travail à un projet plus vaste, tel que le déploiement d’un cluster Kubernetes prêt à la production. Avec Terraform, vous avez pu gérer tous les nœuds, les entrées DNS, les pare-feu, le stockage et d’autres ressources, ainsi qu’utiliser le contrôle de version pour suivre les changements et collaborer avec une équipe.
Pour découvrir les autres caractéristiques de Terraform, consultez la documentation. Vous pouvez également consulter le contenu DigitalOcean relatif à Terraform pour découvrir d’autres tutoriels et des questions-réponses
]]>O Terraform é uma infraestrutura como ferramenta de código criada pela HashiCorp que ajuda os desenvolvedores a implantar, atualizar e remover diferentes ativos de sua infraestrutura de maneira eficiente e mais escalonável.
Os desenvolvedores podem usar o Terraform para organizar diferentes ambientes, rastrear alterações através do controle de versão e automatizar trabalhos repetitivos para limitar o erro humano. Ele também fornece uma maneira das equipes colaborarem na melhoria da sua infraestrutura através de configurações compartilhadas.
Neste tutorial, você importará a infraestrutura existente da DigitalOcean para o Terraform. Até o final deste tutorial, você será capaz de usar o Terraform para toda a sua infraestrutura existente, além de criar ativos.
doctl
. Você pode ler o seguinte tutorial para obter orientações sobre Como usar o Doctl, o cliente de linha de comando oficial da DigitalOcean.Neste primeiro passo, você irá instalar o Terraform em sua máquina local. Esse passo detalha a instalação do binário do Linux. Caso esteja usando o Windows ou o Mac, verifique a página de download do Terraform no site do Terraform.
Vá até a pasta de sua máquina local na qual deseja baixar o Terraform e, em seguida, utilize a ferramenta wget
para baixar o binário 0.12.12
do Terraform:
- cd /tmp
- wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Para verificar se a soma de verificação de sha256
apresenta o mesmo valor fornecido no site do Terraform, você baixará o arquivo de soma de verificação com o seguinte comando:
- wget -q https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_SHA256SUMS
Em seguida, execute o comando a seguir para verificar as somas de verificação:
- sha256sum -c --ignore-missing terraform_0.12.12_SHA256SUMS
O arquivo SHA256SUMS
que você baixou lista os nomes dos arquivos e seus hashes. Esse comando irá procurar pelo mesmo arquivo terraform_0.12.12_SHA256SUMS
localmente e, então, verificar se as hashes correspondem usando o sinalizador -x
. Como esse arquivo tem mais de um nome de arquivo e tem sua plataforma listada, use o sinalizador --ignore-missing
para evitar erros no seu resultado, já que não tem uma cópia dos outros arquivos.
Você verá um resultado como o seguinte:
Outputterraform_0.12.12_linux_amd64.zip: OK
Use unzip
para extrair o binário:
- sudo unzip terraform_0.12.12_linux_amd64.zip -d /usr/local/bin/
Agora, verifique se o Terraform foi instalado corretamente, verificando a versão:
- terraform version
Você verá um resultado parecido com este:
OutputTerraform v0.12.12
Você instalou o Terraform na sua máquina local e agora irá preparar os arquivos de configuração.
Neste passo, você importará ativos existentes para o Terraform, criando um diretório de projeto e gravando os arquivos de configuração. Como o Terraform não oferece suporte à geração de configurações do comando import
neste momento, você precisa criar essas configurações manualmente.
Execute o comando a seguir para criar seu diretório de projeto:
- mkdir -p do_terraform_import
Em seguida, vá até esse diretório com:
- cd do_terraform_import
Neste passo, você criará três arquivos adicionas que terão as configurações necessárias. Sua estrutura de diretório para esse projeto ficará parecida com a seguinte:
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
└── provider.tf
Para começar, você criará o arquivo provider.tf
para definir seu token de acesso à DigitalOcean como uma variável de ambiente, em vez de embuti-lo em sua configuração.
Aviso: seu token de acesso dá acesso irrestrito à sua infraestrutura completa, então trate-o como tal. Certifique-se de que você é a única pessoa que tem acesso à máquina onde o token está armazenado.
Além do seu token de acesso, você também irá especificar qual provedor quer usar. Neste tutorial, será digitalocean
. Para uma lista completa das fontes de dados e recursos disponíveis para a DigitalOcean com o Terraform, acesse a Página de provedores no seu site.
Crie e edite o provider.tf
com o seguinte comando:
- nano provider.tf
Adicione o seguinte conteúdo ao arquivo provider.tf
:
variable "do_token" {}
provider "digitalocean" {
token = "${var.do_token}"
version = "1.9.1"
}
Neste arquivo, adicione seu token de acesso da DigitalOcean como uma variável, que o Terraform usará como identificação para a API da DigitalOcean. Especifique também a versão do plug-in do provedor DigitalOcean. O Terraform recomenda que você especifique qual versão do provedor está usando, de modo que as atualizações futuras não tenham a possibilidade de inutilizar sua configuração atual.
Agora, você criará o arquivo digitalocean_droplet.tf
. Aqui, você irá especificar o recurso que será usado; neste caso: droplet
.
Crie o arquivo com o seguinte comando:
- nano digitalocean_droplet.tf
Adicione a seguinte configuração:
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Aqui, você especifica quatro parâmetros:
name
: o nome do Droplet.
region
: a região onde o Droplet está localizado.
tags
: uma lista de rótulos que são aplicados a esse Droplet.
count
: o número de recursos necessários para essa configuração.
Em seguida, você criará um arquivo de configuração para seu firewall. Crie o arquivo digitalocean_firewall.tf
com o seguinte comando:
- nano digitalocean_firewall.tf
Adicione o conteúdo a seguir ao arquivo:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
}
Aqui, você especifica o nome do firewall que deseja importar e os rótulos dos Droplets aos quais as regras do firewall se aplicam. Por fim, o valor count
de 1
define o número necessário do recurso específico.
Nota: você também pode incluir recursos de firewall no arquivo digitalocean_droplet.tf
. No entanto, caso tenha vários ambientes onde vários Droplets compartilhem o mesmo firewall, é boa ideia separá-lo caso você quiser remover somente um único Droplet. Depois de fazer isso, o firewall não será afetado.
Agora, é hora de inicializar essas alterações, de modo que o Terraform possa baixar as dependências necessárias. Para tanto, você usará o comando terraform init
, o qual permitirá que você inicialize um diretório de trabalho que contém os arquivos de configuração do Terraform.
Execute este comando do seu diretório de projeto:
- terraform init
Você verá o seguinte resultado:
OutputTerraform has been successfully initialized!
O Terraform preparou o diretório de trabalho com sucesso, baixando plug-ins, procurando módulos e assim por diante. Em seguida, você começará a importar seus ativos para o Terraform.
Neste passo, você importará seus ativos da DigitalOcean para o Terraform. Você usará o doctl
para encontrar os números de ID dos seus Droplets, antes de importar seus ativos. Então, você irá verificar a configuração da importação com os comandos terraform show
e terraform plan
.
Para começar, você irá exportar seu token de acesso da DigitalOcean como uma variável de ambiente, a qual você irá, na sequência, injetar no Terraform durante o tempo de execução.
Exporte-o como uma variável de ambiente para sua sessão atual do shell com o seguinte comando:
- export DO_TOKEN="YOUR_TOKEN"
Para importar seu Droplet e firewall existentes, precisará de seus números de ID. Você pode usar o doctl
, a interface de linha de comando da API da DigitalOcean. Execute o comando a seguir para listar seus Droplets e acessar seus IDs:
- doctl compute droplet list
Você verá um resultado parecido com este:
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags Features Volumes
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 2048 1 50 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64
Agora, você importará seu Droplet e firewall existentes para o Terraform:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET_ID
Use o sinalizador -var
para especificar o valor do seu token de acesso à DigitalOcean - que você exportou anteriormente para sua sessão do shell. Isso é necessário para que a API da DigitalOcean possa verificar quem é você e aplicar alterações na sua infraestrutura.
Agora, execute o mesmo comando para o seu firewall:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL_ID
Você irá verificar se a importação foi bem-sucedida, usando o comando terraform show
. Esse comando possibilita que o resultado do estado de sua infraestrutura fique legível para humanos. Ele pode ser usado para inspecionar um plano, no intuito de garantir que as alterações desejadas serão executadas, ou inspecionar o estado atual - da maneira como o Terraform o vê.
Nesse contexto, state se refere ao mapeamento de seus ativos da DigitalOcean para a configuração do Terraform que você gravou e ao rastreamento dos metadados. Isso permite que você confirme se não há diferenças entre os ativos existentes da DigitalOcean que você deseja importar e os ativos que o Terraform está controlando:
- terraform show
Você verá um resultado parecido com este:
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
Você verá dois recursos no resultado, junto com seus atributos.
Após importar seu Droplet e firewall para o estado do Terraform, certifique-se de que as configurações representam o estado atual dos ativos importados. Para fazer isso, você irá especificar a image
(imagem) do Droplet e seu size
(tamanho). Esses dois valores podem ser encontrados no resultado do terraform show
em relação ao recurso digitalocean_droplet.do_droplet
.
Abra o arquivo digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
Neste tutorial:
ubuntu-16-04-x64
.fra1
.terraform-testing
.O Droplet que você importou usando a configuração no digitalocean_droplet.tf
ficará parecido com o seguinte:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
Em seguida, você adicionará as regras do firewall. No nosso exemplo, as portas abertas para o tráfego de entrada são: 22
, 80
e 443
. Todas as portas estão abertas para o tráfego de saída. Você pode ajustar essa configuração de acordo com suas portas abertas.
Abra o digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Adicione a seguinte configuração:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Essas regras replicam o estado do firewall exemplo existente. Se quiser limitar o tráfego a diferentes endereços IP, portas diferentes ou protocolos diferentes, você pode ajustar o arquivo para replicar seu firewall existente.
Após atualizar seus arquivos do Terraform, você usará o comando plan
para ver se as alterações que você fez replicam o estado dos ativos existentes na DigitalOcean.
O comando terraform plan
é usado como uma simulação. Com esse comando, você pode verificar se as alterações que o Terraform irá fazer são as alterações que deseja fazer. É uma boa ideia executar sempre esse comando para confirmação, antes de aplicar alterações.
Execute o terraform plan
com o seguinte:
- terraform plan -var "do_token=$DO_TOKEN"
Você verá um resultado parecido com o seguinte:
OutputNo changes. Infrastructure is up-to-date.
Você importou os ativos existentes da DigitalOcean com sucesso no Terraform. Agora, você pode fazer alterações na sua infraestrutura através do Terraform, sem o risco de excluir ou modificar acidentalmente ativos existentes.
Neste passo, você adicionará dois Droplets adicionais à sua infraestrutura existente. Adicionar ativos dessa maneira à sua infraestrutura existente pode ser útil, por exemplo, se você tiver um site ativo e não quiser fazer quaisquer alterações com possibilidade de interromper as alterações naquele site enquanto você trabalha nele. Em vez disso, você pode adicionar mais um Droplet para usar como um ambiente de desenvolvimento e trabalhar em seu projeto no mesmo ambiente de produção do Droplet, sem qualquer risco em potencial.
Agora, abra o digitalocean_droplet.tf
para adicionar as regras aos seus novos Droplets:
- nano digitalocean_droplet.tf
Adicione as seguintes linhas ao seu arquivo:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
Use o meta-argumento count
para informar ao Terraform quantos Droplets com as mesmas especificações você deseja. Esses novos Droplets também serão adicionados ao seu firewall existente, à medida que você especificará o mesmo rótulo, de acordo com o seu firewall.
Aplique essas regras para verificar as alterações que está especificando no digitalocean_droplet.tf
:
- terraform plan -var "do_token=$DO_TOKEN"
Verifique se as alterações que deseja fazer foram replicadas no resultado desse comando.
Você verá um resultado parecido com este:
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-18-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Assim que estiver satisfeito com o resultado, use o comando terraform apply
para aplicar as alterações que você especificou ao estado da configuração:
- terraform apply -var "do_token=$DO_TOKEN"
Confirme as alterações, digitando yes
na linha de comando. Após a execução bem-sucedida, você verá um resultado parecido com o seguinte:
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
Você verá dois novos Droplets no seu painel Web da DigitalOcean:
Você também os verá anexados ao seu firewall existente:
Você criou ativos com o Terraform usando seus ativos existentes. Para aprender como destruir esses ativos, você pode, de maneira opcional, completar o próximo passo.
Neste passo, você irá destruir os ativos que você importou e criou, ajustando a configuração.
Comece abrindo o digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
No arquivo, defina count
como 0, de acordo com o seguinte:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
Salve e saia do arquivo.
Abra seu arquivo de configuração do firewall para alterar o count
também:
- nano digitalocean_firewall.tf
Defina o count
como 0
, assim como na linha destacada a seguir:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "0"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Salve e saia do arquivo.
Agora, aplique essas alterações com o seguinte comando:
- terraform apply -var "do_token=${DO_TOKEN}"
O Terraform irá pedir a você para confirmar se deseja destruir os Droplets e o firewall. Isso irá destruir todos os ativos que você importou e criou através do Terraform. Assim, certifique-se de verificar se deseja prosseguir, antes de digitar yes
.
Você verá um resultado parecido com este:
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
Você excluiu todos os ativos gerenciados pelo Terraform. Esse é um fluxo de trabalho útil se você não for mais precisar de um ativo ou se estiver fazendo uma redução.
Neste tutorial, você instalou o Terraform, importou ativos existentes, criou ativos e, de maneira opcional, destruiu esses ativos. Você pode dimensionar esse fluxo de trabalho para um projeto maior, como a implantação de um cluster do Kubernetes pronto para produção. Usando o Terraform, você poderia gerenciar todos os nós, entradas DNS, firewalls, armazenamento e outros ativos, além de usar o controle de versão para rastrear alterações e colaborar com uma equipe.
Para explorar outras características do Terraform, leia sua documentação. Você também pode ler o conteúdo do Terraform da DigitalOcean para obter mais tutoriais e o arquivo de Perguntas e ReDigitalOcean
]]>I’d enabled firewall on my digitalocean account. I want to add a HTTPS port, But When I try to open firewall, I’m getting the below issue. “Looks like something went wrong… If this keeps happening, check out status.digitalocean.com.”
Kindly look into it
Thanks, Ehsan
]]>Terraform es una herramienta de infraestructura como código creada por HashiCorp que permite a los desarrolladores a implementar, actualizar y eliminar diferentes recursos de su infraestructura de manera eficiente y más escalable.
Los desarrolladores pueden usar Terraform para organizar diferentes entornos, realizar un seguimiento de los cambios a través del control de versiones y automatizar el trabajo repetitivo para reducir los errores humanos. La herramienta ofrece una alternativa para que los equipos colaboren en la mejora de su infraestructura a través de configuraciones compartidas.
A través de este turorial, importará infraestructura existente de DigitalOcean a Terraform. Al finalizar, podrá utilizar Terraform para toda su infraestructura existente además de crear nuevos recursos.
doctl
de GitHub. Puede leer el siguiente tutorial Cómo usar Doctl, el cliente de línea de comandos oficial de DigitalOcean.En este primer paso, instalará Terraform en su máquina local. En este paso, se detalla la instalación del binario de Linux. Si utiliza Windows o Mac, puede revisar la página de Descarga de Terraform en el sitio web de Terraform.
Diríjase a la carpeta en la que desee descargar Terraform en su máquina local y luego utilice la herramienta wget
para descargar el binario 0.12.12
de Terraform:
- cd /tmp
- wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Para verificar si la suma de comprobación sha256
es el mismo valor que se proporciona en el sitio web de Terraform, descargará el archivo de suma de comprobación con el siguiente comando:
- wget -q https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_SHA256SUMS
Luego ejecute el siguiente comando para verificar las sumas de comprobación:
- sha256sum -c --ignore-missing terraform_0.12.12_SHA256SUMS
En el archivo SHA256SUMS
que descargó se enumeran los nombres de archivos y sus hash. Con este comando se buscará el mismo archivo terraform_0.12.12_SHA256SUMS
de forma local y luego se verificará que los hash coincidan usando el indicador -c
. Debido a que en este archivo se incluye más de un nombre de archivo y su plataforma indicada, utilice el indicador --ignore-missing
para evitar errores en el resultado, ya que no tiene copias de los demás archivos.
Verá un resultado como el siguiente:
Outputterraform_0.12.12_linux_amd64.zip: OK
Utilice unzip
para extraer el binario:
- sudo unzip terraform_0.12.12_linux_amd64.zip -d /usr/local/bin/
Ahora verifique si Terraform está correctamente instalado revisando la versión:
- terraform version
Visualizará un resultado similar al siguiente:
OutputTerraform v0.12.12
Instaló Terraform en su máquina local. Ahora, preparará los archivos de configuración.
En este paso, importará sus activos existentes a Terraform creando un directorio de proyecto y escribiendo archivos de configuración. Debido a que Terraform por el momento no admite la generación de configuraciones a partir del comando import
, debe crearlas de forma manual.
Ejecute el siguiente comando para crear el directorio de su proyecto:
- mkdir -p do_terraform_import
Posiciónese en ese directorio con lo siguiente:
- cd do_terraform_import
Durante este paso, creará tres archivos adicionales que contendrán las configuraciones necesarias. Su estructura de directorios para este proyecto tendrá el siguiente aspecto:
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
└── provider.tf
Para comenzar, creará el archivo provider.tf
a fin de definir su Token de acceso de DigitalOcean como una variable de entorno en lugar de codificarlo de forma rígida en su configuración.
Advertencia: Con su token de acceso se le proporciona acceso a toda su infraestructura sin restricciones; considérelo como tal. Asegúrese de ser la única persona que tenga acceso a la máquina en la que se almacene ese token.
Además de su token de acceso, también especificará el proveedor que desee usar. En este tutorial, es digitalocean
. Si desea acceder a una lista completa de las fuentes y los recursos de datos disponibles para DigitalOcean con Terraform, consulte la página de proveedores en el sitio web.
Cree y edite provider.tf
con el siguiente comando:
- nano provider.tf
Añada el siguiente contenido al archivo provider.tf
:
variable "do_token" {}
provider "digitalocean" {
token = "${var.do_token}"
version = "1.9.1"
}
En este archivo, se agrega el Token de acceso de DigitalOcean como una variable que Terraform usará como identificación para la API de DigitalOcean. También se especifica la versión del complemento del proveedor de DigitalOcean. Desde Terraform, se recomienda especificar la versión del proveedor que usará para que las actualizaciones futuras no puedan dañar su configuración actual.
Ahora creará el archivo digitalocean_droplet.tf
. Aquí, especificará el recurso que usará; en este caso, droplet
.
Cree el archivo con el siguiente comando:
- nano digitalocean_droplet.tf
Añada la siguiente configuración:
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Aquí, especifique cuatro parámetros:
name
: nombre del Droplet.
region
: región en la que se ubica el Droplet.
tags
: lista de las etiquetas que se aplican a este Droplet.
count
: número de recursos necesarios para esta configuración.
A continuación, creará un archivo de configuración para su firewall. Cree el archivo digitalocean_firewall.tf
con el siguiente comando:
- nano digitalocean_firewall.tf
Añada el siguiente contenido al archivo:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
}
Aquí especifica el nombre del firewall que desea importar y las etiquetas de los Droplets a las que se aplican las reglas del firewall. Por último, en el valor count
de 1
se define el número requerido del recurso específico.
Nota: También puede incluir recursos del firewall en el archivo digitalocean_droplet.tf
. Sin embargo, si dispone de varios entornos en los cuales varios Droplets comparten el mismo firewall, se recomienda separarlo en caso de querer eliminar un solo Droplet. Esto dejará el firewall intacto.
Ahora, es momento de inicializar esos cambios para que en Terraform se puedan descargar las dependencias necesarias. Para esto utilizará el comando terraform init
, el cual le permitirá inicializar un directorio de trabajo que contenga archivos de configuración de Terraform.
Ejecute el siguiente comando desde el directorio de su proyecto:
- terraform init
Verá el siguiente resultado:
OutputTerraform has been successfully initialized!
Terraform preparó de forma correcta el directorio de trabajo descargando complementos y buscando módulos, entre otras acciones. A continuación, comenzará a importar sus recursos a Terraform.
Durante este paso, importará sus activos de DigitalOcean a Terraform. Usará doctl
para encontrar los números de ID de sus Droplets antes de importar sus recursos. Luego, verificará la configuración de importación con los comandos terraform show
y terraform plan
.
Para comenzar, exportará su Token de acceso de DigitalOcean como una variable de entorno que luego insertará en Terraform durante el tiempo de ejecución.
Expórtelo como una variable de entorno a su sesión de shell actual con el siguiente comando:
- export DO_TOKEN="YOUR_TOKEN"
Para poder importar su Droplet y firewall existentes, necesitará los números de ID de estos. Puede usar doctl
, la interfaz de línea de comandos de la API de DigitalOcean. Ejecute el siguiente comando para listar sus Droplets y acceder a sus IDs:
- doctl compute droplet list
Visualizará un resultado similar al siguiente:
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags Features Volumes
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 2048 1 50 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64
Ahora, importará su Droplet y firewall existentes a Terraform:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET_ID
Se utiliza el indicador -var
para especificar el valor de su Token de acceso de DigitalOcean, previamente exportado a su sesión de shell. Esto es necesario para que en la API de DigitalOcean se verifique su identidad y se apliquen cambios en su infraestructura.
Ahora, ejecute el mismo comando para su firewall:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL_ID
Compruebe que la importación se haya realizado correctamente usando el comando terraform show
. Este comando proporciona un resultado legible para humanos del estado de su infraestructura. Puede utilizarse para inspeccionar un plan a fin de garantizar que los cambios requeridos se ejecuten o inspeccionar el estado actual tal como se ve en Terraform.
En este contexto, el estado hace referencia a la asignación de sus recursos de DigitalOcean en la configuración de Terraform que escribió y al seguimiento de los metadatos. Esto le permite confirmar que no existe diferencia entre los recursos existentes de DigitalOcean que desea importar y los recursos que Terraform somete a seguimiento:
- terraform show
Verá un resultado similar a este:
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
Verá dos recursos en el resultado junto con sus atributos.
Después de importar su Droplet y firewall al estado de Terraform, debe asegurarse que las configuraciones representen el estado actual de los recursos importados. Para hacer esto, especificará la image
de su Droplet y su size
. Puede encontrar estos dos valores en el resultado de terraform show
relacionado con el recurso digitalocean_droplet.do_droplet
.
Abra el archivo digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
En este tutorial:
ubuntu-16-04-x64
.fra1
.terraform-testing
.El Droplet que importó usando la configuración en digitalocean_droplet.tf
tendrá el siguiente aspecto:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
A continuación, añadirá las reglas del firewall. En nuestro ejemplo, los puertos abiertos para el tráfico entrante son 22
, 80
y 443
. Todos los puertos están abiertos para el tráfico saliente. Puede ajustar esta configuración de manera correspondiente para sus puertos abiertos.
Abra digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Añada la siguiente configuración:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
En estas reglas se replica el estado del firewall de ejemplo existente. Si desea limitar el tráfico a diferentes direcciones IP, puertos o protocolos, puede ajustar el archivo para replicar su firewall existente.
Una vez que haya actualizado sus archivos de Terraform, usará el comando plan
para ver si en los cambios realizados se replica el estado de los activos existentes en DigitalOcean.
El comando terraform plan
se utiliza a modo de simulacro. Con este comando, puede verificar si los cambios que se realizarán en Terraform son los cambios que quiere hacer. Es recomendable ejecutar siempre este comando para confirmarlo antes de aplicar los cambios.
Ejecute terraform plan
con lo siguiente:
- terraform plan -var "do_token=$DO_TOKEN"
Verá un resultado similar al siguiente:
OutputNo changes. Infrastructure is up-to-date.
Importó de forma correcta los recursos de DigitalOcean existentes a Terraform y ahora podrá realizar cambios en su infraestructura mediante Terraform sin el riesgo de eliminar o modificar los recursos existentes.
En este paso, agregará dos Droplets adicionales a su infraestructura existente. Añadir recursos de esta manera a su infraestructura existente puede ser útil, por ejemplo, si tiene un sitio web activo y no quiere realizar cambios que puedan ocasionar perjuicios en dicho sitio mientras realiza tareas en él. En su lugar, puede añadir un Droplet adicional para usarlo como entorno de desarrollo y trabajar en su proyecto en el mismo entorno que el Droplet de producción sin riesgos.
Ahora, abra digitalocean_droplet.tf
para añadir las reglas de sus nuevos Droplets:
- nano digitalocean_droplet.tf
Añada las siguientes líneas a su archivo:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
Utilizará el metargumento count
para indicar a Terraform la cantidad de Droplets con las mismas especificaciones que desea. Estos nuevos Droplets también se agregarán a su firewall existente a medida que especifique la misma etiqueta que en su firewall.
Aplique estas reglas para verificar los cambios que especifique en DigitalOcean_droplet.tf
:
- terraform plan -var "do_token=$DO_TOKEN"
Verifique que los cambios que desea realizar se repliquen en el resultado de este comando.
Visualizará un resultado similar al siguiente:
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-18-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Una vez que esté satisfecho con el resultado, utilice el comando terraform apply
para aplicar los cambios que especificó al estado de la configuración:
- terraform apply -var "do_token=$DO_TOKEN"
Confirme los cambios ingresando yes
en la línea de comandos. Cuando la ejecución sea exitosa, verá un resultado similar al siguiente:
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
Visualizará dos nuevos Droplets en su panel web de DigitalOcean:
También los verá adjuntos a su firewall existente:
Creó nuevos recursos con Terraform usando sus activos existentes. Para aprender a destruir estos recursos, opcionalmente puede completar el paso siguiente.
En este paso, destruirá los activos que importó y creó ajustando la configuración.
Comience abriendo digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
En el archivo, fije count
en 0 como se muestra a continuación:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
Guarde el archivo y ciérrelo.
Abra su archivo de configuración de firewall para modificar count
también:
- nano digitalocean_firewall.tf
Fije count
en 0
como en la siguiente línea resaltada:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "0"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Guarde el archivo y ciérrelo.
Ahora, aplique esos cambios con el siguiente comando:
- terraform apply -var "do_token=${DO_TOKEN}"
Terraform le solicitará confirmar si desea destruir los Droplets y el firewall. Con esto se eliminarán todos los activos que importó y creó mediante Terraform. Por lo tanto, asegúrese de verificar que desee proceder antes de escribir yes
.
Verá un resultado similar a lo siguiente:
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
Eliminó todos los activos administrados por Terraform. Este es un flujo de trabajo útil si ya no necesita un recurso o realiza una reducción.
A lo largo de este tutorial, instaló Terraform, importó los recursos existentes, creó recursos nuevos y, opcionalmente, los destruyó. Puede escalar este flujo de trabajo para un proyecto más grande, como la implementación de un clúster de Kubernetes listo para la producción. A través de Terraform, puede administrar los nodos, las entradas de DNS, los firewalls, el almacenamiento y otros recurss, además de usar el control de versiones para supervisar cambios y colaborar con un equipo.
Para explorar más características de Terraform, lea la documentación pertinente. También puede leer contenido de Terraform de DigitalOcean para acceder a más tutoriales y preguntas y respuestas.
]]>Terraform — созданный HashiCorp инструмент на базе модели «инфраструктура как код». Он помогает разработчикам эффективно развертывать, обновлять и удалять различные ресурсы инфраструктуры и обеспечивает поддержку масштабирования.
Разработчики могут использовать Terraform для организации различных сред, отслеживания изменений посредством контроля версий и автоматизации повторяющихся задач для предотвращения человеческих ошибок. Также Terraform позволяет командам совместно работать над совершенствованием инфраструктуры посредством общих конфигураций.
В этом обучающем руководстве мы импортируем существующую инфраструктуру DigitalOcean в Terraform. К завершению этого обучающего руководства вы сможете использовать Terraform для всей своей инфраструктуры, а также создавать новые ресурсы.
doctl
на GitHub. Также вы можете прочитать руководство Использование Doctl, официального клиента командной строки DigitalOcean.На первом шаге следует установить Terraform на локальный компьютер. На этом шаге описывается установка двоичного файла Linux. Если вы используете операционную систему Windows или Mac, вы можете воспользоваться страницей загрузки Terraform на сайте Terraform.
Перейдите в папку на локальном компьютере, куда вы хотите загрузить Terraform, а затем используйте утилиту wget
для загрузки двоичного файла Terraform 0.12.12
:
- cd /tmp
- wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Чтобы проверить соответствие контрольной суммы sha256
указанному на сайте Terraform значению, загрузите файл контрольной суммы с помощью следующей команды:
- wget -q https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_SHA256SUMS
Затем запустите следующую команду для проверки контрольных сумм:
- sha256sum -c --ignore-missing terraform_0.12.12_SHA256SUMS
В загруженном вами файле SHA256SUMS
содержится список имен файлов и значений хэш-сумм для этих файлов. Эта команда ищет локальный файл terraform_0.12.12_SHA256SUMS
и проверяет соответствие хэш-сумм, используя флаг -c
. Поскольку у этого файла имеется несколько имен файла, и указана его платформа, используйте флаг --ignore-missing
для предотвращения ошибок, поскольку у вас нет копий других файлов.
Вы увидите следующий результат:
Outputterraform_0.12.12_linux_amd64.zip: OK
Используйте unzip
для распаковки двоичного файла:
- sudo unzip terraform_0.12.12_linux_amd64.zip -d /usr/local/bin/
Убедитесь в правильности установки Terraform посредством проверки версии:
- terraform version
Результат будет выглядеть примерно так:
OutputTerraform v0.12.12
Мы установили Terraform на локальном компьютере и можем перейти к подготовке файлов конфигурации.
На этом шаге мы импортируем в Terraform имеющиеся ресурсы посредством создания директории проекта и записи файлов конфигурации. Поскольку Terraform не поддерживает генерирование конфигураций из команды import
, эти конфигурации следует создать вручную.
Запустите следующую команду для создания директории вашего проекта:
- mkdir -p do_terraform_import
Затем перейдите в эту директорию:
- cd do_terraform_import
На этом шаге мы создадим три дополнительных файла, в которых будут содержаться требуемые конфигурации. Структура директорий этого проекта будет выглядеть следующим образом:
├── digitalocean_droplet.tf
├── digitalocean_firewall.tf
└── provider.tf
Для начала мы создадим файл provider.tf
для определения токена доступа DigitalOcean как переменной среды вместо его программирования в конфигурации.
Предупреждение. Токен доступа предоставляет неограниченный доступ ко всей вашей инфраструктуре, поэтому с ним следует обращаться осторожно. Убедитесь, что доступ к компьютеру, где хранится токен, имеется только у вас.
Помимо токена доступа также следует указать, какого провайдера вы хотите использовать. Для целей данного обучающего руководства мы используем digitalocean
. Полный список доступных источников данных и ресурсов для DigitalOcean с Terraform можно найти на странице провайдеров на соответствующем сайте.
Создайте файл provider.tf
и откройте его для редактирования:
- nano provider.tf
Добавьте в файл provider.tf
следующие строки:
variable "do_token" {}
provider "digitalocean" {
token = "${var.do_token}"
version = "1.9.1"
}
В этом файле вы добавляете свой токен доступа DigitalOcean как переменную, которую Terraform будет использовать для идентификации в DigitalOcean API. Также вы указываете версию плагина провайдера DigitalOcean. Terraform рекомендует указать используемую версию провайдера, чтобы будущие обновления не нарушили имеющуюся систему.
Далее мы создадим файл digitalocean_droplet.tf
. Здесь мы указываем, какие ресурсы будем использовать. В данном случае это droplet
.
Создайте файл с помощью следующей команды:
- nano digitalocean_droplet.tf
Добавьте следующую конфигурацию:
resource "digitalocean_droplet" "do_droplet" {
name = "testing-terraform"
region = "fra1"
tags = ["terraform-testing"]
count = "1"
}
Здесь задается четыре параметра:
name
: имя дроплета.
region
: регион местонахождения дроплета.
tags
: перечень всех тегов, применяемых к этому дроплету.
count
: количество ресурсов, требуемых для этой конфигурации.
Далее мы создадим файл конфигурации брандмауэра. Создайте файл digitalocean_firewall.tf
с помощью следующей команды:
- nano digitalocean_firewall.tf
Добавьте в файл следующие строки:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
}
Здесь указывается имя брандмауэра, который вы хотите импортировать, а также теги дроплетов, к которым применяются правила брандмауэра. Наконец, значение count
1
определяет требуемое количество соответствующего ресурса.
Примечание. Вы можете включить ресурсы брандмауэра в файл digitalocean_droplet.tf
, однако если вы используете несколько сред, где несколько дроплетов используют один брандмауэр, лучше разделить их на случай, если вы захотите удалить один из дроплетов. Это не повлияет на вывод брандмауэра.
Теперь следует инициализировать эти изменения, чтобы у Terraform была возможность загрузить требуемые зависимости. Для этого используется команда terraform init
, позволяющая инициализировать рабочую директорию с файлами конфигурации Terraform.
Запустите в директории проекта следующую команду:
- terraform init
Вывод должен выглядеть так:
OutputTerraform has been successfully initialized!
Terraform успешно подготовил рабочую директорию, выполнив загрузку плагинов, поиск модулей и т. д. Теперь мы можем начать импорт ресурсов в Terraform.
На этом шаге вы импортируете ресурсы DigitalOcean в Terraform. Используйте doctl
для определения идентификационных номеров дроплетов, прежде чем начать импорт ресурсов. Также вы можете проверить конфигурацию импорта с помощью команд terraform show
и terraform plan
.
Для начала экспортируйте токен доступа DigitalOcean как переменную среды, которая будет использоваться Terraform во время выполнения.
Экспортируйте ее как переменную среды текущего сеанса оболочки с помощью следующей команды:
- export DO_TOKEN="YOUR_TOKEN"
Чтобы импортировать существующие дроплет и брандмауэр, вам потребуются их идентификационные номера. Вы можете использовать doctl
, интерфейс командной строки DigitalOcean API. Запустите следующую команду для вывода списка дроплетов и получения доступа к их идентификаторам:
- doctl compute droplet list
Результат будет выглядеть примерно так:
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags Features Volumes
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 2048 1 50 fra1 Ubuntu 18.04.3 (LTS) x64 active
DROPLET-ID DROPLET-NAME DROPLET-IPv4 1024 1 25 fra1 Ubuntu 18.04.3 (LTS) x64
Теперь вы импортируете существующий дроплет и брандмауэр в Terraform:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_droplet.do_droplet DROPLET_ID
Мы используем флаг -var
, чтобы задать токен доступа DigitalOcean, который вы ранее экспортировали в сеанс оболочки. Это требуется, чтобы DigitalOcean API мог проверить вашу личность и применить изменения к инфраструктуре.
Теперь запустите эту же команду для вашего брандмауэра:
- terraform import -var "do_token=${DO_TOKEN}" digitalocean_firewall.do_firewall FIREWALL_ID
Команда terraform show
позволяет проверить, был ли импорт выполнен успешно. Эта команда позволяет получить удобочитаемые данные по состоянию инфраструктуры. Ее можно использовать для проверки плана, чтобы обеспечить выполнение желаемых изменений, или для проверки текущего состояния с точки зрения Terraform.
В этом контексте state означает сопоставление ресурсов DigitalOcean с записанной конфигурацией Terraform и отслеживание метаданных. Это позволяет подтвердить отсутствие различий между существующими ресурсами DigitalOcean, которые вы хотите импортировать, и ресурсами, которые отслеживает Terraform:
- terraform show
Вывод будет выглядеть следующим образом:
Output. . .
# digitalocean_droplet.do_droplet:
resource "digitalocean_droplet" "do_droplet" {
backups = false
created_at = "2020-02-03T16:12:02Z"
disk = 25
id = "DROPLET-ID"
image = "DROPLET-IMAGE"
ipv4_address = "DROPLET-IP"
ipv6 = false
locked = false
memory = 1024
monitoring = false
name = "testing-terraform-0"
price_hourly = 0.00744
price_monthly = 5
private_networking = false
region = "fra1"
resize_disk = true
size = "s-1vcpu-1gb"
status = "active"
tags = [
"terraform-testing",
]
urn = "DROPLET-URN"
vcpus = 1
volume_ids = []
. . .
}
В результатах вы увидите два ресурса совместно с атрибутами.
После импорта дроплета и брандмауэра в состояние Terraform необходимо убедиться, что конфигурации представляют текущее состояние импортируемых ресурсов. Для этого следует указать образ
Droplet и его размер
. Эти два значения можно увидеть в результатах выполнения команды terraform show
для ресурса digitalocean_droplet.do_droplet
.
Откройте файл digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
В этом обучающем руководстве:
ubuntu-16-04-x64
.fra1
.terraform-testing
.Дроплет, импортированный с помощью конфигурации в digitalocean_droplet.tf
, будет выглядеть следующим образом:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
}
Далее вы добавите правила брандмауэра. В нашем примере для входящего трафика открыты порты 22
, 80
и 443
. Все порты открыты для исходящего трафика. Вы можете изменить конфигурацию в зависимости от состава и количества открытых портов.
Откройте файл digitalocean_firewall.tf
:
- nano digitalocean_firewall.tf
Добавьте следующую конфигурацию:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "1"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Эти правила воспроизводят состояние существующего образца брандмауэра. Если вы хотите ограничить трафик для других IP-адресов, портов или протоколов, вы можете изменить файл для соответствия настройкам вашего брандмауэра.
После обновления файлов Terraform используйте команду plan
, чтобы увидеть, соответствуют ли внесенные изменения состоянию существующих ресурсов в DigitalOcean.
Команда terraform plan
используется для пробного прогона. С ее помощью вы можете проверить, соответствуют ли вносимые Terraform изменения желаемым. Эту команду всегда полезно запускать для подтверждения перед применением изменений.
Запустите команду terraform plan
со следующим синтаксисом:
- terraform plan -var "do_token=$DO_TOKEN"
Вы увидите следующие результаты:
OutputNo changes. Infrastructure is up-to-date.
Вы успешно импортировали существующие ресурсы DigitalOcean в Terraform и теперь можете вносить через Terraform изменения в инфраструктуру без риска случайного удаления или изменения существующих ресурсов.
На этом шаге мы добавляем два дополнительных дроплета в существующую инфраструктуру. Например, такое добавление ресурсов в существующую инфраструктуру может быть полезным, если у вас запущен сайт и вы не хотите нарушить его работу во время внесения изменений. Вместо этого вы можете добавить еще один дроплет в качестве среды разработки и поработать над проектом в той же среде, где находится производственный дроплет, без каких-либо потенциальных рисков.
Откройте файл digitalocean_droplet.tf
для добавления правил для новых дроплетов:
- nano digitalocean_droplet.tf
Добавьте в файл следующие строки:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "1"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "2"
}
Вы используете мета-аргумент count
, чтобы указать Terraform, сколько дроплетов с такими же спецификациями вам потребуется. Эти новые дроплеты также будут добавлены в брандмауэр, поскольку вы указываете тот же тег, что и для брандмауэра.
Примените эти правила для проверки изменений, задаваемых в digitalocean_droplet.tf
:
- terraform plan -var "do_token=$DO_TOKEN"
Убедитесь, что желаемые изменения отражаются в результатах выполнения команды.
Результат будет выглядеть примерно так:
. . .
[secondary_label Output]
# digitalocean_droplet.do_droplet_new[1] will be created
+ resource "digitalocean_droplet" "do_droplet_new" {
+ backups = false
+ created_at = (known after apply)
+ disk = (known after apply)
+ id = (known after apply)
+ image = "ubuntu-18-04-x64"
+ ipv4_address = (known after apply)
+ ipv4_address_private = (known after apply)
+ ipv6 = false
+ ipv6_address = (known after apply)
+ ipv6_address_private = (known after apply)
+ locked = (known after apply)
+ memory = (known after apply)
+ monitoring = false
+ name = "testing-terraform-1"
+ price_hourly = (known after apply)
+ price_monthly = (known after apply)
+ private_networking = true
+ region = "fra1"
+ resize_disk = true
+ size = "s-1vcpu-1gb"
+ status = (known after apply)
+ tags = [
+ "terraform-testing",
]
+ urn = (known after apply)
+ vcpus = (known after apply)
+ volume_ids = (known after apply)
}
Plan: 2 to add, 1 to change, 0 to destroy.
Когда вы будете довольны результатами, используйте команду terraform apply
для применения указанных изменений к состоянию конфигурации:
- terraform apply -var "do_token=$DO_TOKEN"
Подтвердите внесение изменений, введя yes
в командной строке. После успешного выполнения вы увидите примерно следующее:
Output. . .
digitalocean_droplet.do_droplet_new[1]: Creating...
digitalocean_droplet.do_droplet_new[0]: Creating...
digitalocean_firewall.do_firewall[0]: Modifying... [id=FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Modifications complete after 1s [id=FIREWALL-ID]
digitalocean_droplet.do_droplet_new[0]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still creating... [10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Creation complete after 16s [id=DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Still creating... [20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Creation complete after 22s [id=DROPLET-ID]
Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
Вы увидите два новых дроплета на веб-панели DigitalOcean:
Также вы увидите, что они прикреплены к существующему брандмауэру:
Вы создали с помощью Terraform новые ресурсы, использовав для этого имеющиеся ресурсы. На следующем шаге вы можете узнать, как уничтожить эти ресурсы.
На этом шаге мы уничтожим импортированные и созданные ресурсы посредством изменения конфигурации.
Откройте digitalocean_droplet.tf
:
- nano digitalocean_droplet.tf
Задайте в файле для параметра count
значение 0, как показано здесь:
resource "digitalocean_droplet" "do_droplet" {
image = "ubuntu-16-04-x64"
name = "testing-terraform"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
resource "digitalocean_droplet" "do_droplet_new" {
image = "ubuntu-18-04-x64"
name = "testing-terraform-${count.index}"
region = "fra1"
size = "s-1vcpu-1gb"
tags = ["terraform-testing"]
count = "0"
}
Сохраните и закройте файл.
Откройте файл конфигурации брандмауэра и измените в нем параметр count
:
- nano digitalocean_firewall.tf
Задайте для параметра count
значение 0
, как в следующей строке:
resource "digitalocean_firewall" "do_firewall" {
name = "testing-terraform-firewall"
tags = ["terraform-testing"]
count = "0"
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "tcp"
port_range = "443"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "all"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
Сохраните и закройте файл.
Примените изменения с помощью следующей команды:
- terraform apply -var "do_token=${DO_TOKEN}"
Terraform предложит подтвердить уничтожение дроплетов и брандмауэра. Эта команда уничтожит все ресурсы, импортированные и созданные с помощью Terraform, так что вводите yes
, только если уверены, что хотите продолжить.
Результат будет выглядеть примерно так:
Output. . .
digitalocean_droplet.do_droplet[0]: Destroying... [id=YOUR-DROPLET-ID]]
digitalocean_droplet.do_droplet_new[0]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_droplet.do_droplet_new[1]: Destroying... [id=YOUR-DROPLET-ID]
digitalocean_firewall.do_firewall[0]: Destroying... [id=YOUR-FIREWALL-ID]
digitalocean_firewall.do_firewall[0]: Destruction complete after 1s
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 10s elapsed]
digitalocean_droplet.do_droplet_new[1]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet[0]: Still destroying... [id=YOUR-DROPLET-ID, 20s elapsed]
digitalocean_droplet.do_droplet_new[1]: Destruction complete after 22s
digitalocean_droplet.do_droplet[0]: Destruction complete after 22s
digitalocean_droplet.do_droplet_new[0]: Destruction complete after 22s
Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
Вы удалили все ресурсы, управляемые Terraform. Это полезный рабочий процесс для удаления ненужных ресурсов или в случае уменьшения масштаба.
В этом обучающем руководстве мы выполнили установку Terraform, импортировали существующие ресурсы, создали новые ресурсы и (при желании) уничтожили эти ресурсы. Вы можете использовать этот рабочий процесс и в более масштабном проекте, например для развертывания кластера Kubernetes в производственной среде. С помощью Terraform вы сможете управлять всеми узлами, записями DNS, брандмауэрами, ресурсами хранения и другими ресурсами, а также использовать систему контроля версий для отслеживания изменений и совместной работы в команде.
Дополнительные сведения о возможностях Terraform можно найти в документации. Также вы можете ознакомиться с другими обучающими руководствами и ответами на вопросы в материалах DigitalOcean по Terraform.
]]>I want to use postfix as send only smtp without any third party relay such as gmail :- https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-16-04
But many cloud providers block port 25. Is there any way to make work postfix on port 587?
Tried editing postfix configs but not worked.
Thanks
]]>I have two questions:
Thank you.
]]>last night I added digitalocean could firewalls vie control panel. later this morning I found website and all access going beside cpanel. now I m totally stuck.
help me. my IP - 104.131.133.74
]]>Status: Connecting to my_ip...
Response: fzSftp started, protocol_version=9
Command: open "root@my_ip" 22
Error: FATAL ERROR: Network error: Connection timed out
Error: Could not connect to server
In digitalocean access console i run
sftp root@myip
and get message
connected to my_ip
then run following commands
netstat -plunt | grep 22
output : [https://i.imgur.com/0oubnsS.png]
ss -nlput | grep sshd
output : [https://i.imgur.com/zkKAKzk.png]
ssh -p 22 root@my_ip
output: [https://i.imgur.com/vJ1lLTP.png]
tail -f /var/log/auth.log
output : [https://i.imgur.com/YfpGCn1.png]
ufw status
output: status:inactive
iptables --list
output: [https://i.imgur.com/SCc3VO6.png]
nano /etc/ssh/sshd_config
and find following rules
ForwardX11 yes
passwordAuthentication yes
#PubkeyAuthentication yes
#port 22
I also tried to login using putty but got network error “connection time out”
so how to solve this problem so that i can login using filezilla sftp protocol?
]]>I’m using terraform to provision an environment. But I’m running into an issue.
I’d like to terminate SSL on the LB, and then restrict port 80 on my 2 backend servers to only allow the LB to connect on the private network.
The problem I’m seeing with terraform is, there’s no way to define a private IP for the LB (no output, seems it only outputs the public IP).
Is there a way to at least restrict it to the private network CIDR without knowing it ahead of time?
]]>I’ve been following https://crosstalksolutions.com/definitive-guide-to-hosted-unifi/ in order to setup the unifi controller on DO. It works perfectly, but my ISP supplies me with a dynamic IP address. We have a lot of work going on at the moment which means throughout the day, the power goes off for a while and we power up, I get a new IP. Is there anyway to handle this with firewall rules to I don’t have to keep manually logging in and allowing my new ip through? At the moment I’m having to load the console from the DO account page and login as root to unblock myself.
]]>I have set TCP port 4000 as a rule in my firewall and I have been expecting to be able to communicate with my application listening on that port. Netstat reports 4000 to be a listening port.
In the past with my application running on a dedicated remote server, I have been able to connect using telnet from a remote system (in which case my log files respond reporting junk data). Currently, telnet reports “?need to be connected first”
Also, from the droplet command line I issue: echo “some text” > /dev/tcp/127.0.0.1/4000 which invokes “connection refused”
If I use udp instead, there is no error, but still no indication that the data reached my application.
many thanks,
]]>admin-ajax.php
working fine. if non-authenticated user access admin-ajax.php
return 403.
I tried the following operation:
The issue still not fixed. Does any other possibility fix these issues? where I found the uwf firewall access log?
]]>Server A - network 1
public ip = 168.11.111.111
private ip = 10.11.111.111
Server B - network 1
public ip = 168.22.222.222
private ip = 10.22.222.222
Server C - network 2
public ip = 168.33.333.333
My application uses the public ip for binding sockets to, but I feel like it’s possible to use iptables to configure traffic to traverse through the private network for certain static IPS that are known to be in the same private network.
I did a ton of research about iptables, and I finally thought I came up with the correct scripts but I still can’t seem to get traffic to travel correctly.
So for my server a configuration I have
PRIVATE_A_IP=10.11.111.111
PUBLIC_A_IP=168.11.111.111
PRIVATE_B_IP=10.22.222.222
PUBLIC_B_IP=168.22.222.222
// redirect incoming packets for private ip to become input for public ip on the eth0 interface
iptables -t nat -A PREROUTING -d ${PRIVATE_A_IP} -i eth0 -j DNAT --to-destination ${PUBLIC_A_IP}
// redirect traffic meant for public b to be sent to private b on eth1 interface
iptables -t nat -A OUTPUT -d ${PUBLIC_B_IP} -o eth1 -j DNAT --to-destination ${PRIVATE_B_IP}
// change source of outgoing traffic to private b to say source is from private a, still eth1 interface
iptables -t nat -A POSTROUTING -d ${PRIVATE_B_IP} -o eth1 -j SNAT --to-source ${PRIVATE_A_IP}
then since it’s bidirectional i’d do the inverse for server b
iptables -t nat -A PREROUTING -d ${PRIVATE_B_IP} -i eth0 -j DNAT --to-destination ${PUBLIC_B_IP}
iptables -t nat -A OUTPUT -d ${PUBLIC_A_IP} -o eth1 -j DNAT --to-destination ${PRIVATE_A_IP}
iptables -t nat -A POSTROUTING -d ${PRIVATE_A_IP} -o eth1 -j SNAT --to-source ${PRIVATE_B_IP}
I’m pretty certain I’m doing this correct after researching NAT/iptables all weekend, is there something I’m missing?
]]>Within those servers I have node apps using sockets to communicate with eachother, as of now a listens from b and c on the same socket, and b listens to a and c from the same socket.
The problem is, I want to utilize the private networking between a and b, but I understand I can’t from c.
I was wondering if there’s any iptables magic that can handle this situation- or do I need to refactor my servers to utilize a private and public socket for different server communications?
example -
Server A public ip 168.11.111.111, private ip is 10.11.111.111 Server B public ip is 168.22.222.222, private ip is 10.22.222.222 Server C public ip is 168.33.333.333
I was thinking I could do something maybe like this for communication from A to B
sudo iptables -t nat -A POSTROUTING -s 168.11.111.111 -j SNAT --to-source 10.11.111.111 //IF DESTINATION IS 10.22.222.222 ? is this possible to add to the rule?
then on server b it would be something like
iptables -t nat -A PREROUTING -d 10.22.222.222 -j REDIRECT --to-destination 168.22.222.222
Basically I want to make it so the output will redirect it’s source from the public to private and then the receiving end will redirect the private destination to the public destination - this way all my apps can use the same socket listening on a public address but also utilize the private network of digital ocean.
]]>Type: Custom Protocol: TCP Portrange: 6002 for IPv4 and 6
But still if I go to https://ping.eu/port-chk/ my port is still closed!
Any ideas?
I don’t use the local firewall only the DO Cloud Firewall
]]>But after a while my rules keep resetting and my added HTTPS rule disappears.
Why does this happen?
Thanks
]]>I’ve tried using port 465 however I had an error so as I use tls I have changed the port to 587, I think 587 is for tls?
I’m getting the following error:
Failed to send AUTH LOGIN command. Error: 530 5.7.0 Must issue a STARTTLS command first. a7sm12831008wra.43 - gsmtp
I’m trying to send email from Expressionengine, I have the following email settings:
$config['email_newline'] = "\r\n";
$config['email_crlf'] = "\r\n";
$config['smtp_crypto'] = 'tls';
Inbound Rules
Custom TCP 25 All IPv4 All IPv6 More
HTTP TCP 80 All IPv4 All IPv6 More
HTTPS TCP 443 All IPv4 All IPv6 More
Custom TCP 587 All IPv4 All IPv6 More
Outbound Rules
ICMP ICMP All IPv4 All IPv6 More
All TCP TCP All ports All IPv4 All IPv6 More
Custom TCP 587 All IPv4 All IPv6 More
All UDP UDP All ports All IPv4 All IPv6 More
Any ideas?
]]>Timeout when waiting for 127.0.0.1:8500
When I ssh into the server and run:curl localhost:8500 I get: curl: (7) Failed to connect to localhost port 8500: Connection refused
Somehow port 8500 is not allowed. Is it possible that Digital Ocean is blocking this? I looked at my firewall rules and my droplet allows all TCP ports for inbound and outbound (FYI I have other droplets using the same firewall rules and they don’t have the issue)
]]>SSH & FTP connection refused
When i check system log there is error message.
Failed to start OpenBSD Secure shell server
Is there anyone who can help?
]]>Here’s an idea - why not block outgoing port 25 until you have validated a credit card. At least that way you’d be making money from all the spammers that you host.
You do realise that you are actually responsible for the customers that you choose for your services, right? You can’t just say “oh bad people signed up, what a surprise”.
]]>I am trying to reverse proxy requests to the node server but it seems I am unable to communicate with the two instances.
In order to debug this, I am trying to simply determine how to get one droplet to communicate to another droplet using the private IP.
Currently, when I ping or telnet to the private IP of droplet #2, I get 100% loss of packets for ping and telnet does not respond either.
Can you please help me to understand if I am missing a firewall rule or some other configuration setting to get the two to communicate? I would have thought they could communicate over the private network.
Thanks, Gregg
]]>Weeks ago, I already asked a question for how to customize DO managed Kubernetes firewall on forum.
I know how to ADD new firewall rules now, but I don’t know how to customize EXISTING RULES which already added by default DO Kubernetes.
For example, DO defaultly marked that Kubernetes NodePort range (30000 ~ 32767) as a public access, which allows every IPs without any restrictions.
But I want to ONLY ALLOW my own IP to reach NodePort in this case.
Already tried to make an additional firewall with IP restriction on NodePort range, and bound it with my DOKS cluster, But didn’t work properly.
Any helpful tips for this?
Thanks.
]]>Access Blueprints Repositories
MySQL Group Replication with ProxySQL
DigitalOcean Blueprints provide you with fast and flexible infrastructure to support you as you scale. You can leverage and incorporate Blueprints as part of your development workflow to spend more time crafting code and less time setting up your infrastructure.
DigitalOcean Blueprints offer automated multi-server infrastructure setups. The goal of each Blueprint is to give developers a way to streamline the infrastructure setup process so they can spend more time bringing ideas and projects to life.
Blueprints can be the foundation of a project or a component in a multi-server environment. As a starting point for further work, Blueprints leave configuration and content creation within developers’ hands while giving them a tool for getting started quickly.
Each Blueprint uses Terraform and Ansible to create an infrastructure setup with DigitalOcean products that addresses a different use case:
Node.js Web Application: This Blueprint can be used to set up a two-node infrastructure with Nginx, Node.js, and MongoDB. The web and application layers are deployed on one server, while the database is located on the other. Data from the database is stored on a block storage device, and Cloud Firewalls are configured in front of each server to regulate traffic.
MySQL Group Replication with ProxySQL: This Blueprint provides a replicated database group setup using MySQL group replication and ProxySQL. The cloned setup creates a three-node replication database layer to handle project data. It also creates a ProxySQL server that is configured to manage queries and changes to the project’s backend.
Status Page Application: This Blueprint creates a status page using Cachet, an open-source status page application, and a two-node infrastructure. One of the two servers runs MySQL, while the other runs the Cachet application with Nginx and PHP-FRM. The two servers communicate over DigitalOcean’s private network, and customizable Cloud Firewalls are in place to further restrict access. Nginx is also configured with SSL/TLS certificates using Let’s Encrypt.
Each of these Blueprints can lay the groundwork for various use cases and provide a pattern that can be modified based on your needs.
Each Blueprint will be ready to clone and use after a few prerequisites are in place. You will need:
With these prerequisites in place, you will be able to take the following steps to get each Blueprint up and running:
Clone the repository.
Configure definitions and credentials for the Docker image and local repository.
Create your infrastructure.
From here, you will be able to customize your infrastructure and adapt it to your needs and use cases.
A good first step in putting the Blueprints to use will be to read each project’s README.md
in full. There, you will find detailed instructions for installation, as well as discussions of how to test, customize, and deprovision your infrastructure.
Access Blueprints Repositories
DigitalOcean Cloud Firewalls provide a powerful firewall service at the network level, protecting your resources from unauthorized traffic.
Although you can configure Cloud Firewalls through the DigitalOcean Control Panel, when you have many Droplets to manage, need to script a process, or prefer working from the terminal, a command-line interface can be a better choice.
In this tutorial we’ll learn how to use doctl
—the official DigitalOcean Command-Line Client—to create and manage Cloud Firewalls for a web server.
For this tutorial, you will need:
doctl
version 1.7.0 installed and authenticated by following the official installation instructions in the doctl
GitHub repository. (Use the doctl version
command to verify which version of doctl
you’re running.)
An SSH key added to your DigitalOcean account by following the How To Use SSH Keys with DigitalOcean Droplets tutorial.
We’ll be creating a one-click LAMP (Linux, Apache, MySQL, PHP) stack image running Ubuntu 16.04, in the nyc1 region, and we’ll put this on a 512MB Droplet. Before beginning this tutorial, though, we recommend that you familiarize yourself with doctl
and Cloud Firewalls by reading How To Use Doctl, the Official DigitalOcean Command-Line Client and An Introduction To DigitalOcean Cloud Firewalls.
First, we’ll choose a region for our Droplet. We’ll be using nyc1 in this tutorial, but you can see all of the regions and their slugs with the following command:
- doctl compute region list
OutputSlug Name Available
nyc1 New York 1 true
sfo1 San Francisco 1 true
ams2 Amsterdam 2 true
sgp1 Singapore 1 true
lon1 London 1 true
nyc3 New York 3 true
ams3 Amsterdam 3 true
fra1 Frankfurt 1 true
tor1 Toronto 1 true
sfo2 San Francisco 2 true
blr1 Bangalore 1 true
Since we don’t want to send passwords over the network and we want to reduce the possibility of a brute-force attack, we’ll secure our web server with SSH key authentication.
To create a Droplet that includes an SSH key, doctl
requires the SSH key fingerprint, which you can obtain with the command:
- doctl compute ssh-key list
OutputID Name FingerPrint
9763174 sammy_rsa your_ssh_key_fingerprint
Copy the fingerprint of the SSH key you want to use with your Droplet.
Now, let’s bring everything together in a single command that will create a 512MB Droplet named web-1 in the nyc1 region, using a one-click LAMP stack image running Ubuntu 16.04 with our SSH key.
- doctl compute droplet create web-1 \
- --region nyc1 \
- --image lamp-16-04 \
- --ssh-keys your_ssh_key_fingerprint \
- --size 512mb
The output gives us an overview of the Droplet we just created, including the Droplet’s ID, name, IPv4 address, Memory, and more:
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags
52059458 web-1 512 1 20 nyc1 Ubuntu LAMP on 16.04 new
Note: You will need to wait a few minutes for the provisioning process to complete. Once provisioned, the Droplet will have an IPv4 address and a status of active
instead of new
.
Use the following command to check your Droplet’s status, and, if it’s fully provisioned, make note of the ID as we’ll need it when assigning the firewall to the Droplet in Step 2. Do not move past this step until your Droplet’s status reads active
.
- doctl compute droplet list web-1
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags
52059458 web-1 203.0.113.1 512 1 20 nyc1 Ubuntu LAMP on 16.04 active
Next, use doctl
to log into the Droplet via SSH, enabling your LAMP installation and getting additional instructions about how to prepare your server for production use. If you get a connection refused
error message, your Droplet is not yet ready. Wait a few minutes and then re-run the list
command to verify that your Droplet’s status is set to active
before continuing.
- doctl compute ssh web-1
Output...
-------------------------------------------------------------------------------
Thank you for using DigitalOcean's LAMP Application.
LAMP has now been enabled. You can access your LAMP instance at:
Your web root is located at /var/www/html and can be seen from
http://203.0.113.1
...
After you configure the Droplet for your needs, exit the SSH session.
- [environment]
- exit
Finally, point your web browser to the Droplet’s IP address to make sure that the LAMP stack is working correctly. You should see the default DigitalOcean one-click LAMP stack landing page with the message: “Please log into your droplet via SSH to configure your LAMP installation.” If you don’t, re-trace the preceeding steps to ensure that you’ve enabled LAMP and that you’ve correctly copied your Droplet’s IP address into your browser.
Because we’ve already completed the LAMP configuration required for this tutorial, we’re ready to move on to protecting the Droplet from unauthorized traffic.
To begin, we’ll use the Droplet ID that we got from the doctl compute droplet list
command in Step 1 to create a Cloud Firewall named web-firewall
that allows inbound SSH connections on port 22
and all outbound TCP, UDP and ICMP connections. This will let us administer the server from the command line while still giving many fundamental services the ability to operate normally.
The protocol
field is required and must be set either to tcp
, udp
, or icmp
, and you must include a ports
value for all protocols except icmp
which, by its specification, doesn’t require one.
The address
field specifies which IP addresses are allowed to access a given port. If you want to allow traffic from all IPv4 addresses, use 0:0:0:0/0
, and if you want to allow traffic from all IPv6 addresses, use ::0/0
.
Lastly, each Firewall that you create must have at least one rule, either under the --inbound-rules
or --outbound-rules
flag, and all values must be entered as comma-separated key:value
lists. Use a quoted string of space-separated values for multiple rules.
Now, use the create
command create the firewall:
- doctl compute firewall create --name web-firewall \
- --droplet-ids your_droplet_id \
- --inbound-rules "protocol:tcp,ports:22,address:0.0.0.0/0,address:::/0" \
- --outbound-rules "protocol:icmp,address:0.0.0.0/0,address:::/0 protocol:tcp,ports:all,address:0.0.0.0/0,address:::/0 protocol:udp,ports:all,address:0.0.0.0/0,address:::/0"
The output contains a basic overview of the new Cloud Firewall. Make note of the Cloud Firewall’s ID, as you’ll use it in Step 3 to add additional rules to the Firewall.
OutputID Name Status Created At Inbound Rules Outbound Rules Droplet IDs Tags Pending Changes
c7b39b43-4fcc-4594-88f2-160a64aaddd4 web-firewall waiting 2017-06-17T21:20:38Z protocol:tcp,ports:22,address:0.0.0.0/0,address:::/0 protocol:icmp,ports:0,address:0.0.0.0/0,address:::/0 protocol:tcp,ports:0,address:0.0.0.0/0,address:::/0 protocol:udp,ports:0,address:0.0.0.0/0,address:::/0 your_droplet_id droplet_id:your_droplet_id,removing:false,status:waiting
If you ever need to specify a port range, use the following format:
--inbound-rules "protocol:tcp,ports:8000-8080,address:0.0.0.0/0,address:::/0"
You can also use the droplet_id
flag instead of the address
flag. This can be particularly useful in setups that involve multiple Droplets communicating with each other.
--inbound-rules "protocol:tcp,ports:8000-8080,droplet_id:your_droplet_id"
And, you can combine multiple address
or droplet_id
fields into a single rule, like:
--inbound-rules "protocol:tcp,ports:8000-8080,droplet_id:your_first_droplet_id,droplet_id:your_second_droplet_id"
At this point, confirm that the Cloud Firewall is working correctly by pointing your web browser to the Droplet’s IP address. You should see a message indicating that the site is no longer reachable. If you don’t, double-check the output from the previous create
command to make sure you didn’t miss any error messages.
Lastly, even though our inbound rule should already allow for SSH, we’ll verify it using doctl
.
- doctl compute ssh web-1
If you’re unable to connect to the Droplet, the How To Troubleshoot SSH tutorial series will help you diagnose the problem.
Once you’ve successfully connected to the Droplet, exit the SSH session:
- [environment]
- exit
As we’ve now verified that the Cloud Firewall is working correctly, we’ll add an additional rule to allow for incoming traffic to the web server.
Using the Firewall ID that we got from the doctl compute firewall create
command in Step 2, we are now going to add a rule to allow inbound TCP traffic for Apache on port 80
.
We’ll use the add-rules
command, which requires a Firewall ID and at least one rule. Rules are specified using --outbound-rules
and --inbound-rules
flags, just like in Step 2.
- doctl compute firewall add-rules c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --inbound-rules "protocol:tcp,ports:80,address:0.0.0.0/0,address:::/0"
If you need HTTPS, allow inbound TCP traffic on port 443
.
- doctl compute firewall add-rules c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --inbound-rules "protocol:tcp,ports:443,address:0.0.0.0/0,address:::/0"
If successful, this command will produce no output. If you receive an error message, follow the on-screen instructions to diagnose the problem.
Now, re-point your web browser to your Droplet’s IP address. This time you should see the default DigitalOcean one-click LAMP stack landing page again. If you don’t, double-check that you’ve correctly copied your IP address into your web browser and then re-trace the preceeding steps.
If you have additional web servers that you’d like to protect, continue on to Step 4. Otherwise, skip ahead to Step 5 where we’ll manage Cloud Firewalls with tags.
If you have multiple Droplets, you can apply the same Cloud Firewall to each of them.
Use the add-droplets
command to add additional Droplets to a Cloud Firewall. This command requires a Cloud Firewall ID as an argument, and it uses the droplet-ids
flag to determine which Droplets to apply the Firewall to.
If you don’t know the Cloud Firewall’s ID, use the list
command:
- doctl compute firewall list
OutputID Name Status Created At Inbound Rules Outbound Rules Droplet IDs Tags Pending Changes
c7b39b43-4fcc-4594-88f2-160a64aaddd4 web-firewall succeeded 2017-06-17T21:20:38Z protocol:tcp,ports:22,address:0.0.0.0/0,address:::/0 protocol:tcp,ports:80,address:0.0.0.0/0,address:::/0 protocol:icmp,ports:0,address:0.0.0.0/0,address:::/0 protocol:tcp,ports:0,address:0.0.0.0/0,address:::/0 protocol:udp,ports:0,address:0.0.0.0/0,address:::/0 52059458
You can also use the list
command to get Droplets’ IDs:
- doctl compute droplet list
OutputID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image Status Tags
51146959 test-1 203.0.113.1 512 1 20 nyc1 Ubuntu LAMP on 16.04 active
52059458 web-1 203.0.113.2 512 1 20 nyc1 Ubuntu LAMP on 16.04 active
Using the following doctl
command, we’ll add the test-1
Droplet to the web-servers
Firewall, which has an ID of c7b39b43-4fcc-4594-88f2-160a64aaddd4
:
- doctl compute firewall add-droplets c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --droplet-ids 51146959
If you don’t receive any output, the command was successful. If you receive an error message, follow the on-screen instructions to diagnose the problem.
And, if you want to add multiple Droplets at once, separate them out using commas. Note that there are no spaces between two IDs:
--droplet-ids 51146959,52059458
Now, let’s use Tags for easier Cloud Firewall management.
At this point, we’ve added individual Droplets to the Cloud Firewall, but Cloud Firewalls also support Tags for easier management of multiple resources. To better understand how Tags work, see How To Tag DigitalOcean Droplets.
In this step, we’ll tag Droplets, add Tags to the Cloud Firewall, and then remove the individual Droplet IDs from the Firewall keeping the Droplets secure by way of Tags.
Before we can add a Tag to a Droplet using doctl
, we need to first create the Tag with the tag create
command:
- doctl compute tag create web-servers
OutputName Droplet Count
web-servers 0
Once the Tag is created, apply it to the Droplet using the droplet tag
command. This command takes the Droplet ID as an argument, and it gets the Tag name from the --tag-name
flag.
- doctl compute droplet tag 52059458 \
- --tag-name "web-servers"
If you want to secure multiple Droplets with one Cloud Firewall, repeat the previous command for each Droplet.
Next, add the Tag to the Cloud Firewall with the add-tags
command, which takes the Firewall ID as an argument and gets the list of Tag names to use from the --tag-names
flag:
- doctl compute firewall add-tags c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --tag-names web-servers
If you don’t receive any output, the command was successful. If you receive an error message, follow the on-screen instructions to diagnose the problem.
And, if you need to add multiple Tags, provide them as a comma-separated list:
--tag-names web-servers,backend-servers
Finally, we can remove the Droplet’s ID from the Firewall, because the Droplet is part of the web-servers
Tag, and that entire Tag is now protected.
- doctl compute firewall remove-droplets c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --droplet-ids 52059458
Repeat the previous step for each Droplet you want to secure by Tag only.
Warning: Removing non-tagged Droplets from the Cloud Firewall leaves the Droplets unprotected from unauthorized traffic.
You now have a fully configured Cloud Firewall which will protect your web server from unauthorized traffic. If you also want to delete a rule from the Firewall, continue on to Step 6.
If you want to remove a rule from a Cloud Firewall, use the remove-rules
command.
The remove-rules
command takes a Firewall ID as its argument, and rules are specified using the --outbound-rules
and --inbound-rules
flags. Note that the specified rule must be exactly the same as the rule that was used during creation.
- doctl compute firewall remove-rules c7b39b43-4fcc-4594-88f2-160a64aaddd4 \
- --inbound-rules protocol:tcp,ports:80,address:0.0.0.0/0,address:::/0
If you don’t receive any output, the command was successful. If you receive an error message, follow the on-screen instructions to diagnose the problem.
In this tutorial, we used doctl
to create DigitalOcean Cloud Firewalls, add rules to those Firewalls, add additional Droplets to the Firewalls, manage Firewalls with Tags, and remove rules from Firewalls.
To learn other ways to use Cloud Firewalls, see How To Organize DigitalOcean Cloud Firewalls.
And, to learn about troubleshooting Cloud Firewalls, visit How To Troubleshoot DigitalOcean Firewalls.
]]>DigitalOcean Cloud Firewalls provide a powerful firewall service at the network level, leaving your servers free to do their job of serving your applications and storing your data. In this tutorial, we will adapt a two-server Wordpress and MySQL setup to use Cloud Firewalls, and demonstrate some of the advantages this service can provide. If you’d like more background on this firewall service before beginning, please read our Introduction To DigitalOcean Cloud Firewalls tutorial.
Before starting this tutorial, you’ll need to have created the infrastructure outlined in How To Set Up a Remote Database to Optimize Site Performance with MySQL on Ubuntu 16.04. This will leave you with two servers, an Nginx web server with PHP and WordPress installed, and a standalone MySQL server. Throughout this tutorial we will call these servers frontend-01 and database-01 respectively.
Right now, both of our servers have firewalls set up using the ufw
utility. ufw
is an easy-to-use wrapper around Linux’s iptables firewall engine. Log in to both servers now and let’s check the status of our firewalls:
First, on the web server, frontend-01:
- sudo ufw status verbose
OutputStatus: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp (OpenSSH) ALLOW IN Anywhere
80,443/tcp (Nginx Full) ALLOW IN Anywhere
22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6)
80,443/tcp (Nginx Full (v6)) ALLOW IN Anywhere (v6)
In the output, after Default:
we are shown that the firewall is, by default, denying all incoming connections and allowing all outgoing connections. Additionally we have four rules that allow incoming IPv4 and IPv6 TCP connections (ALLOW IN
) to ports 22 (SSH), 80 (HTTP), and 443 (HTTPS).
Let’s do the same thing on the database server, database-01:
- sudo ufw status verbose
OutputStatus: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp (OpenSSH) ALLOW IN Anywhere
3306 ALLOW IN Anywhere
22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6)
3306 (v6) ALLOW IN Anywhere (v6)
This output is similar, except we’ve swapped the two Nginx ports for port 3306, which is the standard MySQL port. Now that we know our current setup, let’s plan our replacement.
Although we could just make two Cloud Firewalls, one tailored for each specific server, and apply one to frontend-01 and the other to database-01, we’re going take a more flexible approach to how we organize our rules.
First, we want to leave ourselves prepared for a future where we may need to add a third type of service to this system (perhaps a cache server). So we’re going to split up our firewall rules based on roles, not by physical server. We can apply multiple Cloud Firewalls to each Droplet, so it’s not a problem to make these firewalls fine-grained and modular.
Note: If you would like a more in-depth exploration of best-practices regarding structuring your Cloud Firewalls, please read How To Organize DigitalOcean Cloud Firewalls.
If we break things down a bit, we notice that both of our servers actually have multiple functions. There’s the primary function of either serving web pages or database information, and there’s also a management function provided by the SSH service. It would make good sense for us to create a management firewall, a frontend firewall, and a database firewall.
To handle the future scenario where we scale our web or database services to multiple hosts, we’ll use DigitalOcean’s tagging feature to organize our Droplets by role. Tags are simple labels we can apply to Droplets to categorize them and address whole groups of servers at once. The Cloud Firewall service can apply firewall rules to all Droplets in a tag, making it easy to provision new Droplets with the correct firewall rules already in place.
An additional bonus – and something that would be difficult do in a dynamic way using ufw
– is that Cloud Firewalls can restrict inbound access based on tags. So for instance, our database servers only need to be accessible from our frontend servers. The current ufw
setup has the database open to anybody on the network. We’ll lock that down to only our Droplets tagged with frontend.
Let’s summarize the three firewalls we need to set up, in plain language:
We’re not going to restrict outbound traffic at all in this tutorial. It’s not a bad idea, but it does take some care to make sure you don’t break auto-update mechanisms and other critical features of the underlying operating system.
Now that we have a plan for our new firewalls, let’s get started.
First, we’ll tag our Droplets by role, in preparation for our firewall rules. Navigate to the DigitalOcean Control Panel. The default view is a list of your Droplets. Click on the More button to the right of your frontend-01 Droplet, and select Add tags:
A text box will pop up where you can enter tags for this Droplet. Enter frontend and click the Add Tags button:
Do the same for your database server, giving it a database tag. The tags will show up in your Droplet list:
When creating future Droplets, you could apply these tags during the initial provisioning process. The Droplets will then automatically inherit the corresponding firewall rules.
We’ll set up those rules in the next step.
We’re going to set up our Cloud Firewalls now. We’ll do the frontend firewall first, followed by database, then management. This order should result in no service disruptions for your website visitors, but we will temporarily lose the ability to make new SSH connections. This will not affect already established connections.
The Firewalls service is available under the Networking section on the DigitalOcean Control Panel. Once there, click the Firewalls tab, then click the Create Firewall button to get started.
On the Create Firewall page, we need to fill out a Name, configure our Inbound Rules, and select which Droplets to apply the firewall to. We will leave the Outbound Rules section as is.
We’re creating the frontend firewall first, so put frontend-fw in the Name field.
Note: We’ll add -fw to the end of our firewall names to disambiguate them. Though the Control Panel interface uses icons to differentiate between resource types, it could get confusing if you’re using the command line or API and have multiple frontend items, for instance.
Next, we need to delete the default SSH rule from the Inbound Rules section. We’ll break this rule out into the management firewall for flexibility. Use the Delete link on the right-hand side of the page to delete the SSH rule now.
Then, click on the New rule dropdown and select HTTP. This will autofill the correct protocol (TCP) and port (80), and by default allow traffic from all IPv4 and IPv6 addresses. This is what we want.
If you have HTTPS enabled, repeat the above process to create a second rule, selecting HTTPS this time. Your Inbound Rules section will end up like this:
Finally, in the Apply to Droplets field, start typing frontend then select the frontend tag when it is auto-suggested.
Click the Create Firewall button. The new firewall will be created and applied to any Droplet with the frontend tag. You will be returned to an updated firewall summary page showing your new firewall:
Now we’ll create the database firewall.
On the Firewalls page, click Create Firewall again. The process will be mostly the same as for our frontend firewall.
Type database-fw into the Name field.
In Inbound Rules, delete the default SSH rule. Then, create a new rule using the dropdown, selecting MySQL. A default MySQL rule will be created allowing access to port 3306 from all IPs. Delete All IPv4 and All IPv6 from the Sources field. We want only our frontend servers to be able to access the database. Start typing frontend into the Sources box, and select the frontend tag when it is auto-suggested. Now any Droplet with that tag applied will be allowed access to the database server. All other IPs are blocked.
Leave the Outbound Rules as is. Under Apply to Droplets, apply this firewall to the database tag, then click Create Firewall. Once again, you’ll be returned to the firewall summary page:
Note that both firewalls show that they are applied to one Droplet each. If you load your website, it should still load fine. Now let’s re-enabled management via SSH.
Click Create Firewall one last time. Add management-fw to the Name field.
The default SSH rule is all we need for this firewall. This will allow any IP to connect to port 22.
Alternately, you could change the Sources field of the SSH rule to a specific IP that you’ll be connecting from. For instance, if your office has a static IP, and you want to restrict SSH access to only connections from the office, put that IP in Sources, replacing All IPv4 and All IPv6. If your IP ever changes in the future, you’ll just have to update this one rule to restore management access, another advantage of planning ahead and making our rules modular.
Under Apply to Droplets, add both the frontend and database tags, then click Create Firewall. Let’s take a look at our final firewall summary:
At this point, our Cloud Firewall should be fully functional, but we also still have the host-based ufw
firewalls active. Let’s disable those, then test our connections.
We need to disable the ufw
firewall on both hosts. First, on frontend-01:
- sudo ufw disable
OutputFirewall stopped and disabled on system startup
Then on database-01:
- sudo ufw disable
OutputFirewall stopped and disabled on system startup
This stops the current firewall, flushes out all of the rules, and prevents the rules from being re-enabled on startup.
At this point, all of our connectivity should be restored. Try creating a new SSH session to one of your servers. Then load your website to verify that the web server is still connecting to the database and returning webpages to the browser.
Being able to connect to all of our services doesn’t actually prove that a firewall is functioning though. Let’s do a little more testing to verify that our firewalls are actually in place.
To test our firewalls, we’re going to log in to a third server, and use a utility called nmap
to scan our web and database servers. nmap
is a port scanner that will scan our hosts and tell us which ports are open, closed, or filtered.
Log in to another Ubuntu 16.04 server that’s in the same region as your frontend-01 and database-01 servers. Then install nmap
:
- sudo apt-get update
- sudo apt-get install nmap
Then, use nmap
to scan the web server’s public IP:
- nmap -Pn frontend-01_public_ip
OutputStarting Nmap 7.01 ( https://nmap.org ) at 2017-06-05 17:08 UTC
Nmap scan report for 203.0.113.11
Host is up (0.0022s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
443/tcp open https
Nmap done: 1 IP address (1 host up) scanned in 4.54 seconds
Note the output about filtered ports
. If the firewall was not functioning, these would show as closed ports
. Filtered means that nmap
can’t even connect to determine if the port is open or closed.
Note also that we see our SSH, HTTP, and HTTPS ports are open, as expected.
Next, we’ll scan the database server. Be sure to use the Droplet’s private IP if you’ve set it up that way, as that’s what the MySQL database will be listening on:
- nmap -Pn database-01_private_ip
OutputStarting Nmap 7.01 ( https://nmap.org ) at 2017-06-05 17:21 UTC
Nmap scan report for 198.51.100.20
Host is up (0.0024s latency).
Not shown: 999 filtered ports
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 8.17 seconds
We see that most ports are filtered, as before. However, we’re only seeing the SSH port as open, with no MySQL port available. Recall that we restricted database access to only those servers tagged with frontend. Switch back over to the DigitalOcean Control Panel and add the frontend tag to the server you’re using nmap
from. Then rerun the command:
- nmap -Pn database-01_private_ip
OutputStarting Nmap 7.01 ( https://nmap.org ) at 2017-06-05 17:22 UTC
Nmap scan report for 198.51.100.20
Host is up (0.0033s latency).
Not shown: 998 filtered ports
PORT STATE SERVICE
22/tcp open ssh
3306/tcp open mysql
Nmap done: 1 IP address (1 host up) scanned in 4.46 seconds
The MySQL port now shows as open. We’ve verified that both of our servers are now protected by our Cloud Firewall rules. You can now restore this test server’s original firewall settings by returning to the Control Panel and removing the Droplet’s frontend tag.
In this tutorial we’ve replaced a ufw
firewall setup with a flexible and powerful network-based Cloud Firewall configuration. For more information on using Cloud Firewalls via doctl
or the DigitalOcean API, please see the following articles: