Skip to content

Commit 2db3322

Browse files
authored
feat(compute): Firewall samples refactor (GoogleCloudPlatform#1593)
Moving firewall samples to a new folder to match agreed structure for upcoming sample work.
1 parent 931263a commit 2db3322

File tree

12 files changed

+334
-72
lines changed

12 files changed

+334
-72
lines changed
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
Google Cloud Compute Engine PHP Samples - Firewall
2+
==================================================
3+
4+
[![Open in Cloud Shell][shell_img]][shell_link]
5+
6+
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.svg
7+
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googlecloudplatform/php-docs-samples&page=editor&working_dir=compute/cloud-client/instances
8+
9+
This directory contains samples for calling [Google Cloud Compute Engine][compute] APIs
10+
from PHP. Specifically, they show how to manage your [VPC firewall rules][firewall_rules].
11+
12+
[compute]: https://cloud.google.com/compute/docs/apis
13+
[firewall_rules]: https://cloud.google.com/vpc/docs/firewalls
14+
15+
## Setup
16+
17+
### Authentication
18+
19+
Authentication is typically done through [Application Default Credentials][adc]
20+
which means you do not have to change the code to authenticate as long as
21+
your environment has credentials. You have a few options for setting up
22+
authentication:
23+
24+
1. When running locally, use the [Google Cloud SDK][google-cloud-sdk]
25+
26+
gcloud auth application-default login
27+
28+
1. When running on App Engine or Compute Engine, credentials are already
29+
set. However, you may need to configure your Compute Engine instance
30+
with [additional scopes][additional_scopes].
31+
32+
1. You can create a [Service Account key file][service_account_key_file]. This file can be used to
33+
authenticate to Google Cloud Platform services from any environment. To use
34+
the file, set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to
35+
the path to the key file, for example:
36+
37+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json
38+
39+
[adc]: https://cloud.google.com/docs/authentication#getting_credentials_for_server-centric_flow
40+
[additional_scopes]: https://cloud.google.com/compute/docs/authentication#using
41+
[service_account_key_file]: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
42+
43+
## Install Dependencies
44+
45+
1. **Install dependencies** using [Composer](http://getcomposer.org/doc/00-intro.md).
46+
Run `php composer.phar install` (if composer is installed locally) or `composer install`
47+
(if composer is installed globally).
48+
49+
1. Create a [service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts#creating).
50+
51+
1. [Download the json key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys#getting_a_service_account_key)
52+
of the service account.
53+
54+
1. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable pointing to that file.
55+
56+
## Samples
57+
58+
To run the Compute samples, run any of the files in `src/` on the CLI to print
59+
the usage instructions:
60+
61+
```
62+
$ php list_firewall_rules.php
63+
64+
Usage: list_firewall_rules.php $projectId
65+
66+
@param string $projectId Project ID or project number of the Cloud project you want to list rules from.
67+
```
68+
69+
### Create a firewall rule
70+
71+
```
72+
$ php src/create_firewall_rule.php $YOUR_PROJECT_ID "my-firewall-rule"
73+
Created rule my-firewall-rule
74+
```
75+
76+
### List firewall rules
77+
78+
```
79+
$ php src/list_firewall_rules.php $YOUR_PROJECT_ID
80+
--- Firewall Rules ---
81+
- default-allow-icmp : Allow ICMP from anywhere : https://www.googleapis.com/compute/v1/projects/$YOUR_PROJECT_ID/global/networks/default
82+
- default-allow-internal : Allow internal traffic on the default network : https://www.googleapis.com/compute/v1/projects/$YOUR_PROJECT_ID/global/networks/default
83+
```
84+
85+
### Print firewall rule
86+
87+
```
88+
$ php src/print_firewall_rule.php $YOUR_PROJECT_ID "my-firewall-rule"
89+
ID: $ID
90+
Kind: compute#firewall
91+
Name: my-firewall-rule
92+
Creation Time: $TIMESTAMP
93+
Direction: INGRESS
94+
Network: https://www.googleapis.com/compute/v1/projects/$YOUR_PROJECT_ID/global/networks/default
95+
Disabled: false
96+
Priority: 100
97+
Self Link: https://www.googleapis.com/compute/v1/projects/$YOUR_PROJECT_ID/global/firewalls/my-firewall-rule
98+
Logging Enabled: false
99+
--Allowed--
100+
Protocol: tcp
101+
- Ports: 80
102+
- Ports: 443
103+
--Source Ranges--
104+
- Range: 0.0.0.0/0
105+
```
106+
107+
### Delete a firewall rule
108+
109+
```
110+
$ php src/delete_firewall_rule.php $YOUR_PROJECT_ID "my-firewall-rule"
111+
Rule my-firewall-rule deleted successfully!
112+
```
113+
114+
### Set firewall rule priority
115+
116+
```
117+
$ php src/patch_firewall_priority.php $YOUR_PROJECT_ID "my-firewall-rule" 100
118+
Patched my-firewall-rule priority to 100.
119+
```
120+
121+
## Troubleshooting
122+
123+
If you get the following error, set the environment variable `GCLOUD_PROJECT` to your project ID:
124+
125+
```
126+
[Google\Cloud\Core\Exception\GoogleException]
127+
No project ID was provided, and we were unable to detect a default project ID.
128+
```
129+
130+
## The client library
131+
132+
This sample uses the [Google Cloud Compute Client Library for PHP][google-cloud-php].
133+
You can read the documentation for more details on API usage and use GitHub
134+
to [browse the source][google-cloud-php-source] and [report issues][google-cloud-php-issues].
135+
136+
[google-cloud-php]: https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.152.0/compute/readme
137+
[google-cloud-php-source]: https://github.com/GoogleCloudPlatform/google-cloud-php
138+
[google-cloud-php-issues]: https://github.com/GoogleCloudPlatform/google-cloud-php/issues
139+
[google-cloud-sdk]: https://cloud.google.com/sdk/
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"require": {
3+
"google/cloud-compute": "^1.0.0",
4+
"google/cloud-storage": "^1.26"
5+
}
6+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
xml version="1.0" encoding="UTF-8"?>
2+
17+
<phpunit bootstrap="../../../testing/bootstrap.php">
18+
<testsuites>
19+
<testsuite name="Google Compute Cloud Client Instances Tests">
20+
<directory>testdirectory>
21+
testsuite>
22+
testsuites>
23+
<logging>
24+
<log type="coverage-clover" target="build/logs/clover.xml"/>
25+
logging>
26+
<filter>
27+
<whitelist>
28+
<directory suffix=".php">srcdirectory>
29+
<exclude>
30+
<directory>./vendordirectory>
31+
exclude>
32+
whitelist>
33+
filter>
34+
phpunit>
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
2+
/**
3+
* Copyright 2022 Google LLC
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace Google\Cloud\Samples\Compute;
19+
20+
use Google\ApiCore\ApiException;
21+
use Google\Cloud\TestUtils\TestTrait;
22+
use PHPUnit\Framework\TestCase;
23+
24+
class firewallTest extends TestCase
25+
{
26+
use TestTrait;
27+
28+
private static $firewallRuleName;
29+
private static $priority;
30+
31+
private const DEFAULT_ZONE = 'us-central1-a';
32+
33+
public static function setUpBeforeClass(): void
34+
{
35+
self::$firewallRuleName = sprintf('test-firewall-rule-%s', rand());
36+
self::$priority = 20;
37+
}
38+
39+
public function testCreateFirewallRule()
40+
{
41+
$output = $this->runFunctionSnippet('create_firewall_rule', [
42+
'projectId' => self::$projectId,
43+
'firewallRuleName' => self::$firewallRuleName
44+
]);
45+
$this->assertStringContainsString('Created rule ' . self::$firewallRuleName, $output);
46+
}
47+
48+
/**
49+
* @depends testCreateFirewallRule
50+
*/
51+
public function testPrintFirewallRule()
52+
{
53+
/* Catch API failure to check if it's a 404. In such case most probably the policy enforcer
54+
removed our fire-wall rule before this test executed and we should ignore the response */
55+
try {
56+
$output = $this->runFunctionSnippet('print_firewall_rule', [
57+
'projectId' => self::$projectId,
58+
'firewallRuleName' => self::$firewallRuleName
59+
]);
60+
$this->assertStringContainsString(self::$firewallRuleName, $output);
61+
$this->assertStringContainsString('0.0.0.0/0', $output);
62+
} catch (ApiException $e) {
63+
if ($e->getCode() != 404) {
64+
throw new ApiException($e->getMessage(), $e->getCode(), $e->getStatus());
65+
} else {
66+
$this->addWarning('Skipping testPrintFirewallRule - ' . self::$firewallRuleName
67+
. ' has already been removed.');
68+
}
69+
}
70+
}
71+
72+
/**
73+
* @depends testCreateFirewallRule
74+
*/
75+
public function testListFirewallRules()
76+
{
77+
/* Catch API failure to check if it's a 404. In such case most probably the policy enforcer
78+
removed our fire-wall rule before this test executed and we should ignore the response */
79+
try {
80+
$output = $this->runFunctionSnippet('list_firewall_rules', [
81+
'projectId' => self::$projectId
82+
]);
83+
$this->assertStringContainsString(self::$firewallRuleName, $output);
84+
$this->assertStringContainsString('Allowing TCP traffic on ports 80 and 443 from Internet.', $output);
85+
} catch (ApiException $e) {
86+
if ($e->getCode() != 404) {
87+
throw new ApiException($e->getMessage(), $e->getCode(), $e->getStatus());
88+
} else {
89+
$this->addWarning('Skipping testPrintFirewallRule - ' . self::$firewallRuleName
90+
. ' has already been removed.');
91+
}
92+
}
93+
}
94+
95+
/**
96+
* @depends testCreateFirewallRule
97+
*/
98+
public function testPatchFirewallPriority()
99+
{
100+
/* Catch API failure to check if it's a 404. In such case most probably the policy enforcer
101+
removed our fire-wall rule before this test executed and we should ignore the response */
102+
try {
103+
$output = $this->runFunctionSnippet('patch_firewall_priority', [
104+
'projectId' => self::$projectId,
105+
'firewallRuleName' => self::$firewallRuleName,
106+
'priority' => self::$priority
107+
]);
108+
$this->assertStringContainsString('Patched ' . self::$firewallRuleName . ' priority', $output);
109+
} catch (ApiException $e) {
110+
if ($e->getCode() != 404) {
111+
throw new ApiException($e->getMessage(), $e->getCode(), $e->getStatus());
112+
} else {
113+
$this->addWarning('Skipping testPrintFirewallRule - ' . self::$firewallRuleName
114+
. ' has already been removed.');
115+
}
116+
}
117+
}
118+
/**
119+
* @depends testPrintFirewallRule
120+
* @depends testListFirewallRules
121+
* @depends testPatchFirewallPriority
122+
*/
123+
public function testDeleteFirewallRule()
124+
{
125+
/* Catch API failure to check if it's a 404. In such case most probably the policy enforcer
126+
removed our fire-wall rule before this test executed and we should ignore the response */
127+
try {
128+
$output = $this->runFunctionSnippet('delete_firewall_rule', [
129+
'projectId' => self::$projectId,
130+
'firewallRuleName' => self::$firewallRuleName
131+
]);
132+
$this->assertStringContainsString('Rule ' . self::$firewallRuleName . ' deleted', $output);
133+
} catch (ApiException $e) {
134+
if ($e->getCode() != 404) {
135+
throw new ApiException($e->getMessage(), $e->getCode(), $e->getStatus());
136+
} else {
137+
$this->addWarning('Skipping testPrintFirewallRule - ' . self::$firewallRuleName
138+
. ' has already been removed.');
139+
}
140+
}
141+
}
142+
}

compute/cloud-client/instances/README.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
Google Cloud Compute PHP Instances Samples
2-
==========================================
1+
Google Cloud Compute Engine PHP Samples - Instances
2+
===================================================
33

44
[![Open in Cloud Shell][shell_img]][shell_link]
55

66
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.svg
77
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googlecloudplatform/php-docs-samples&page=editor&working_dir=compute/cloud-client/instances
88

9-
This directory contains samples for calling [Google Cloud Compute][compute]
9+
This directory contains samples for calling [Google Cloud Compute Engine][compute] APIs
1010
from PHP. Specifically, they show how to manage your Compute Engine [instances][instances].
1111

1212
[compute]: https://cloud.google.com/compute/docs/apis
@@ -26,7 +26,7 @@ authentication:
2626
gcloud auth application-default login
2727

2828
1. When running on App Engine or Compute Engine, credentials are already
29-
set-up. However, you may need to configure your Compute Engine instance
29+
set. However, you may need to configure your Compute Engine instance
3030
with [additional scopes][additional_scopes].
3131

3232
1. You can create a [Service Account key file][service_account_key_file]. This file can be used to
@@ -42,20 +42,20 @@ authentication:
4242

4343
## Install Dependencies
4444

45-
1. **Install dependencies** via [Composer](http://getcomposer.org/doc/00-intro.md).
45+
1. **Install dependencies** using [Composer](http://getcomposer.org/doc/00-intro.md).
4646
Run `php composer.phar install` (if composer is installed locally) or `composer install`
4747
(if composer is installed globally).
4848

49-
1. Create a service account at the
50-
[Service account section in the Cloud Console](https://console.cloud.google.com/iam-admin/serviceaccounts/)
49+
1. Create a [service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts#creating).
5150

52-
1. Download the json key file of the service account.
51+
1. [Download the json key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys#getting_a_service_account_key)
52+
of the service account.
5353

54-
1. Set `GOOGLE_APPLICATION_CREDENTIALS` environment variable pointing to that file.
54+
1. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable pointing to that file.
5555

5656
## Samples
5757

58-
To run the Compute Samples, run any of the files in `src/` on the CLI to print
58+
To run the Compute samples, run any of the files in `src/` on the CLI to print
5959
the usage instructions:
6060

6161
```

0 commit comments

Comments
 (0)