Skip to content

Commit

Permalink
new env scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
vmleon committed Jun 25, 2023
1 parent 7f954ae commit a04e42c
Show file tree
Hide file tree
Showing 12 changed files with 1,014 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# Icon must end with two \r
Icon

.env.json

# Thumbnails
._*
Expand Down Expand Up @@ -51,7 +52,6 @@ downloads/
generated/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
Expand Down
10 changes: 5 additions & 5 deletions dev/terraform/terraform.tfvars.template
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
config_file_profile = "DEFAULT"
region = "XXXXX"
tenancy_ocid = "XXXXX"
compartment_ocid = "XXXXX"
ssh_public_key = "XXXXX"
riotgames_api_key = "XXXXX" # https://developer.riotgames.com/
region = "REGION_NAME"
tenancy_ocid = "TENANCY_OCID"
compartment_ocid = "COMPARTMENT_OCID"
ssh_public_key = "SSH_PUBLIC_KEY"
riotgames_api_key = "RIOT_GAMES_API_KEY" # https://developer.riotgames.com/
252 changes: 252 additions & 0 deletions scripts/lib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
# OCI ZX Scripts

## Usage

From the root folder of your project, download the scripts folder:

```sh
wget -cO - \
https://github.com/vmleon/oci-zx-scripts/archive/refs/heads/main.zip > scripts.zip \
&& unzip scripts.zip -d scripts \
&& rm scripts.zip \
&& mv scripts/oci-zx-scripts-main scripts/lib
```

## Example

Create a `setenv.mjs` script to prepare environment:

```sh
touch scripts/setenv.mjs
```

Use the following example:
```js
#!/usr/bin/env zx

import { getNamespace } from "./lib/oci.mjs";
import { checkRequiredProgramsExist } from "./lib/utils.mjs";

const shell = process.env.SHELL | "/bin/zsh";
$.shell = shell;
$.verbose = false;

console.log("Check fake dependencies...");
const dependencies = ["git", "unzip"];
await checkRequiredProgramsExist(dependencies);

const namespace = await getNamespace();
console.log(namespace);
```

Run the script:

```sh
npx zx scripts/setenv.mjs
```

## Create new functions

```javascript
#!/usr/bin/env zx
import { exitWithError } from "./utils.mjs";

export async function example() {
try {
const { stdout, exitCode, stderr } = await $`pwd`;
if (exitCode !== 0) {
exitWithError(stderr);
}
return stdout.trim();
} catch (error) {
exitWithError(error.stderr);
}
}
```

## Get Region example

```javascript
const regions = await getRegions();
const regionName = await setVariableFromEnvOrPrompt(
"OCI_REGION",
"OCI Region name",
async () => printRegionNames(regions)
);
const { key } = regions.find((r) => r.name === regionName);
const url = `${key}.ocir.io`;
```

## Release Example

```javascript
#!/usr/bin/env zx
import {
getVersion,
getNamespace,
printRegionNames,
setVariableFromEnvOrPrompt,
} from "./lib/utils.mjs";
import { buildImage, tagImage, pushImage } from "./lib/container.mjs";
import { buildWeb } from "./lib/npm.mjs";
import {
buildJarGradle,
cleanGradle,
getVersionGradle,
} from "./lib/gradle.mjs";
import { getRegions } from "./lib/oci.mjs";

const shell = process.env.SHELL | "/bin/zsh";
$.shell = shell;
$.verbose = false;

const { a, _ } = argv;
const [action] = _;

const project = "project_name";
const namespace = await getNamespace();

const regions = await getRegions();
const regionName = await setVariableFromEnvOrPrompt(
"OCI_REGION",
"OCI Region name",
() => printRegionNames(regions)
);
const { key } = regions.find((r) => r.name === regionName);
const ocirUrl = `${key}.ocir.io`;

if (action === "web") {
await releaseNpm("web");
process.exit(0);
}

if (action === "backend") {
await releaseGradle("backend");
process.exit(0);
}

if (a || action === "all") {
await releaseNpm("web");
await releaseGradle("backend");
process.exit(0);
}

console.log("Usage:");
console.log("\tnpx zx scripts/release.mjs all");
console.log("\tnpx zx scripts/release.mjs -a");
console.log("\tnpx zx scripts/release.mjs web");
console.log("\tnpx zx scripts/release.mjs backend");

async function releaseNpm(service) {
await cd(service);
const currentVersion = await getVersion();
if (service === "web") {
await buildWeb();
}
const image_name = `${project}/${service}`;
await buildImage(`localhost/${image_name}`, currentVersion);
const local_image = `localhost/${image_name}:${currentVersion}`;
const remote_image = `${ocirUrl}/${namespace}/${image_name}:${currentVersion}`;
await tagImage(local_image, remote_image);
await pushImage(remote_image);
console.log(`Released: ${chalk.yellow(remote_image)}`);
await cd("..");
}
async function releaseGradle(service) {
await cd(service);
await cleanGradle();
await buildJarGradle();
const currentVersion = await getVersionGradle();
const image_name = `${project}/${service}`;
await buildImage(`localhost/${image_name}`, currentVersion);
const local_image = `localhost/${image_name}:${currentVersion}`;
const remote_image = `${ocirUrl}/${namespace}/${image_name}:${currentVersion}`;
await tagImage(local_image, remote_image);
await pushImage(remote_image);
console.log(`Released: ${chalk.yellow(remote_image)}`);
await cd("..");
}

```

## Create RSA

```javascript
#!/usr/bin/env zx

import {
getUserId,
uploadApiKeyFile,
} from "./lib/oci.mjs";
import { createRSAKeyPair } from "./lib/tls.mjs";

const shell = process.env.SHELL | "/bin/zsh";
$.shell = shell;
$.verbose = false;

async function createUserDetails() {
console.log("Generate RSA key pair...");

const userId = await getUserId();

properties = {
...properties,
userId,
};

const rsaPath = "./.rsa";
const prevKeyExists = await fs.pathExists(path.join(rsaPath, "rsa.pem"));
if (prevKeyExists) {
console.log(`${chalk.yellow("Existing RSA key pair ")} on ${rsaPath}.`);
} else {
await createRSAKeyPair(rsaPath);
const apikeyFingerprint = await uploadApiKeyFile(
userId,
path.join(rsaPath, "rsa_public.pem")
);
properties = { ...properties, rsaPath, apikeyFingerprint };
}
console.log();
}
```

## Use .env.json

```javascript
#!/usr/bin/env zx

import {
getNamespace,
writeEnvJson,
generateRandomString,
readEnvJson,
} from "./lib/utils.mjs";
import { getTenancyId } from "./lib/oci.mjs";

const shell = process.env.SHELL | "/bin/zsh";
$.shell = shell;
$.verbose = false;

let properties = await readEnvJson();

const namespace = await getNamespace();
const tenancyId = await getTenancyId();
properties = { ...properties, namespace, tenancyId };

const generatedPassword = await generateRandomString();
properties = { ...properties, generatedPassword };

await writeEnvJson(properties);
```

```javascript
#!/usr/bin/env zx

import { readEnvJson } from "./lib/utils.mjs";

const shell = process.env.SHELL | "/bin/zsh";
$.shell = shell;
$.verbose = false;

const { namespace } = await readEnvJson();
```
74 changes: 74 additions & 0 deletions scripts/lib/container.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/usr/bin/env zx
import { exitWithError } from "./utils.mjs";

export async function whichContainerEngine() {
try {
const dockerPath = await which("docker");
return !dockerPath ? "podman" : "docker";
} catch (err) {
return "podman";
}
}

const ce = await whichContainerEngine();

export async function checkPodmanMachineRunning() {
if (ce === "podman") {
const isMachineRunning = (
await $`podman machine info --format {{.Host.MachineState}}`
).stdout.trim();
if (isMachineRunning === "Stopped") {
console.log(
`Run ${chalk.yellow("podman machine start")} before continue`
);
exitWithError("Podman machine stopped");
} else {
console.log(`${chalk.green("[ok]")} podman machine running`);
}
}
}

export async function containerLogin(namespace, user, token, url) {
try {
const { stdout, stderr, exitCode } =
await $`${ce} login -u ${namespace}/${user} -p ${token} ${url}`;
if (exitCode == 0) {
console.log(`${chalk.yellow(url)}: ${chalk.green(stdout.trim())}`);
} else {
console.error(chalk.red(stderr.trim()));
}
} catch (error) {
console.error(chalk.red(error.stderr.trim()));
const yellowUserString = chalk.yellow(user);
exitWithError(
`Review the user ${yellowUserString} and token pair, and try again.`
);
}
}

export async function tagImage(local, remote) {
console.log(`${ce} tag ${local} ${remote}`);
try {
await $`${ce} tag ${local} ${remote}`;
} catch (error) {
exitWithError(error.stderr);
}
}

export async function pushImage(remote) {
console.log(`${ce} push ${remote}`);
try {
await $`${ce} push ${remote}`;
} catch (error) {
exitWithError(error.stderr);
}
}

export async function buildImage(name, version) {
console.log(`${ce} build . -t ${name}:${version}`);
try {
await $`${ce} build . -t ${name}:${version}`;
} catch (error) {
exitWithError(error.stderr);
}
}
Loading

0 comments on commit a04e42c

Please sign in to comment.