Skip to content

Commit e8dcadf

Browse files
m-strzelczykdinagravesrsamborski
authored andcommitted
chore(docs): Adding firewall samples. (#117)
Co-authored-by: Dina Graves Portman <dinagraves@google.com> Co-authored-by: Remigiusz Samborski <rsamborski@users.noreply.github.com>
1 parent e8641cf commit e8dcadf

File tree

2 files changed

+246
-0
lines changed

2 files changed

+246
-0
lines changed
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
from typing import Iterable
17+
18+
# [START compute_firewall_list]
19+
# [START compute_firewall_create]
20+
# [START compute_firewall_patch]
21+
# [START compute_firewall_delete]
22+
import google.cloud.compute_v1 as compute_v1
23+
# [END compute_firewall_delete]
24+
# [END compute_firewall_patch]
25+
# [END compute_firewall_create]
26+
# [END compute_firewall_list]
27+
28+
29+
# [START compute_firewall_list]
30+
def list_firewall_rules(project_id: str) -> Iterable:
31+
"""
32+
Return a list of all the firewall rules in specified project. Also prints the
33+
list of firewall names and their descriptions.
34+
35+
Args:
36+
project_id: project ID or project number of the Cloud project you want to use.
37+
38+
Returns:
39+
A flat list of all firewall rules defined for given project.
40+
"""
41+
firewall_client = compute_v1.FirewallsClient()
42+
firewalls_list = firewall_client.list(project=project_id)
43+
44+
for firewall in firewalls_list:
45+
print(f" - {firewall.name}: {firewall.description}")
46+
47+
return firewalls_list
48+
# [END compute_firewall_list]
49+
50+
51+
def print_firewall_rule(project_id: str, firewall_rule_name: str):
52+
firewall_client = compute_v1.FirewallsClient()
53+
print(firewall_client.get(project=project_id, firewall=firewall_rule_name))
54+
55+
56+
# [START compute_firewall_create]
57+
def create_firewall_rule(
58+
project_id: str, firewall_rule_name: str, network: str = "global/networks/default"
59+
):
60+
"""
61+
Creates a simple firewall rule allowing for incoming HTTP and HTTPS access from the entire Internet.
62+
63+
Args:
64+
project_id: project ID or project number of the Cloud project you want to use.
65+
firewall_rule_name: name of the rule that is created.
66+
network: name of the network the rule will be applied to. Available name formats:
67+
* https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
68+
* projects/{project_id}/global/networks/{network}
69+
* global/networks/{network}
70+
"""
71+
firewall_rule = compute_v1.Firewall()
72+
firewall_rule.name = firewall_rule_name
73+
firewall_rule.direction = compute_v1.Firewall.Direction.INGRESS
74+
75+
tcp_80_443_allowed = compute_v1.Allowed()
76+
tcp_80_443_allowed.I_p_protocol = "tcp"
77+
tcp_80_443_allowed.ports = ["80", "443"]
78+
79+
firewall_rule.allowed = [tcp_80_443_allowed]
80+
firewall_rule.source_ranges = ["0.0.0.0/0"]
81+
firewall_rule.network = network
82+
firewall_rule.description = "Allowing TCP traffic on port 80 and 443 from Internet."
83+
84+
# Note that the default value of priority for the firewall API is 1000.
85+
# If you check the value of `firewall_rule.priority` at this point it
86+
# will be equal to 0, however it is not treated as "set" by the library and thus
87+
# the default will be applied to the new rule. If you want to create a rule that
88+
# has priority == 0, you need to explicitly set it so:
89+
90+
# firewall_rule.priority = 0
91+
92+
firewall_client = compute_v1.FirewallsClient()
93+
op = firewall_client.insert(project=project_id, firewall_resource=firewall_rule)
94+
95+
op_client = compute_v1.GlobalOperationsClient()
96+
op_client.wait(project=project_id, operation=op.name)
97+
98+
return
99+
# [END compute_firewall_create]
100+
101+
102+
# [START compute_firewall_patch]
103+
def patch_firewall_priority(project_id: str, firewall_rule_name: str, priority: int):
104+
"""
105+
Modifies the priority of a given firewall rule.
106+
107+
Args:
108+
project_id: project ID or project number of the Cloud project you want to use.
109+
firewall_rule_name: name of the rule you want to modify.
110+
priority: the new priority to be set for the rule.
111+
"""
112+
firewall_rule = compute_v1.Firewall()
113+
firewall_rule.priority = priority
114+
115+
# The patch operation doesn't require the full definition of a Firewall object. It will only update
116+
# the values that were set in it, in this case it will only change the priority.
117+
firewall_client = compute_v1.FirewallsClient()
118+
operation = firewall_client.patch(
119+
project=project_id, firewall=firewall_rule_name, firewall_resource=firewall_rule
120+
)
121+
122+
operation_client = compute_v1.GlobalOperationsClient()
123+
operation_client.wait(project=project_id, operation=operation.name)
124+
return
125+
# [END compute_firewall_patch]
126+
127+
128+
# [START compute_firewall_delete]
129+
def delete_firewall_rule(project_id: str, firewall_rule_name: str):
130+
"""
131+
Deleted a firewall rule from the project.
132+
133+
Args:
134+
project_id: project ID or project number of the Cloud project you want to use.
135+
firewall_rule_name: name of the firewall rule you want to delete.
136+
"""
137+
firewall_client = compute_v1.FirewallsClient()
138+
operation = firewall_client.delete(project=project_id, firewall=firewall_rule_name)
139+
140+
operation_client = compute_v1.GlobalOperationsClient()
141+
operation_client.wait(project=project_id, operation=operation.name)
142+
return
143+
# [END compute_firewall_delete]
144+
145+
146+
if __name__ == "__main__":
147+
import google.auth
148+
import google.auth.exceptions
149+
150+
try:
151+
default_project_id = google.auth.default()[1]
152+
print(f"Using project {default_project_id}.")
153+
except google.auth.exceptions.DefaultCredentialsError:
154+
print(
155+
"Please use `gcloud auth application-default login` "
156+
"or set GOOGLE_APPLICATION_CREDENTIALS to use this script."
157+
)
158+
else:
159+
import uuid
160+
161+
rule_name = "firewall-sample-" + uuid.uuid4().hex[:10]
162+
print(f"Creating firewall rule {rule_name}...")
163+
# The rule will be created with default priority of 1000.
164+
create_firewall_rule(default_project_id, rule_name)
165+
try:
166+
print("Rule created:")
167+
print_firewall_rule(default_project_id, rule_name)
168+
print("Updating rule priority to 10...")
169+
patch_firewall_priority(default_project_id, rule_name, 10)
170+
print("Rule updated: ")
171+
print_firewall_rule(default_project_id, rule_name)
172+
print(f"Deleting rule {rule_name}...")
173+
finally:
174+
delete_firewall_rule(default_project_id, rule_name)
175+
print("Done.")
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import time
15+
import uuid
16+
17+
import google.auth
18+
from google.cloud import compute_v1
19+
import pytest
20+
21+
22+
from sample_firewall import (
23+
create_firewall_rule,
24+
delete_firewall_rule,
25+
list_firewall_rules,
26+
patch_firewall_priority,
27+
)
28+
29+
PROJECT = google.auth.default()[1]
30+
31+
32+
@pytest.fixture
33+
def firewall_rule():
34+
firewall_rule = compute_v1.Firewall()
35+
firewall_rule.name = "firewall-sample-test" + uuid.uuid4().hex[:10]
36+
firewall_rule.direction = compute_v1.Firewall.Direction.INGRESS
37+
tcp_80_443_allowed = compute_v1.Allowed()
38+
tcp_80_443_allowed.I_p_protocol = "tcp"
39+
tcp_80_443_allowed.ports = ["80"]
40+
firewall_rule.allowed = [tcp_80_443_allowed]
41+
firewall_rule.source_ranges = ["0.0.0.0/0"]
42+
firewall_rule.network = "global/networks/default"
43+
firewall_rule.description = "Rule generated by Python sample test fixture."
44+
45+
firewall_client = compute_v1.FirewallsClient()
46+
op = firewall_client.insert(project=PROJECT, firewall_resource=firewall_rule)
47+
48+
op_client = compute_v1.GlobalOperationsClient()
49+
op_client.wait(project=PROJECT, operation=op.name)
50+
51+
yield firewall_client.get(project=PROJECT, firewall=firewall_rule.name)
52+
53+
op = firewall_client.delete(project=PROJECT, firewall=firewall_rule.name)
54+
op_client.wait(project=PROJECT, operation=op.name)
55+
56+
57+
def test_create_delete():
58+
rule_name = "firewall-sample-test-" + uuid.uuid4().hex[:10]
59+
create_firewall_rule(PROJECT, rule_name)
60+
assert any(rule.name == rule_name for rule in list_firewall_rules(PROJECT))
61+
delete_firewall_rule(PROJECT, rule_name)
62+
assert all(rule.name != rule_name for rule in list_firewall_rules(PROJECT))
63+
64+
65+
def test_patch_rule(firewall_rule):
66+
fw_client = compute_v1.FirewallsClient()
67+
assert firewall_rule.priority == 1000
68+
patch_firewall_priority(PROJECT, firewall_rule.name, 500)
69+
time.sleep(2)
70+
updated_firewall_rule = fw_client.get(project=PROJECT, firewall=firewall_rule.name)
71+
assert updated_firewall_rule.priority == 500

0 commit comments

Comments
 (0)