Last active
October 11, 2023 06:17
-
-
Save rdlabo/0f5b91ebcd02ad6171d102447668f3bb to your computer and use it in GitHub Desktop.
Which Instance is main on Elastic Beanstalk ( NestJS )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class AwsService { | |
public async isMainInstance(): Promise<boolean> { | |
/* | |
* インスタンスメタデータを取得するための手続き。IMDSv2で実装。 | |
* https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html | |
*/ | |
const token = await firstValueFrom( | |
this.http | |
.put( | |
'http://169.254.169.254/latest/api/token', | |
{}, | |
{ | |
headers: { | |
'X-aws-ec2-metadata-token-ttl-seconds': '21600', | |
}, | |
}, | |
) | |
.pipe(map((d) => d.data)), | |
).catch((e) => console.log(e)); | |
if (token === undefined) { | |
console.error('AWS EC2以外での実行のため結果を得ることができません'); | |
return false; | |
} | |
// 実行中のInstanceIdを取得 | |
const instanceId = await firstValueFrom( | |
this.http | |
.get('http://169.254.169.254/latest/meta-data/instance-id', { | |
headers: { | |
'X-aws-ec2-metadata-token': token, | |
}, | |
}) | |
.pipe(map((d) => d.data)), | |
); | |
const input = { | |
EnvironmentName: 'tipsys-api-v8', // 自分のプロジェクトのEnvironmentNameで | |
}; | |
const command = new DescribeEnvironmentResourcesCommand(input); | |
const response = await this.ebClient.send(command); | |
if (response.$metadata.httpStatusCode !== 200) { | |
throw new Error('ebClientのhttpStatusCodeが' + response.$metadata.httpStatusCode); | |
} | |
return response.EnvironmentResources.Instances[0].Id === instanceId; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment