我在本地Windows机器中有aws凭证文件和配置文件。 使用下面的javascript代码,我可以从aws秘密管理器获取包含用户名和密码的秘密。但是问题是,我的代码通过cypress在浏览器中运行,并且无法从我的本地访问aws凭证文件。 ,我已经将我的AWS凭证信息硬编码了。
我的问题是,如何从本地访问aws凭证文件,以便摆脱硬编码令牌?请告知
\.aws\credentials
[default]
aws_access_key_id=<access key>
aws_secret_access_key= <secret key>
aws_session_token=<session token>
aws_expiration=<datetime>
awssecretmanager.ts:
const AWS = require('aws-sdk');
const region = 'eu-central-1';
const secretName = 'secretname of my application';
const secretManager = new AWS.SecretsManager({
region,
accessKeyId : 'qbxx1234556', //hardcoded
secretAccessKey : 'axyx124545', //hardcoded
sessionToken : 'x1234; //hardcoded
});
const getSecrets = async () => {
return await new Promise((resolve, reject) => {
secretManager.getSecretValue({ SecretId : secretName }, (err, result) => {
if (err) { reject(err); }
else { resolve(JSON.parse(result.SecretString)); }
});
});
};
const getSecret = async () => {
const secret = await getSecrets();
return secret; //secret contains username and password
};
export {getSecret};
如何从我的测试文件访问它? test.spec.ts
const secret = await getSecret();
if (secret !== undefined){
username = secret['username'];
password = secret['password'];
我尝试使用下面的代码,但由于浏览器无法访问本地凭据文件,因此无法正常工作
const credentials = new AWS.SharedIniFileCredentials({ profile: "default" });
AWS.config.credentials = credentials;
答案 0 :(得分:0)
拥有一种更简单的解决方法。
1。由于我们将“ Azure devops”用于CI,因此我们更容易通过Azure devops管道任务从AWS Secret Manager获得机密。 2.一旦掌握了秘密,我们就会设置环境变量,例如CYPRESS_USERNAME,CYPRESS_PASSWORD 3.在测试中,我们可以使用Cypress.env('USERNAME')和Cypress.env('PASSWORD')
引用环境变量步骤1和步骤2: 下面包含任务的azure-pipeline.yml文件
jobs:
- job: run_e2e_tests
steps:
- task: SecretsManagerGetSecret@1
displayName: Get AWS secrets
inputs:
awsCredentials: 'aws credentials'
regionName: 'eu-central-1'
secretIdOrName: 'secretname'
variableName: 'variable-containing-secrets'
- powershell: |
$variablecontainingsecrets ='$(variable-containing-secrets)' | ConvertFrom-Json
echo "##vso[task.setvariable variable=TestUsername;isOutput=true;issecret=true;]$($variablecontainingsecrets.'username')"
echo "##vso[task.setvariable variable=TestPassword;isOutput=true;issecret=true;]$($variablecontainingsecrets.'password')"
name: secrets
displayName: Set environment variables from secrets JSON
- task: PowerShell@2
displayName: 'Setup environment variables for Cypress tests'
inputs:
targetType: 'inline'
script: |
Write-Host "##vso[task.setvariable variable=CYPRESS_USERNAME;]$(secrets.TestUsername)"
Write-Host "About to set environment variable for username ($env:CYPRESS_USERNAME)"
Write-Host "##vso[task.setvariable variable=CYPRESS_PASSWORD;]$(secrets.TestPassword)"
Write-Host "About to set environment variable for password ($env:CYPRESS_PASSWORD)"
Step3: 在赛普拉斯测试中,我们像这样引用了env变量
cy.get('input#signInFormUsername').type(Cypress.env('USERNAME'));
请注意,如果您在本地运行它,则可能需要设置环境变量。例如,我需要设置CYPRESS_USERNAME=username
之类的环境变量,
CYPRESS_PASSWORD=password