-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaws-profile.ts
More file actions
204 lines (168 loc) · 7.2 KB
/
aws-profile.ts
File metadata and controls
204 lines (168 loc) · 7.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import {
CreatePlan,
DestroyPlan,
getPty,
ModifyPlan,
ParameterChange,
Resource,
ResourceSettings
} from 'codify-plugin-lib';
import { StringIndexedObject } from 'codify-schemas';
import * as fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SpawnStatus, codifySpawn } from '../../../utils/codify-spawn.js';
import Schema from './aws-profile-schema.json'
import { CSVCredentialsTransformation } from './csv-credentials-transformation.js';
export interface AwsProfileConfig extends StringIndexedObject {
awsAccessKeyId: string;
awsSecretAccessKey: string;
csvCredentials: string,
metadataServiceNumAttempts?: number;
metadataServiceTimeout?: number;
output?: string;
profile: string;
region: string;
}
export class AwsProfileResource extends Resource<AwsProfileConfig> {
getSettings(): ResourceSettings<AwsProfileConfig> {
return {
id: 'aws-profile',
dependencies: ['aws-cli'],
schema: Schema,
parameterSettings: {
awsAccessKeyId: { canModify: true },
awsSecretAccessKey: { canModify: true, isSensitive: true },
csvCredentials: { type: 'directory', setting: true }, // Type setting means it won't be included in the plan calculation
output: { default: 'json', canModify: true },
profile: { default: 'default', canModify: true },
metadataServiceNumAttempts: { canModify: true, setting: true },
metadataServiceTimeout: { canModify: true, setting: true },
},
transformation: CSVCredentialsTransformation,
importAndDestroy:{
requiredParameters: ['profile']
},
allowMultiple: {
identifyingParameters: ['profile'],
findAllParameters: async () => {
const $ = getPty();
const { status } = await $.spawnSafe('which aws');
if (status === 'error') {
return [];
}
const { data } = await $.spawnSafe('aws configure list-profiles')
return data
?.split(/\n/)
?.filter(Boolean)
?.map((profile) => ({ profile }))
?? [];
}
}
};
}
override async validate(parameters: Partial<AwsProfileConfig>): Promise<void> {
// if (parameters.csvCredentials
// && (parameters.awsAccessKeyId || parameters.awsSecretAccessKey)) {
// throw new Error('Csv credentials cannot be added together with awsAccessKeyId or awsSecretAccessKey')
// }
}
override async refresh(parameters: Partial<AwsProfileConfig>): Promise<Partial<AwsProfileConfig> | null> {
const $ = getPty();
const profile = parameters.profile!;
// Make sure aws-cli is installed
const { status: awsStatus } = await $.spawnSafe('which aws');
if (awsStatus === SpawnStatus.ERROR) {
return null;
}
// Check if the profile exists
const { data: profiles } = await $.spawn('aws configure list-profiles');
if (!profiles.includes(profile)) {
return null;
}
const awsAccessKeyId = await this.getAwsConfigureValueOrNull('aws_access_key_id', profile);
const awsSecretAccessKey = await this.getAwsConfigureValueOrNull('aws_secret_access_key', profile);
const result: Partial<AwsProfileConfig> = {
awsAccessKeyId: awsAccessKeyId ?? undefined,
awsSecretAccessKey: awsSecretAccessKey ?? undefined,
profile,
};
if (parameters.region !== undefined) {
result.region = await this.getAwsConfigureValueOrNull('region', profile);
}
if (parameters.output !== undefined) {
result.output = await this.getAwsConfigureValueOrNull('output', profile);
}
if (parameters.metadataServiceTimeout) {
const metadataServiceTimeout = await this.getAwsConfigureValueOrNull('metadata_service_timeout', profile);
if (metadataServiceTimeout) {
result.metadataServiceTimeout = Number.parseInt(metadataServiceTimeout, 10);
}
}
if (parameters.metadataServiceNumAttempts) {
const metadataServiceNumAttempts = await this.getAwsConfigureValueOrNull('metadata_service_num_attempts', profile);
if (metadataServiceNumAttempts) {
result.metadataServiceNumAttempts = Number.parseInt(metadataServiceNumAttempts, 10);
}
}
return result;
}
override async create(plan: CreatePlan<AwsProfileConfig>): Promise<void> {
// Assert that aws-cli is installed
await codifySpawn('which aws')
const {
awsAccessKeyId,
awsSecretAccessKey,
metadataServiceNumAttempts,
metadataServiceTimeout,
output,
profile,
region
} = plan.desiredConfig;
await this.setAwsConfigureValue('aws_access_key_id', awsAccessKeyId, profile);
await this.setAwsConfigureValue('aws_secret_access_key', awsSecretAccessKey, profile);
await this.setAwsConfigureValue('region', region, profile);
await this.setAwsConfigureValue('output', output!, profile);
if (metadataServiceTimeout) {
await this.setAwsConfigureValue('metadata_service_timeout', metadataServiceTimeout, profile);
}
if (metadataServiceNumAttempts) {
await this.setAwsConfigureValue('metadata_service_num_attempts', metadataServiceNumAttempts, profile);
}
}
override async modify(
pc: ParameterChange<AwsProfileConfig>,
plan: ModifyPlan<AwsProfileConfig>
): Promise<void> {
await this.setAwsConfigureValue(pc.name, pc.newValue, plan.desiredConfig.profile);
}
override async destroy(plan: DestroyPlan<AwsProfileConfig>): Promise<void> {
const { profile } = plan.currentConfig;
const credentialsPath = path.resolve(os.homedir(), '.aws', 'credentials');
const credentialsFile = await fs.readFile(credentialsPath, 'utf8');
// Split using header [PROFILE_NAME]. Using a negative lookup so header remains after split
const credentialsBlocks = credentialsFile.split(/(?=\[.*\])/)
const credentialsPrefilterLength = credentialsBlocks.length;
const filteredCredentialsBlocks = credentialsBlocks.filter((b) => b.includes(`[${profile}])`))
if (filteredCredentialsBlocks.length === credentialsPrefilterLength) {
throw new Error(`Unable to find profile ${profile} in .aws/credentials. Please remove the profile and re-run Codify`);
}
await fs.writeFile(credentialsPath, filteredCredentialsBlocks.join('\n'), 'utf8');
const configPath = path.resolve(os.homedir(), '.aws', 'config');
const configFile = await fs.readFile(configPath, 'utf8');
const configBlocks = configFile.split(/(?=\[.*\])/) // Split using header [PROFILE_NAME]. Using a negative lookup so header remains after split
const filteredConfigBlocks = configBlocks.filter((b) => b.includes(`[profile ${profile}])`) || b.includes(`[${profile}]`))
await fs.writeFile(configPath, filteredConfigBlocks.join('\n'), 'utf8');
}
private async getAwsConfigureValueOrNull(key: string, profile: string): Promise<string | undefined> {
const $ = getPty();
const { data, status } = await $.spawnSafe(`aws configure get ${key} --profile ${profile}`);
if (status === SpawnStatus.ERROR) {
return undefined;
}
return data.trim();
}
private async setAwsConfigureValue(key: string, value: number | string, profile: string): Promise<void> {
await codifySpawn(`aws configure set ${key} ${value} --profile ${profile}`);
}
}