Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Implemented State and outputs #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 40 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,50 @@ Terraform cloud scripts
### Usage:

```shell
terraform-cloud <resource> <action> [arguments]
terraform-cloud <command> <sucommand> [arguments]
```
OR
```shell
tfc <resource> <action> [arguments]
tfc <command> <sucommand> [arguments]
```
### Available Allowed Resources:
### Available Commands and Subcommands:
- `workspace`
- `get` - Prints the provided workspace as output

Example:
```shell
$ tfc workspace get orgnization/workspace
```
- `list` - List all workspaces in Organization.

Note: In case of missing organization name, Throws an error and outputs all available organizations in the account.

Example:
```shell
$ tfc workspace list

Error: Organization Missing
Please pass organization from list below:
- OrgA
- OrgB


Terraform Cloud - Devops Scripts

Github: https://github.com/phenixcoder/devops-scripts

Usage:
terraform-cloud <resource> <action> [arguments]
OR
tfc <resource> <action> [arguments]

```
OR
```shell
$ tfc workspace list orgnization
```
- `output`
- `get` - Get the first output from latest state and prints as output
- `list` - Lista all output in the state.
- `state`

### Available Allowed Actions:
- `get`
- `set`
- `list`

---
- `get` - Get the latest state and prints as output
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
}
},
"dependencies": {
"command-line-args": "^5.2.0",
"follow-redirects": "^1.14.1"
}
}
54 changes: 39 additions & 15 deletions scripts/shared/environment.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,48 @@
const { existsSync, readFileSync } = require('fs');
const path = require('path');

const currentEnv = {
TFCRC_PATH: undefined,
config: undefined
}
const Environment = (render) => {
const env = {
// args: process.argv,
paths: {
pwd: process.env.PWD,
home: process.env.HOME,
},
secrets: {
TFC_TOKEN: process.env.TFC_TOKEN,
TFC_WORKSPACE: process.env.TFC_WORKSPACE,
},
action: process.argv[3] || '',
resource: process.argv[2] || '',
args: process.argv.slice(4)
if (!currentEnv.config) {
const TFCRC_PATH = path.join(process.env.PWD, '.tfcrc');
const TFC_CONFIG = {};
if (existsSync(TFCRC_PATH)) {
currentEnv.TFCRC_PATH = TFCRC_PATH;

readFileSync(TFCRC_PATH, { encoding: 'utf-8' })
.split('\n').forEach(line => {
const [key, value] = line.split('=');
if(key && value) {
TFC_CONFIG[key] = value;
}
});
}

currentEnv.config = {
// args: process.argv,
paths: {
pwd: process.env.PWD,
home: process.env.HOME,
},
secrets: {
TFC_TOKEN: process.env.TFC_TOKEN || TFC_CONFIG.TFC_TOKEN,
TFC_WORKSPACE: process.env.TFC_WORKSPACE || TFC_CONFIG.TFC_WORKSPACE || TFC_CONFIG.WORKSPACE_ID,
},
action: process.argv[3] || '',
resource: process.argv[2] || '',
args: process.argv.slice(4)
}
}

if (render) {
console.log('Envrionment');
console.log(env);
console.log(currentEnv.config);
}

return env;
return currentEnv.config;
}

module.exports = Environment;
1 change: 1 addition & 0 deletions scripts/terraform/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ if (
console.log(JSON.stringify(value, null, ' '));
}
}).catch(err => {
// console.log(err);
Help(err);
});
}
Expand Down
1 change: 1 addition & 0 deletions scripts/terraform/help.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
function Help(errorMessage) {
if (errorMessage) {
console.error(`Error: ${errorMessage}`);
// console.trace()
}

console.log(`
Expand Down
27 changes: 21 additions & 6 deletions scripts/terraform/resources/output.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,44 @@ const Request = require("../../shared/request");
const Help = require("../help");

const OUTPUT = {
list: async (...args) => {
const env = Environment();
if (!env.secrets.TFC_TOKEN) {
Help('Missing TFC_TOKEN.');
}
if (!env.secrets.TFC_WORKSPACE) {
Help('Missing TFC_WORKSPACE.');
}
const state = await Request('app.terraform.io', 'GET', `/api/v2/workspaces/${env.secrets.TFC_WORKSPACE}/current-state-version`, {
'Authorization': `Bearer ${env.secrets.TFC_TOKEN}`
});
const stateJSON = JSON.parse(state);
stateJSON.data.relationships.outputs.data.forEach((output, i) => {
console.log(i, output.id);
});
},
get: async (...args) => {
const env = Environment();
if (env.secrets.TFC_TOKEN) {
if (!env.secrets.TFC_TOKEN) {
Help('Missing TFC_TOKEN.');
}
if (env.secrets.TFC_WORKSPACE) {
if (!env.secrets.TFC_WORKSPACE) {
Help('Missing TFC_WORKSPACE.');
}
const state = await Request('app.terraform.io', 'GET', `/api/v2/workspaces/${env.secrets.TFC_WORKSPACE}/current-state-version`, {
'Authorization': `Bearer ${env.secrets.TFC_TOKEN}`
});

console.log(state);

const output_id = JSON.parse(state).data.relationships.outputs.data[0].id;

let outputs = await Request('app.terraform.io', 'GET', `/api/v2/state-version-outputs/${output_id}`, {
'Authorization': `Bearer ${env.secrets.TFC_TOKEN}`
});

outputs = JSON.parse(outputs).data.attributes.value;

console.log(outputs.byString(env.args[0] || ''));
// console.log(outputs.byString(env.args[0] || ''));
console.log(JSON.stringify(outputs, null, ' '));

},
}
Expand Down
26 changes: 24 additions & 2 deletions scripts/terraform/resources/state.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
const Environment = require("../../shared/environment");
const Request = require("../../shared/request");
const Help = require("../help");
const URL = require('url');
const { writeFileSync, existsSync } = require("fs");

const OUTPUT = {
get: () => {
throw "not implimented";
get: async (...args) => {
const env = Environment();
if (!env.secrets.TFC_TOKEN) {
Help('Missing TFC_TOKEN.');
}
if (!env.secrets.TFC_WORKSPACE) {
Help('Missing TFC_WORKSPACE.');
}
const response = await Request('app.terraform.io', 'GET', `/api/v2/workspaces/${env.secrets.TFC_WORKSPACE}/current-state-version`, {
'Authorization': `Bearer ${env.secrets.TFC_TOKEN}`
});

const stateURL = URL.parse(JSON.parse(response).data.attributes['hosted-state-download-url']);
const stateResponse = await Request(stateURL.hostname, 'GET', stateURL.path, {
'Authorization': `Bearer ${env.secrets.TFC_TOKEN}`
});

console.log(stateResponse)
},

set: () => {
Expand Down
13 changes: 12 additions & 1 deletion scripts/terraform/resources/workspace.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,16 @@ const WORKSPACE = {

list: async (args, returnOnly) => {
if (!args[0]) {
throw 'Organisation Missing'
let responseOrgs = await Request('app.terraform.io', 'GET', `/api/v2/organizations/`, {
'Authorization': `Bearer ${Environment().secrets.TFC_TOKEN}`
});
let errorString = 'Organization Missing\nPlease pass organization from list below:\n';
JSON.parse(responseOrgs).data.forEach(org => {
errorString += ` - ${org.id}\n`
})
throw errorString;
}

const org = args[0];

let response = await Request('app.terraform.io', 'GET', `/api/v2/organizations/${org}/workspaces`, {
Expand All @@ -29,6 +37,9 @@ const WORKSPACE = {
response = JSON.parse(response);
if (response.errors) {
response.errors.forEach(error => {
if (error.status == 404) {
throw `Organization ${org} not found.`
}
console.log(`error: [${error.status}] ${error.title}`);
});
throw "";
Expand Down