JavaScript (v3) 용 SDK를 사용한 IAM 예제 - AWS SDK 코드 예제

AWS문서 AWS SDK 예제 리포지토리에 더 많은 SDK 예제가 있습니다. GitHub

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

JavaScript (v3) 용 SDK를 사용한 IAM 예제

다음 코드 예제에서는 IAM에서 AWS SDK for JavaScript(v3)를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 호출하는 방법을 보여주며 관련 시나리오와 크로스 서비스 예제에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예시입니다.

각 예제에는 상황에 GitHub 맞게 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 링크가 포함되어 있습니다.

시작하기

다음 코드 예제에서는 IAM을 사용하여 시작하는 방법을 보여 줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { IAMClient, paginateListPolicies } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const listLocalPolicies = async () => { /** * In v3, the clients expose paginateOperationName APIs that are written using async generators so that you can use async iterators in a for await..of loop. * https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators */ const paginator = paginateListPolicies( { client, pageSize: 10 }, // List only customer managed policies. { Scope: "Local" }, ); console.log("IAM policies defined in your account:"); let policyCount = 0; for await (const page of paginator) { if (page.Policies) { page.Policies.forEach((p) => { console.log(`${p.PolicyName}`); policyCount++; }); } } console.log(`Found ${policyCount} policies.`); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI ListPolicies참조를 참조하십시오.

작업

다음 코드 예제에서는 IAM 정책을 역할에 연결하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 연결합니다.

import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn * @param {string} roleName */ export const attachRolePolicy = (policyArn, roleName) => { const command = new AttachRolePolicyCommand({ PolicyArn: policyArn, RoleName: roleName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var paramsRoleList = { RoleName: process.argv[2], }; iam.listAttachedRolePolicies(paramsRoleList, function (err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { console.log( "AmazonDynamoDBFullAccess is already attached to this role." ); process.exit(); } }); var params = { PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", RoleName: process.argv[2], }; iam.attachRolePolicy(params, function (err, data) { if (err) { console.log("Unable to attach policy to role", err); } else { console.log("Role attached successfully"); } }); } });

다음 코드 예제에서는 인라인 정책을 IAM 역할에 연결하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { PutRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const examplePolicyDocument = JSON.stringify({ Version: "2012-10-17", Statement: [ { Sid: "VisualEditor0", Effect: "Allow", Action: [ "s3:ListBucketMultipartUploads", "s3:ListBucketVersions", "s3:ListBucket", "s3:ListMultipartUploadParts", ], Resource: "arn:aws:s3:::some-test-bucket", }, { Sid: "VisualEditor1", Effect: "Allow", Action: [ "s3:ListStorageLensConfigurations", "s3:ListAccessPointsForObjectLambda", "s3:ListAllMyBuckets", "s3:ListAccessPoints", "s3:ListJobs", "s3:ListMultiRegionAccessPoints", ], Resource: "*", }, ], }); const client = new IAMClient({}); /** * * @param {string} roleName * @param {string} policyName * @param {string} policyDocument */ export const putRolePolicy = async (roleName, policyName, policyDocument) => { const command = new PutRolePolicyCommand({ RoleName: roleName, PolicyName: policyName, PolicyDocument: policyDocument, }); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScriptAPI PutRolePolicy참조를 참조하십시오.

다음 코드 예제에서는 AWS Identity and Access Management (IAM) SAML 공급자를 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { CreateSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam"; import { readFileSync } from "fs"; import * as path from "path"; import { dirnameFromMetaUrl } from "@aws-sdk-examples/libs/utils/util-fs.js"; const client = new IAMClient({}); /** * This sample document was generated using Auth0. * For more information on generating this document, see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html#samlstep1. */ const sampleMetadataDocument = readFileSync( path.join( dirnameFromMetaUrl(import.meta.url), "../../../../resources/sample_files/sample_saml_metadata.xml", ), ); /** * * @param {*} providerName * @returns */ export const createSAMLProvider = async (providerName) => { const command = new CreateSAMLProviderCommand({ Name: providerName, SAMLMetadataDocument: sampleMetadataDocument.toString(), }); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScript API 참조CreateSAMLProvider를 참조하십시오.

다음 코드 예제에서는 IAM 그룹을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { CreateGroupCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} groupName */ export const createGroup = async (groupName) => { const command = new CreateGroupCommand({ GroupName: groupName }); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScriptAPI CreateGroup참조를 참조하십시오.

다음 코드 예제에서는 IAM 정책을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 생성합니다.

import { CreatePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyName */ export const createPolicy = (policyName) => { const command = new CreatePolicyCommand({ PolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: "*", Resource: "*", }, ], }), PolicyName: policyName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var myManagedPolicy = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: "logs:CreateLogGroup", Resource: "RESOURCE_ARN", }, { Effect: "Allow", Action: [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:UpdateItem", ], Resource: "RESOURCE_ARN", }, ], }; var params = { PolicyDocument: JSON.stringify(myManagedPolicy), PolicyName: "myDynamoDBPolicy", }; iam.createPolicy(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 역할을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할을 생성합니다.

import { CreateRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const createRole = (roleName) => { const command = new CreateRoleCommand({ AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "lambda.amazonaws.com", }, Action: "sts:AssumeRole", }, ], }), RoleName: roleName, }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI CreateRole참조를 참조하십시오.

다음 코드 예제에서는 IAM 서비스 연결 역할을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

서비스 연결 역할을 생성합니다.

import { CreateServiceLinkedRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} serviceName */ export const createServiceLinkedRole = async (serviceName) => { const command = new CreateServiceLinkedRoleCommand({ // For a list of AWS services that support service-linked roles, // see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html. // // For a list of AWS service endpoints, see https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html. AWSServiceName: serviceName, }); const response = await client.send(command); console.log(response); return response; };

다음 코드 예제에서는 IAM 사용자를 생성하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

사용자를 생성합니다.

import { CreateUserCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} name */ export const createUser = (name) => { const command = new CreateUserCommand({ UserName: name }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { UserName: process.argv[2], }; iam.getUser(params, function (err, data) { if (err && err.code === "NoSuchEntity") { iam.createUser(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } else { console.log( "User " + process.argv[2] + " already exists", data.User.UserId ); } });

다음 코드 예제에서는 IAM 액세스 키를 생성하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

액세스 키를 생성합니다.

import { CreateAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} userName */ export const createAccessKey = (userName) => { const command = new CreateAccessKeyCommand({ UserName: userName }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.createAccessKey({ UserName: "IAM_USER_NAME" }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKey); } });

다음 코드 예제에서는 IAM 계정의 별칭을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

계정 별칭을 생성합니다.

import { CreateAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} alias - A unique name for the account alias. * @returns */ export const createAccountAlias = (alias) => { const command = new CreateAccountAliasCommand({ AccountAlias: alias, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.createAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 인스턴스 프로파일을 생성하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

const { InstanceProfile } = await iamClient.send( new CreateInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, }), ); await waitUntilInstanceProfileExists( { client: iamClient }, { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName }, );

다음 코드 예제에서는 AWS Identity and Access Management (IAM) SAML 공급자를 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { DeleteSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} providerArn * @returns */ export const deleteSAMLProvider = async (providerArn) => { const command = new DeleteSAMLProviderCommand({ SAMLProviderArn: providerArn, }); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScript API 참조DeleteSAMLProvider를 참조하십시오.

다음 코드 예제에서는 IAM 그룹을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { DeleteGroupCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} groupName */ export const deleteGroup = async (groupName) => { const command = new DeleteGroupCommand({ GroupName: groupName, }); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScriptAPI DeleteGroup참조를 참조하십시오.

다음 코드 예제에서는 IAM 정책을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 삭제합니다.

import { DeletePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn */ export const deletePolicy = (policyArn) => { const command = new DeletePolicyCommand({ PolicyArn: policyArn }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI DeletePolicy참조를 참조하십시오.

다음 코드 예제에서는 IAM 역할을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할을 삭제합니다.

import { DeleteRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const deleteRole = (roleName) => { const command = new DeleteRoleCommand({ RoleName: roleName }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI DeleteRole참조를 참조하십시오.

다음 코드 예제에서는 IAM 역할 정책을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { DeleteRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName * @param {string} policyName */ export const deleteRolePolicy = (roleName, policyName) => { const command = new DeleteRolePolicyCommand({ RoleName: roleName, PolicyName: policyName, }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI DeleteRolePolicy참조를 참조하십시오.

다음 코드 예제에서는 IAM 서버 인증서를 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

서버 인증서를 삭제합니다.

import { DeleteServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} certName */ export const deleteServerCertificate = (certName) => { const command = new DeleteServerCertificateCommand({ ServerCertificateName: certName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.deleteServerCertificate( { ServerCertificateName: "CERTIFICATE_NAME" }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } } );

다음 코드 예제에서는 IAM 서비스 연결 역할을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { DeleteServiceLinkedRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const deleteServiceLinkedRole = (roleName) => { const command = new DeleteServiceLinkedRoleCommand({ RoleName: roleName }); return client.send(command); };

다음 코드 예제에서는 IAM 사용자를 삭제하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

사용자를 삭제합니다.

import { DeleteUserCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} name */ export const deleteUser = (name) => { const command = new DeleteUserCommand({ UserName: name }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { UserName: process.argv[2], }; iam.getUser(params, function (err, data) { if (err && err.code === "NoSuchEntity") { console.log("User " + process.argv[2] + " does not exist."); } else { iam.deleteUser(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } });

다음 코드 예제에서는 IAM 액세스 키를 삭제하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

액세스 키를 삭제합니다.

import { DeleteAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} userName * @param {string} accessKeyId */ export const deleteAccessKey = (userName, accessKeyId) => { const command = new DeleteAccessKeyCommand({ AccessKeyId: accessKeyId, UserName: userName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { AccessKeyId: "ACCESS_KEY_ID", UserName: "USER_NAME", }; iam.deleteAccessKey(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 계정 별칭을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

계정 별칭을 삭제합니다.

import { DeleteAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} alias */ export const deleteAccountAlias = (alias) => { const command = new DeleteAccountAliasCommand({ AccountAlias: alias }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.deleteAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 인스턴스 프로파일을 삭제하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

const client = new IAMClient({}); await client.send( new DeleteInstanceProfileCommand({ InstanceProfileName: NAMES.instanceProfileName, }), );

다음 코드 예제에서는 역할에서 IAM 정책을 분리하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

태그를 분리합니다.

import { DetachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn * @param {string} roleName */ export const detachRolePolicy = (policyArn, roleName) => { const command = new DetachRolePolicyCommand({ PolicyArn: policyArn, RoleName: roleName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var paramsRoleList = { RoleName: process.argv[2], }; iam.listAttachedRolePolicies(paramsRoleList, function (err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { var params = { PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", RoleName: process.argv[2], }; iam.detachRolePolicy(params, function (err, data) { if (err) { console.log("Unable to detach policy from role", err); } else { console.log("Policy detached from role successfully"); process.exit(); } }); } }); } });

다음 코드 예제에서는 IAM 정책을 가져오는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 가져옵니다.

import { GetPolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn */ export const getPolicy = (policyArn) => { const command = new GetPolicyCommand({ PolicyArn: policyArn, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute", }; iam.getPolicy(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Policy.Description); } });

다음 코드 예제에서는 IAM 역할을 가져오는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할을 가져옵니다.

import { GetRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const getRole = (roleName) => { const command = new GetRoleCommand({ RoleName: roleName, }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI GetRole참조를 참조하십시오.

다음 코드 예제에서는 IAM 서버 인증서를 가져오는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

서버 인증서를 가져옵니다.

import { GetServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} certName * @returns */ export const getServerCertificate = async (certName) => { const command = new GetServerCertificateCommand({ ServerCertificateName: certName, }); const response = await client.send(command); console.log(response); return response; };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.getServerCertificate( { ServerCertificateName: "CERTIFICATE_NAME" }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } } );

다음 코드 예제에서는 AWS Identity and Access Management (IAM) 서비스 연결 역할의 삭제 상태를 확인하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { GetServiceLinkedRoleDeletionStatusCommand, IAMClient, } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} deletionTaskId */ export const getServiceLinkedRoleDeletionStatus = (deletionTaskId) => { const command = new GetServiceLinkedRoleDeletionStatusCommand({ DeletionTaskId: deletionTaskId, }); return client.send(command); };

다음 코드 예제에서는 IAM 액세스 키의 마지막 사용에 관한 데이터를 가져오는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

액세스 키를 가져옵니다.

import { GetAccessKeyLastUsedCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} accessKeyId */ export const getAccessKeyLastUsed = async (accessKeyId) => { const command = new GetAccessKeyLastUsedCommand({ AccessKeyId: accessKeyId, }); const response = await client.send(command); if (response.AccessKeyLastUsed?.LastUsedDate) { console.log(` ${accessKeyId} was last used by ${response.UserName} via the ${response.AccessKeyLastUsed.ServiceName} service on ${response.AccessKeyLastUsed.LastUsedDate.toISOString()} `); } return response; };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.getAccessKeyLastUsed( { AccessKeyId: "ACCESS_KEY_ID" }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKeyLastUsed); } } );

다음 코드 예제에서는 IAM 계정 암호 정책을 가져오는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

계정 암호 정책을 가져옵니다.

import { GetAccountPasswordPolicyCommand, IAMClient, } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const getAccountPasswordPolicy = async () => { const command = new GetAccountPasswordPolicyCommand({}); const response = await client.send(command); console.log(response.PasswordPolicy); return response; };

다음 코드 예제에서는 IAM에 대한 SAML 공급자를 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

SAML 공급자를 나열합니다.

import { ListSAMLProvidersCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const listSamlProviders = async () => { const command = new ListSAMLProvidersCommand({}); const response = await client.send(command); console.log(response); return response; };
  • API 세부 정보는 AWS SDK for JavaScript API 참조ListSAMLProviders를 참조하십시오.

다음 코드 예제에서는 사용자의 IAM 액세스 키를 나열하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

액세스 키를 나열합니다.

import { ListAccessKeysCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * * @param {string} userName */ export async function* listAccessKeys(userName) { const command = new ListAccessKeysCommand({ MaxItems: 5, UserName: userName, }); /** * @type {import("@aws-sdk/client-iam").ListAccessKeysCommandOutput | undefined} */ let response = await client.send(command); while (response?.AccessKeyMetadata?.length) { for (const key of response.AccessKeyMetadata) { yield key; } if (response.IsTruncated) { response = await client.send( new ListAccessKeysCommand({ Marker: response.Marker, }), ); } else { break; } } }
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { MaxItems: 5, UserName: "IAM_USER_NAME", }; iam.listAccessKeys(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 계정 별칭을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

계정 별칭을 나열합니다.

import { ListAccountAliasesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. */ export async function* listAccountAliases() { const command = new ListAccountAliasesCommand({ MaxItems: 5 }); let response = await client.send(command); while (response.AccountAliases?.length) { for (const alias of response.AccountAliases) { yield alias; } if (response.IsTruncated) { response = await client.send( new ListAccountAliasesCommand({ Marker: response.Marker, MaxItems: 5, }), ); } else { break; } } }
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.listAccountAliases({ MaxItems: 10 }, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 그룹을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

그룹을 나열합니다.

import { ListGroupsCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. */ export async function* listGroups() { const command = new ListGroupsCommand({ MaxItems: 10, }); let response = await client.send(command); while (response.Groups?.length) { for (const group of response.Groups) { yield group; } if (response.IsTruncated) { response = await client.send( new ListGroupsCommand({ Marker: response.Marker, MaxItems: 10, }), ); } else { break; } } }
  • API 세부 정보는 AWS SDK for JavaScriptAPI ListGroups참조를 참조하십시오.

다음 코드 예제에서는 IAM 역할에 대한 인라인 정책을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 나열합니다.

import { ListRolePoliciesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * * @param {string} roleName */ export async function* listRolePolicies(roleName) { const command = new ListRolePoliciesCommand({ RoleName: roleName, MaxItems: 10, }); let response = await client.send(command); while (response.PolicyNames?.length) { for (const policyName of response.PolicyNames) { yield policyName; } if (response.IsTruncated) { response = await client.send( new ListRolePoliciesCommand({ RoleName: roleName, MaxItems: 10, Marker: response.Marker, }), ); } else { break; } } }
  • API 세부 정보는 AWS SDK for JavaScriptAPI ListRolePolicies참조를 참조하십시오.

다음 코드 예제에서는 IAM 정책을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

정책을 나열합니다.

import { ListPoliciesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * */ export async function* listPolicies() { const command = new ListPoliciesCommand({ MaxItems: 10, OnlyAttached: false, // List only the customer managed policies in your Amazon Web Services account. Scope: "Local", }); let response = await client.send(command); while (response.Policies?.length) { for (const policy of response.Policies) { yield policy; } if (response.IsTruncated) { response = await client.send( new ListPoliciesCommand({ Marker: response.Marker, MaxItems: 10, OnlyAttached: false, Scope: "Local", }), ); } else { break; } } }
  • API 세부 정보는 AWS SDK for JavaScriptAPI ListPolicies참조를 참조하십시오.

다음 코드 예제에서는 IAM 역할에 연결된 정책을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할에 연결된 정책을 나열합니다.

import { ListAttachedRolePoliciesCommand, IAMClient, } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * @param {string} roleName */ export async function* listAttachedRolePolicies(roleName) { const command = new ListAttachedRolePoliciesCommand({ RoleName: roleName, }); let response = await client.send(command); while (response.AttachedPolicies?.length) { for (const policy of response.AttachedPolicies) { yield policy; } if (response.IsTruncated) { response = await client.send( new ListAttachedRolePoliciesCommand({ RoleName: roleName, Marker: response.Marker, }), ); } else { break; } } }

다음 코드 예제에서는 IAM 역할을 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할을 나열합니다.

import { ListRolesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * */ export async function* listRoles() { const command = new ListRolesCommand({ MaxItems: 10, }); /** * @type {import("@aws-sdk/client-iam").ListRolesCommandOutput | undefined} */ let response = await client.send(command); while (response?.Roles?.length) { for (const role of response.Roles) { yield role; } if (response.IsTruncated) { response = await client.send( new ListRolesCommand({ Marker: response.Marker, }), ); } else { break; } } }
  • API 세부 정보는 AWS SDK for JavaScriptAPI ListRoles참조를 참조하십시오.

다음 코드 예제에서는 IAM 서버 인증서를 나열하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

인증서를 나열합니다.

import { ListServerCertificatesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * */ export async function* listServerCertificates() { const command = new ListServerCertificatesCommand({}); let response = await client.send(command); while (response.ServerCertificateMetadataList?.length) { for await (const cert of response.ServerCertificateMetadataList) { yield cert; } if (response.IsTruncated) { response = await client.send(new ListServerCertificatesCommand({})); } else { break; } } }
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); iam.listServerCertificates({}, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 사용자를 나열하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

사용자를 나열합니다.

import { ListUsersCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const listUsers = async () => { const command = new ListUsersCommand({ MaxItems: 10 }); const response = await client.send(command); response.Users?.forEach(({ UserName, CreateDate }) => { console.log(`${UserName} created on: ${CreateDate}`); }); return response; };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { MaxItems: 10, }; iam.listUsers(params, function (err, data) { if (err) { console.log("Error", err); } else { var users = data.Users || []; users.forEach(function (user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } });

다음 코드 예제에서는 IAM 서버 인증서를 업데이트하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

서버 인증서를 업데이트합니다.

import { UpdateServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} currentName * @param {string} newName */ export const updateServerCertificate = (currentName, newName) => { const command = new UpdateServerCertificateCommand({ ServerCertificateName: currentName, NewServerCertificateName: newName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { ServerCertificateName: "CERTIFICATE_NAME", NewServerCertificateName: "NEW_CERTIFICATE_NAME", }; iam.updateServerCertificate(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 사용자를 업데이트하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

사용자를 업데이트합니다.

import { UpdateUserCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} currentUserName * @param {string} newUserName */ export const updateUser = (currentUserName, newUserName) => { const command = new UpdateUserCommand({ UserName: currentUserName, NewUserName: newUserName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { UserName: process.argv[2], NewUserName: process.argv[3], }; iam.updateUser(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 IAM 액세스 키를 업데이트하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

액세스 키를 업데이트합니다.

import { UpdateAccessKeyCommand, IAMClient, StatusType, } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} userName * @param {string} accessKeyId */ export const updateAccessKey = (userName, accessKeyId) => { const command = new UpdateAccessKeyCommand({ AccessKeyId: accessKeyId, Status: StatusType.Inactive, UserName: userName, }); return client.send(command); };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { AccessKeyId: "ACCESS_KEY_ID", Status: "Active", UserName: "USER_NAME", }; iam.updateAccessKey(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

다음 코드 예제에서는 AWS Identity and Access Management (IAM) 서버 인증서를 업로드하는 방법을 보여줍니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { UploadServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam"; import { readFileSync } from "fs"; import { dirnameFromMetaUrl } from "@aws-sdk-examples/libs/utils/util-fs.js"; import * as path from "path"; const client = new IAMClient({}); const certMessage = `Generate a certificate and key with the following command, or the equivalent for your system. openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \ -keyout example.key -out example.crt -subj "/CN=example.com" \ -addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1" `; const getCertAndKey = () => { try { const cert = readFileSync( path.join(dirnameFromMetaUrl(import.meta.url), "./example.crt") ); const key = readFileSync( path.join(dirnameFromMetaUrl(import.meta.url), "./example.key") ); return { cert, key }; } catch (err) { if (err.code === "ENOENT") { throw new Error( `Certificate and/or private key not found. ${certMessage}` ); } throw err; } }; /** * * @param {string} certificateName */ export const uploadServerCertificate = (certificateName) => { const { cert, key } = getCertAndKey(); const command = new UploadServerCertificateCommand({ ServerCertificateName: certificateName, CertificateBody: cert.toString(), PrivateKey: key.toString(), }); return client.send(command); };

시나리오

다음 코드 예제에서는 책, 영화, 노래 추천을 반환하는 로드 밸런싱 웹 서비스를 만드는 방법을 보여줍니다. 이 예제에서는 서비스가 장애에 대응하는 방법과 장애 발생 시 복원력을 높이기 위해 서비스를 재구성하는 방법을 보여줍니다.

  • Amazon EC2 Auto Scaling 그룹을 사용하여 시작 템플릿을 기반으로 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 생성하고 인스턴스 수를 지정된 범위 내로 유지합니다.

  • Elastic Load Balancing으로 HTTP 요청을 처리하고 배포합니다.

  • 오토 스케일링의 인스턴스 상태를 모니터링하고 요청을 정상 인스턴스로만 전달합니다.

  • 각 EC2 인스턴스에서 Python 웹 서버를 실행하여 HTTP 요청을 처리합니다. 웹 서버는 추천 및 상태 확인으로 응답합니다.

  • Amazon DynamoDB 테이블을 사용하여 추천 서비스를 시뮬레이션합니다.

  • AWS Systems Manager 파라미터를 업데이트하여 요청 및 상태 확인에 대한 웹 서버 응답을 제어합니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

명령 프롬프트에서 대화형 시나리오를 실행합니다.

#!/usr/bin/env node // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { Scenario, parseScenarioArgs, } from "@aws-sdk-examples/libs/scenario/index.js"; /** * The workflow steps are split into three stages: * - deploy * - demo * - destroy * * Each of these stages has a corresponding file prefixed with steps-*. */ import { deploySteps } from "./steps-deploy.js"; import { demoSteps } from "./steps-demo.js"; import { destroySteps } from "./steps-destroy.js"; /** * The context is passed to every scenario. Scenario steps * will modify the context. */ const context = {}; /** * Three Scenarios are created for the workflow. A Scenario is an orchestration class * that simplifies running a series of steps. */ export const scenarios = { // Deploys all resources necessary for the workflow. deploy: new Scenario("Resilient Workflow - Deploy", deploySteps, context), // Demonstrates how a fragile web service can be made more resilient. demo: new Scenario("Resilient Workflow - Demo", demoSteps, context), // Destroys the resources created for the workflow. destroy: new Scenario("Resilient Workflow - Destroy", destroySteps, context), }; // Call function if run directly import { fileURLToPath } from "url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { parseScenarioArgs(scenarios); }

모든 리소스를 배포하기 위한 단계를 생성합니다.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { join } from "node:path"; import { readFileSync, writeFileSync } from "node:fs"; import axios from "axios"; import { BatchWriteItemCommand, CreateTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { EC2Client, CreateKeyPairCommand, CreateLaunchTemplateCommand, DescribeAvailabilityZonesCommand, DescribeVpcsCommand, DescribeSubnetsCommand, DescribeSecurityGroupsCommand, AuthorizeSecurityGroupIngressCommand, } from "@aws-sdk/client-ec2"; import { IAMClient, CreatePolicyCommand, CreateRoleCommand, CreateInstanceProfileCommand, AddRoleToInstanceProfileCommand, AttachRolePolicyCommand, waitUntilInstanceProfileExists, } from "@aws-sdk/client-iam"; import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm"; import { CreateAutoScalingGroupCommand, AutoScalingClient, AttachLoadBalancerTargetGroupsCommand, } from "@aws-sdk/client-auto-scaling"; import { CreateListenerCommand, CreateLoadBalancerCommand, CreateTargetGroupCommand, ElasticLoadBalancingV2Client, waitUntilLoadBalancerAvailable, } from "@aws-sdk/client-elastic-load-balancing-v2"; import { ScenarioOutput, ScenarioInput, ScenarioAction, } from "@aws-sdk-examples/libs/scenario/index.js"; import { retry } from "@aws-sdk-examples/libs/utils/util-timers.js"; import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js"; import { initParamsSteps } from "./steps-reset-params.js"; /** * @type {import('@aws-sdk-examples/libs/scenario.js').Step[]} */ export const deploySteps = [ new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }), new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, { type: "confirm", }), new ScenarioAction( "handleConfirmDeployment", (c) => c.confirmDeployment === false && process.exit(), ), new ScenarioOutput( "creatingTable", MESSAGES.creatingTable.replace("${TABLE_NAME}", NAMES.tableName), ), new ScenarioAction("createTable", async () => { const client = new DynamoDBClient({}); await client.send( new CreateTableCommand({ TableName: NAMES.tableName, ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, AttributeDefinitions: [ { AttributeName: "MediaType", AttributeType: "S", }, { AttributeName: "ItemId", AttributeType: "N", }, ], KeySchema: [ { AttributeName: "MediaType", KeyType: "HASH", }, { AttributeName: "ItemId", KeyType: "RANGE", }, ], }), ); await waitUntilTableExists({ client }, { TableName: NAMES.tableName }); }), new ScenarioOutput( "createdTable", MESSAGES.createdTable.replace("${TABLE_NAME}", NAMES.tableName), ), new ScenarioOutput( "populatingTable", MESSAGES.populatingTable.replace("${TABLE_NAME}", NAMES.tableName), ), new ScenarioAction("populateTable", () => { const client = new DynamoDBClient({}); /** * @type {{ default: import("@aws-sdk/client-dynamodb").PutRequest['Item'][] }} */ const recommendations = JSON.parse( readFileSync(join(RESOURCES_PATH, "recommendations.json")), ); return client.send( new BatchWriteItemCommand({ RequestItems: { [NAMES.tableName]: recommendations.map((item) => ({ PutRequest: { Item: item }, })), }, }), ); }), new ScenarioOutput( "populatedTable", MESSAGES.populatedTable.replace("${TABLE_NAME}", NAMES.tableName), ), new ScenarioOutput( "creatingKeyPair", MESSAGES.creatingKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName), ), new ScenarioAction("createKeyPair", async () => { const client = new EC2Client({}); const { KeyMaterial } = await client.send( new CreateKeyPairCommand({ KeyName: NAMES.keyPairName, }), ); writeFileSync(`${NAMES.keyPairName}.pem`, KeyMaterial, { mode: 0o600 }); }), new ScenarioOutput( "createdKeyPair", MESSAGES.createdKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName), ), new ScenarioOutput( "creatingInstancePolicy", MESSAGES.creatingInstancePolicy.replace( "${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName, ), ), new ScenarioAction("createInstancePolicy", async (state) => { const client = new IAMClient({}); const { Policy: { Arn }, } = await client.send( new CreatePolicyCommand({ PolicyName: NAMES.instancePolicyName, PolicyDocument: readFileSync( join(RESOURCES_PATH, "instance_policy.json"), ), }), ); state.instancePolicyArn = Arn; }), new ScenarioOutput("createdInstancePolicy", (state) => MESSAGES.createdInstancePolicy .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName) .replace("${INSTANCE_POLICY_ARN}", state.instancePolicyArn), ), new ScenarioOutput( "creatingInstanceRole", MESSAGES.creatingInstanceRole.replace( "${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName, ), ), new ScenarioAction("createInstanceRole", () => { const client = new IAMClient({}); return client.send( new CreateRoleCommand({ RoleName: NAMES.instanceRoleName, AssumeRolePolicyDocument: readFileSync( join(ROOT, "assume-role-policy.json"), ), }), ); }), new ScenarioOutput( "createdInstanceRole", MESSAGES.createdInstanceRole.replace( "${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName, ), ), new ScenarioOutput( "attachingPolicyToRole", MESSAGES.attachingPolicyToRole .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName) .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName), ), new ScenarioAction("attachPolicyToRole", async (state) => { const client = new IAMClient({}); await client.send( new AttachRolePolicyCommand({ RoleName: NAMES.instanceRoleName, PolicyArn: state.instancePolicyArn, }), ); }), new ScenarioOutput( "attachedPolicyToRole", MESSAGES.attachedPolicyToRole .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName), ), new ScenarioOutput( "creatingInstanceProfile", MESSAGES.creatingInstanceProfile.replace( "${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName, ), ), new ScenarioAction("createInstanceProfile", async (state) => { const client = new IAMClient({}); const { InstanceProfile: { Arn }, } = await client.send( new CreateInstanceProfileCommand({ InstanceProfileName: NAMES.instanceProfileName, }), ); state.instanceProfileArn = Arn; await waitUntilInstanceProfileExists( { client }, { InstanceProfileName: NAMES.instanceProfileName }, ); }), new ScenarioOutput("createdInstanceProfile", (state) => MESSAGES.createdInstanceProfile .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName) .replace("${INSTANCE_PROFILE_ARN}", state.instanceProfileArn), ), new ScenarioOutput( "addingRoleToInstanceProfile", MESSAGES.addingRoleToInstanceProfile .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName), ), new ScenarioAction("addRoleToInstanceProfile", () => { const client = new IAMClient({}); return client.send( new AddRoleToInstanceProfileCommand({ RoleName: NAMES.instanceRoleName, InstanceProfileName: NAMES.instanceProfileName, }), ); }), new ScenarioOutput( "addedRoleToInstanceProfile", MESSAGES.addedRoleToInstanceProfile .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName), ), ...initParamsSteps, new ScenarioOutput("creatingLaunchTemplate", MESSAGES.creatingLaunchTemplate), new ScenarioAction("createLaunchTemplate", async () => { // snippet-start:[javascript.v3.wkflw.resilient.CreateLaunchTemplate] const ssmClient = new SSMClient({}); const { Parameter } = await ssmClient.send( new GetParameterCommand({ Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2", }), ); const ec2Client = new EC2Client({}); await ec2Client.send( new CreateLaunchTemplateCommand({ LaunchTemplateName: NAMES.launchTemplateName, LaunchTemplateData: { InstanceType: "t3.micro", ImageId: Parameter.Value, IamInstanceProfile: { Name: NAMES.instanceProfileName }, UserData: readFileSync( join(RESOURCES_PATH, "server_startup_script.sh"), ).toString("base64"), KeyName: NAMES.keyPairName, }, }), // snippet-end:[javascript.v3.wkflw.resilient.CreateLaunchTemplate] ); }), new ScenarioOutput( "createdLaunchTemplate", MESSAGES.createdLaunchTemplate.replace( "${LAUNCH_TEMPLATE_NAME}", NAMES.launchTemplateName, ), ), new ScenarioOutput( "creatingAutoScalingGroup", MESSAGES.creatingAutoScalingGroup.replace( "${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName, ), ), new ScenarioAction("createAutoScalingGroup", async (state) => { const ec2Client = new EC2Client({}); const { AvailabilityZones } = await ec2Client.send( new DescribeAvailabilityZonesCommand({}), ); state.availabilityZoneNames = AvailabilityZones.map((az) => az.ZoneName); const autoScalingClient = new AutoScalingClient({}); await retry({ intervalInMs: 1000, maxRetries: 30 }, () => autoScalingClient.send( new CreateAutoScalingGroupCommand({ AvailabilityZones: state.availabilityZoneNames, AutoScalingGroupName: NAMES.autoScalingGroupName, LaunchTemplate: { LaunchTemplateName: NAMES.launchTemplateName, Version: "$Default", }, MinSize: 3, MaxSize: 3, }), ), ); }), new ScenarioOutput( "createdAutoScalingGroup", /** * @param {{ availabilityZoneNames: string[] }} state */ (state) => MESSAGES.createdAutoScalingGroup .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName) .replace( "${AVAILABILITY_ZONE_NAMES}", state.availabilityZoneNames.join(", "), ), ), new ScenarioInput("confirmContinue", MESSAGES.confirmContinue, { type: "confirm", }), new ScenarioOutput("loadBalancer", MESSAGES.loadBalancer), new ScenarioOutput("gettingVpc", MESSAGES.gettingVpc), new ScenarioAction("getVpc", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.DescribeVpcs] const client = new EC2Client({}); const { Vpcs } = await client.send( new DescribeVpcsCommand({ Filters: [{ Name: "is-default", Values: ["true"] }], }), ); // snippet-end:[javascript.v3.wkflw.resilient.DescribeVpcs] state.defaultVpc = Vpcs[0].VpcId; }), new ScenarioOutput("gotVpc", (state) => MESSAGES.gotVpc.replace("${VPC_ID}", state.defaultVpc), ), new ScenarioOutput("gettingSubnets", MESSAGES.gettingSubnets), new ScenarioAction("getSubnets", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.DescribeSubnets] const client = new EC2Client({}); const { Subnets } = await client.send( new DescribeSubnetsCommand({ Filters: [ { Name: "vpc-id", Values: [state.defaultVpc] }, { Name: "availability-zone", Values: state.availabilityZoneNames }, { Name: "default-for-az", Values: ["true"] }, ], }), ); // snippet-end:[javascript.v3.wkflw.resilient.DescribeSubnets] state.subnets = Subnets.map((subnet) => subnet.SubnetId); }), new ScenarioOutput( "gotSubnets", /** * @param {{ subnets: string[] }} state */ (state) => MESSAGES.gotSubnets.replace("${SUBNETS}", state.subnets.join(", ")), ), new ScenarioOutput( "creatingLoadBalancerTargetGroup", MESSAGES.creatingLoadBalancerTargetGroup.replace( "${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName, ), ), new ScenarioAction("createLoadBalancerTargetGroup", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.CreateTargetGroup] const client = new ElasticLoadBalancingV2Client({}); const { TargetGroups } = await client.send( new CreateTargetGroupCommand({ Name: NAMES.loadBalancerTargetGroupName, Protocol: "HTTP", Port: 80, HealthCheckPath: "/healthcheck", HealthCheckIntervalSeconds: 10, HealthCheckTimeoutSeconds: 5, HealthyThresholdCount: 2, UnhealthyThresholdCount: 2, VpcId: state.defaultVpc, }), ); // snippet-end:[javascript.v3.wkflw.resilient.CreateTargetGroup] const targetGroup = TargetGroups[0]; state.targetGroupArn = targetGroup.TargetGroupArn; state.targetGroupProtocol = targetGroup.Protocol; state.targetGroupPort = targetGroup.Port; }), new ScenarioOutput( "createdLoadBalancerTargetGroup", MESSAGES.createdLoadBalancerTargetGroup.replace( "${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName, ), ), new ScenarioOutput( "creatingLoadBalancer", MESSAGES.creatingLoadBalancer.replace("${LB_NAME}", NAMES.loadBalancerName), ), new ScenarioAction("createLoadBalancer", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.CreateLoadBalancer] const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new CreateLoadBalancerCommand({ Name: NAMES.loadBalancerName, Subnets: state.subnets, }), ); state.loadBalancerDns = LoadBalancers[0].DNSName; state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn; await waitUntilLoadBalancerAvailable( { client }, { Names: [NAMES.loadBalancerName] }, ); // snippet-end:[javascript.v3.wkflw.resilient.CreateLoadBalancer] }), new ScenarioOutput("createdLoadBalancer", (state) => MESSAGES.createdLoadBalancer .replace("${LB_NAME}", NAMES.loadBalancerName) .replace("${DNS_NAME}", state.loadBalancerDns), ), new ScenarioOutput( "creatingListener", MESSAGES.creatingLoadBalancerListener .replace("${LB_NAME}", NAMES.loadBalancerName) .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName), ), new ScenarioAction("createListener", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.CreateListener] const client = new ElasticLoadBalancingV2Client({}); const { Listeners } = await client.send( new CreateListenerCommand({ LoadBalancerArn: state.loadBalancerArn, Protocol: state.targetGroupProtocol, Port: state.targetGroupPort, DefaultActions: [ { Type: "forward", TargetGroupArn: state.targetGroupArn }, ], }), ); // snippet-end:[javascript.v3.wkflw.resilient.CreateListener] const listener = Listeners[0]; state.loadBalancerListenerArn = listener.ListenerArn; }), new ScenarioOutput("createdListener", (state) => MESSAGES.createdLoadBalancerListener.replace( "${LB_LISTENER_ARN}", state.loadBalancerListenerArn, ), ), new ScenarioOutput( "attachingLoadBalancerTargetGroup", MESSAGES.attachingLoadBalancerTargetGroup .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName) .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName), ), new ScenarioAction("attachLoadBalancerTargetGroup", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.AttachTargetGroup] const client = new AutoScalingClient({}); await client.send( new AttachLoadBalancerTargetGroupsCommand({ AutoScalingGroupName: NAMES.autoScalingGroupName, TargetGroupARNs: [state.targetGroupArn], }), ); // snippet-end:[javascript.v3.wkflw.resilient.AttachTargetGroup] }), new ScenarioOutput( "attachedLoadBalancerTargetGroup", MESSAGES.attachedLoadBalancerTargetGroup, ), new ScenarioOutput("verifyingInboundPort", MESSAGES.verifyingInboundPort), new ScenarioAction( "verifyInboundPort", /** * * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup}} state */ async (state) => { const client = new EC2Client({}); const { SecurityGroups } = await client.send( new DescribeSecurityGroupsCommand({ Filters: [{ Name: "group-name", Values: ["default"] }], }), ); if (!SecurityGroups) { state.verifyInboundPortError = new Error(MESSAGES.noSecurityGroups); } state.defaultSecurityGroup = SecurityGroups[0]; /** * @type {string} */ const ipResponse = (await axios.get("http://checkip.amazonaws.com")).data; state.myIp = ipResponse.trim(); const myIpRules = state.defaultSecurityGroup.IpPermissions.filter( ({ IpRanges }) => IpRanges.some( ({ CidrIp }) => CidrIp.startsWith(state.myIp) || CidrIp === "0.0.0.0/0", ), ) .filter(({ IpProtocol }) => IpProtocol === "tcp") .filter(({ FromPort }) => FromPort === 80); state.myIpRules = myIpRules; }, ), new ScenarioOutput( "verifiedInboundPort", /** * @param {{ myIpRules: any[] }} state */ (state) => { if (state.myIpRules.length > 0) { return MESSAGES.foundIpRules.replace( "${IP_RULES}", JSON.stringify(state.myIpRules, null, 2), ); } else { return MESSAGES.noIpRules; } }, ), new ScenarioInput( "shouldAddInboundRule", /** * @param {{ myIpRules: any[] }} state */ (state) => { if (state.myIpRules.length > 0) { return false; } else { return MESSAGES.noIpRules; } }, { type: "confirm" }, ), new ScenarioAction( "addInboundRule", /** * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup }} state */ async (state) => { if (!state.shouldAddInboundRule) { return; } const client = new EC2Client({}); await client.send( new AuthorizeSecurityGroupIngressCommand({ GroupId: state.defaultSecurityGroup.GroupId, CidrIp: `${state.myIp}/32`, FromPort: 80, ToPort: 80, IpProtocol: "tcp", }), ); }, ), new ScenarioOutput("addedInboundRule", (state) => { if (state.shouldAddInboundRule) { return MESSAGES.addedInboundRule.replace("${IP_ADDRESS}", state.myIp); } else { return false; } }), new ScenarioOutput("verifyingEndpoint", (state) => MESSAGES.verifyingEndpoint.replace("${DNS_NAME}", state.loadBalancerDns), ), new ScenarioAction("verifyEndpoint", async (state) => { try { const response = await retry({ intervalInMs: 2000, maxRetries: 30 }, () => axios.get(`http://${state.loadBalancerDns}`), ); state.endpointResponse = JSON.stringify(response.data, null, 2); } catch (e) { state.verifyEndpointError = e; } }), new ScenarioOutput("verifiedEndpoint", (state) => { if (state.verifyEndpointError) { console.error(state.verifyEndpointError); } else { return MESSAGES.verifiedEndpoint.replace( "${ENDPOINT_RESPONSE}", state.endpointResponse, ); } }), ];

데모를 실행하기 위한 단계를 생성합니다.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { readFileSync } from "node:fs"; import { join } from "node:path"; import axios from "axios"; import { DescribeTargetGroupsCommand, DescribeTargetHealthCommand, ElasticLoadBalancingV2Client, } from "@aws-sdk/client-elastic-load-balancing-v2"; import { DescribeInstanceInformationCommand, PutParameterCommand, SSMClient, SendCommandCommand, } from "@aws-sdk/client-ssm"; import { IAMClient, CreatePolicyCommand, CreateRoleCommand, AttachRolePolicyCommand, CreateInstanceProfileCommand, AddRoleToInstanceProfileCommand, waitUntilInstanceProfileExists, } from "@aws-sdk/client-iam"; import { AutoScalingClient, DescribeAutoScalingGroupsCommand, TerminateInstanceInAutoScalingGroupCommand, } from "@aws-sdk/client-auto-scaling"; import { DescribeIamInstanceProfileAssociationsCommand, EC2Client, RebootInstancesCommand, ReplaceIamInstanceProfileAssociationCommand, } from "@aws-sdk/client-ec2"; import { ScenarioAction, ScenarioInput, ScenarioOutput, } from "@aws-sdk-examples/libs/scenario/scenario.js"; import { retry } from "@aws-sdk-examples/libs/utils/util-timers.js"; import { MESSAGES, NAMES, RESOURCES_PATH } from "./constants.js"; import { findLoadBalancer } from "./shared.js"; const getRecommendation = new ScenarioAction( "getRecommendation", async (state) => { const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName); if (loadBalancer) { state.loadBalancerDnsName = loadBalancer.DNSName; try { state.recommendation = ( await axios.get(`http://${state.loadBalancerDnsName}`) ).data; } catch (e) { state.recommendation = e instanceof Error ? e.message : e; } } else { throw new Error(MESSAGES.demoFindLoadBalancerError); } }, ); const getRecommendationResult = new ScenarioOutput( "getRecommendationResult", (state) => `Recommendation:\n${JSON.stringify(state.recommendation, null, 2)}`, { preformatted: true }, ); const getHealthCheck = new ScenarioAction("getHealthCheck", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.DescribeTargetGroups] const client = new ElasticLoadBalancingV2Client({}); const { TargetGroups } = await client.send( new DescribeTargetGroupsCommand({ Names: [NAMES.loadBalancerTargetGroupName], }), ); // snippet-end:[javascript.v3.wkflw.resilient.DescribeTargetGroups] // snippet-start:[javascript.v3.wkflw.resilient.DescribeTargetHealth] const { TargetHealthDescriptions } = await client.send( new DescribeTargetHealthCommand({ TargetGroupArn: TargetGroups[0].TargetGroupArn, }), ); // snippet-end:[javascript.v3.wkflw.resilient.DescribeTargetHealth] state.targetHealthDescriptions = TargetHealthDescriptions; }); const getHealthCheckResult = new ScenarioOutput( "getHealthCheckResult", /** * @param {{ targetHealthDescriptions: import('@aws-sdk/client-elastic-load-balancing-v2').TargetHealthDescription[]}} state */ (state) => { const status = state.targetHealthDescriptions .map((th) => `${th.Target.Id}: ${th.TargetHealth.State}`) .join("\n"); return `Health check:\n${status}`; }, { preformatted: true }, ); const loadBalancerLoop = new ScenarioAction( "loadBalancerLoop", getRecommendation.action, { whileConfig: { inputEquals: true, input: new ScenarioInput( "loadBalancerCheck", MESSAGES.demoLoadBalancerCheck, { type: "confirm", }, ), output: getRecommendationResult, }, }, ); const healthCheckLoop = new ScenarioAction( "healthCheckLoop", getHealthCheck.action, { whileConfig: { inputEquals: true, input: new ScenarioInput("healthCheck", MESSAGES.demoHealthCheck, { type: "confirm", }), output: getHealthCheckResult, }, }, ); const statusSteps = [ getRecommendation, getRecommendationResult, getHealthCheck, getHealthCheckResult, ]; /** * @type {import('@aws-sdk-examples/libs/scenario.js').Step[]} */ export const demoSteps = [ new ScenarioOutput("header", MESSAGES.demoHeader, { header: true }), new ScenarioOutput("sanityCheck", MESSAGES.demoSanityCheck), ...statusSteps, new ScenarioInput( "brokenDependencyConfirmation", MESSAGES.demoBrokenDependencyConfirmation, { type: "confirm" }, ), new ScenarioAction("brokenDependency", async (state) => { if (!state.brokenDependencyConfirmation) { process.exit(); } else { const client = new SSMClient({}); state.badTableName = `fake-table-${Date.now()}`; await client.send( new PutParameterCommand({ Name: NAMES.ssmTableNameKey, Value: state.badTableName, Overwrite: true, Type: "String", }), ); } }), new ScenarioOutput("testBrokenDependency", (state) => MESSAGES.demoTestBrokenDependency.replace( "${TABLE_NAME}", state.badTableName, ), ), ...statusSteps, new ScenarioInput( "staticResponseConfirmation", MESSAGES.demoStaticResponseConfirmation, { type: "confirm" }, ), new ScenarioAction("staticResponse", async (state) => { if (!state.staticResponseConfirmation) { process.exit(); } else { const client = new SSMClient({}); await client.send( new PutParameterCommand({ Name: NAMES.ssmFailureResponseKey, Value: "static", Overwrite: true, Type: "String", }), ); } }), new ScenarioOutput("testStaticResponse", MESSAGES.demoTestStaticResponse), ...statusSteps, new ScenarioInput( "badCredentialsConfirmation", MESSAGES.demoBadCredentialsConfirmation, { type: "confirm" }, ), new ScenarioAction("badCredentialsExit", (state) => { if (!state.badCredentialsConfirmation) { process.exit(); } }), new ScenarioAction("fixDynamoDBName", async () => { const client = new SSMClient({}); await client.send( new PutParameterCommand({ Name: NAMES.ssmTableNameKey, Value: NAMES.tableName, Overwrite: true, Type: "String", }), ); }), new ScenarioAction( "badCredentials", /** * @param {{ targetInstance: import('@aws-sdk/client-auto-scaling').Instance }} state */ async (state) => { await createSsmOnlyInstanceProfile(); const autoScalingClient = new AutoScalingClient({}); const { AutoScalingGroups } = await autoScalingClient.send( new DescribeAutoScalingGroupsCommand({ AutoScalingGroupNames: [NAMES.autoScalingGroupName], }), ); state.targetInstance = AutoScalingGroups[0].Instances[0]; // snippet-start:[javascript.v3.wkflw.resilient.DescribeIamInstanceProfileAssociations] const ec2Client = new EC2Client({}); const { IamInstanceProfileAssociations } = await ec2Client.send( new DescribeIamInstanceProfileAssociationsCommand({ Filters: [ { Name: "instance-id", Values: [state.targetInstance.InstanceId] }, ], }), ); // snippet-end:[javascript.v3.wkflw.resilient.DescribeIamInstanceProfileAssociations] state.instanceProfileAssociationId = IamInstanceProfileAssociations[0].AssociationId; // snippet-start:[javascript.v3.wkflw.resilient.ReplaceIamInstanceProfileAssociation] await retry({ intervalInMs: 1000, maxRetries: 30 }, () => ec2Client.send( new ReplaceIamInstanceProfileAssociationCommand({ AssociationId: state.instanceProfileAssociationId, IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName }, }), ), ); // snippet-end:[javascript.v3.wkflw.resilient.ReplaceIamInstanceProfileAssociation] await ec2Client.send( new RebootInstancesCommand({ InstanceIds: [state.targetInstance.InstanceId], }), ); const ssmClient = new SSMClient({}); await retry({ intervalInMs: 20000, maxRetries: 15 }, async () => { const { InstanceInformationList } = await ssmClient.send( new DescribeInstanceInformationCommand({}), ); const instance = InstanceInformationList.find( (info) => info.InstanceId === state.targetInstance.InstanceId, ); if (!instance) { throw new Error("Instance not found."); } }); await ssmClient.send( new SendCommandCommand({ InstanceIds: [state.targetInstance.InstanceId], DocumentName: "AWS-RunShellScript", Parameters: { commands: ["cd / && sudo python3 server.py 80"] }, }), ); }, ), new ScenarioOutput( "testBadCredentials", /** * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation}} state */ (state) => MESSAGES.demoTestBadCredentials.replace( "${INSTANCE_ID}", state.targetInstance.InstanceId, ), ), loadBalancerLoop, new ScenarioInput( "deepHealthCheckConfirmation", MESSAGES.demoDeepHealthCheckConfirmation, { type: "confirm" }, ), new ScenarioAction("deepHealthCheckExit", (state) => { if (!state.deepHealthCheckConfirmation) { process.exit(); } }), new ScenarioAction("deepHealthCheck", async () => { const client = new SSMClient({}); await client.send( new PutParameterCommand({ Name: NAMES.ssmHealthCheckKey, Value: "deep", Overwrite: true, Type: "String", }), ); }), new ScenarioOutput("testDeepHealthCheck", MESSAGES.demoTestDeepHealthCheck), healthCheckLoop, loadBalancerLoop, new ScenarioInput( "killInstanceConfirmation", /** * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state */ (state) => MESSAGES.demoKillInstanceConfirmation.replace( "${INSTANCE_ID}", state.targetInstance.InstanceId, ), { type: "confirm" }, ), new ScenarioAction("killInstanceExit", (state) => { if (!state.killInstanceConfirmation) { process.exit(); } }), new ScenarioAction( "killInstance", /** * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state */ async (state) => { const client = new AutoScalingClient({}); await client.send( new TerminateInstanceInAutoScalingGroupCommand({ InstanceId: state.targetInstance.InstanceId, ShouldDecrementDesiredCapacity: false, }), ); }, ), new ScenarioOutput("testKillInstance", MESSAGES.demoTestKillInstance), healthCheckLoop, loadBalancerLoop, new ScenarioInput("failOpenConfirmation", MESSAGES.demoFailOpenConfirmation, { type: "confirm", }), new ScenarioAction("failOpenExit", (state) => { if (!state.failOpenConfirmation) { process.exit(); } }), new ScenarioAction("failOpen", () => { const client = new SSMClient({}); return client.send( new PutParameterCommand({ Name: NAMES.ssmTableNameKey, Value: `fake-table-${Date.now()}`, Overwrite: true, Type: "String", }), ); }), new ScenarioOutput("testFailOpen", MESSAGES.demoFailOpenTest), healthCheckLoop, loadBalancerLoop, new ScenarioInput( "resetTableConfirmation", MESSAGES.demoResetTableConfirmation, { type: "confirm" }, ), new ScenarioAction("resetTableExit", (state) => { if (!state.resetTableConfirmation) { process.exit(); } }), new ScenarioAction("resetTable", async () => { const client = new SSMClient({}); await client.send( new PutParameterCommand({ Name: NAMES.ssmTableNameKey, Value: NAMES.tableName, Overwrite: true, Type: "String", }), ); }), new ScenarioOutput("testResetTable", MESSAGES.demoTestResetTable), healthCheckLoop, loadBalancerLoop, ]; async function createSsmOnlyInstanceProfile() { const iamClient = new IAMClient({}); const { Policy } = await iamClient.send( new CreatePolicyCommand({ PolicyName: NAMES.ssmOnlyPolicyName, PolicyDocument: readFileSync( join(RESOURCES_PATH, "ssm_only_policy.json"), ), }), ); await iamClient.send( new CreateRoleCommand({ RoleName: NAMES.ssmOnlyRoleName, AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "ec2.amazonaws.com" }, Action: "sts:AssumeRole", }, ], }), }), ); await iamClient.send( new AttachRolePolicyCommand({ RoleName: NAMES.ssmOnlyRoleName, PolicyArn: Policy.Arn, }), ); await iamClient.send( new AttachRolePolicyCommand({ RoleName: NAMES.ssmOnlyRoleName, PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", }), ); // snippet-start:[javascript.v3.wkflw.resilient.CreateInstanceProfile] const { InstanceProfile } = await iamClient.send( new CreateInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, }), ); await waitUntilInstanceProfileExists( { client: iamClient }, { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName }, ); // snippet-end:[javascript.v3.wkflw.resilient.CreateInstanceProfile] await iamClient.send( new AddRoleToInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, RoleName: NAMES.ssmOnlyRoleName, }), ); return InstanceProfile; }

모든 리소스를 폐기하는 단계를 생성합니다.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { unlinkSync } from "node:fs"; import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb"; import { EC2Client, DeleteKeyPairCommand, DeleteLaunchTemplateCommand, } from "@aws-sdk/client-ec2"; import { IAMClient, DeleteInstanceProfileCommand, RemoveRoleFromInstanceProfileCommand, DeletePolicyCommand, DeleteRoleCommand, DetachRolePolicyCommand, paginateListPolicies, } from "@aws-sdk/client-iam"; import { AutoScalingClient, DeleteAutoScalingGroupCommand, TerminateInstanceInAutoScalingGroupCommand, UpdateAutoScalingGroupCommand, paginateDescribeAutoScalingGroups, } from "@aws-sdk/client-auto-scaling"; import { DeleteLoadBalancerCommand, DeleteTargetGroupCommand, DescribeTargetGroupsCommand, ElasticLoadBalancingV2Client, } from "@aws-sdk/client-elastic-load-balancing-v2"; import { ScenarioOutput, ScenarioInput, ScenarioAction, } from "@aws-sdk-examples/libs/scenario/index.js"; import { retry } from "@aws-sdk-examples/libs/utils/util-timers.js"; import { MESSAGES, NAMES } from "./constants.js"; import { findLoadBalancer } from "./shared.js"; /** * @type {import('@aws-sdk-examples/libs/scenario.js').Step[]} */ export const destroySteps = [ new ScenarioInput("destroy", MESSAGES.destroy, { type: "confirm" }), new ScenarioAction( "abort", (state) => state.destroy === false && process.exit(), ), new ScenarioAction("deleteTable", async (c) => { try { const client = new DynamoDBClient({}); await client.send(new DeleteTableCommand({ TableName: NAMES.tableName })); } catch (e) { c.deleteTableError = e; } }), new ScenarioOutput("deleteTableResult", (state) => { if (state.deleteTableError) { console.error(state.deleteTableError); return MESSAGES.deleteTableError.replace( "${TABLE_NAME}", NAMES.tableName, ); } else { return MESSAGES.deletedTable.replace("${TABLE_NAME}", NAMES.tableName); } }), new ScenarioAction("deleteKeyPair", async (state) => { try { const client = new EC2Client({}); await client.send( new DeleteKeyPairCommand({ KeyName: NAMES.keyPairName }), ); unlinkSync(`${NAMES.keyPairName}.pem`); } catch (e) { state.deleteKeyPairError = e; } }), new ScenarioOutput("deleteKeyPairResult", (state) => { if (state.deleteKeyPairError) { console.error(state.deleteKeyPairError); return MESSAGES.deleteKeyPairError.replace( "${KEY_PAIR_NAME}", NAMES.keyPairName, ); } else { return MESSAGES.deletedKeyPair.replace( "${KEY_PAIR_NAME}", NAMES.keyPairName, ); } }), new ScenarioAction("detachPolicyFromRole", async (state) => { try { const client = new IAMClient({}); const policy = await findPolicy(NAMES.instancePolicyName); if (!policy) { state.detachPolicyFromRoleError = new Error( `Policy ${NAMES.instancePolicyName} not found.`, ); } else { await client.send( new DetachRolePolicyCommand({ RoleName: NAMES.instanceRoleName, PolicyArn: policy.Arn, }), ); } } catch (e) { state.detachPolicyFromRoleError = e; } }), new ScenarioOutput("detachedPolicyFromRole", (state) => { if (state.detachPolicyFromRoleError) { console.error(state.detachPolicyFromRoleError); return MESSAGES.detachPolicyFromRoleError .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName); } else { return MESSAGES.detachedPolicyFromRole .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName); } }), new ScenarioAction("deleteInstancePolicy", async (state) => { const client = new IAMClient({}); const policy = await findPolicy(NAMES.instancePolicyName); if (!policy) { state.deletePolicyError = new Error( `Policy ${NAMES.instancePolicyName} not found.`, ); } else { return client.send( new DeletePolicyCommand({ PolicyArn: policy.Arn, }), ); } }), new ScenarioOutput("deletePolicyResult", (state) => { if (state.deletePolicyError) { console.error(state.deletePolicyError); return MESSAGES.deletePolicyError.replace( "${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName, ); } else { return MESSAGES.deletedPolicy.replace( "${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName, ); } }), new ScenarioAction("removeRoleFromInstanceProfile", async (state) => { try { const client = new IAMClient({}); await client.send( new RemoveRoleFromInstanceProfileCommand({ RoleName: NAMES.instanceRoleName, InstanceProfileName: NAMES.instanceProfileName, }), ); } catch (e) { state.removeRoleFromInstanceProfileError = e; } }), new ScenarioOutput("removeRoleFromInstanceProfileResult", (state) => { if (state.removeRoleFromInstanceProfile) { console.error(state.removeRoleFromInstanceProfileError); return MESSAGES.removeRoleFromInstanceProfileError .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName); } else { return MESSAGES.removedRoleFromInstanceProfile .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName) .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName); } }), new ScenarioAction("deleteInstanceRole", async (state) => { try { const client = new IAMClient({}); await client.send( new DeleteRoleCommand({ RoleName: NAMES.instanceRoleName, }), ); } catch (e) { state.deleteInstanceRoleError = e; } }), new ScenarioOutput("deleteInstanceRoleResult", (state) => { if (state.deleteInstanceRoleError) { console.error(state.deleteInstanceRoleError); return MESSAGES.deleteInstanceRoleError.replace( "${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName, ); } else { return MESSAGES.deletedInstanceRole.replace( "${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName, ); } }), new ScenarioAction("deleteInstanceProfile", async (state) => { try { // snippet-start:[javascript.v3.wkflw.resilient.DeleteInstanceProfile] const client = new IAMClient({}); await client.send( new DeleteInstanceProfileCommand({ InstanceProfileName: NAMES.instanceProfileName, }), ); // snippet-end:[javascript.v3.wkflw.resilient.DeleteInstanceProfile] } catch (e) { state.deleteInstanceProfileError = e; } }), new ScenarioOutput("deleteInstanceProfileResult", (state) => { if (state.deleteInstanceProfileError) { console.error(state.deleteInstanceProfileError); return MESSAGES.deleteInstanceProfileError.replace( "${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName, ); } else { return MESSAGES.deletedInstanceProfile.replace( "${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName, ); } }), new ScenarioAction("deleteAutoScalingGroup", async (state) => { try { await terminateGroupInstances(NAMES.autoScalingGroupName); await retry({ intervalInMs: 60000, maxRetries: 60 }, async () => { await deleteAutoScalingGroup(NAMES.autoScalingGroupName); }); } catch (e) { state.deleteAutoScalingGroupError = e; } }), new ScenarioOutput("deleteAutoScalingGroupResult", (state) => { if (state.deleteAutoScalingGroupError) { console.error(state.deleteAutoScalingGroupError); return MESSAGES.deleteAutoScalingGroupError.replace( "${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName, ); } else { return MESSAGES.deletedAutoScalingGroup.replace( "${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName, ); } }), new ScenarioAction("deleteLaunchTemplate", async (state) => { const client = new EC2Client({}); try { // snippet-start:[javascript.v3.wkflw.resilient.DeleteLaunchTemplate] await client.send( new DeleteLaunchTemplateCommand({ LaunchTemplateName: NAMES.launchTemplateName, }), ); // snippet-end:[javascript.v3.wkflw.resilient.DeleteLaunchTemplate] } catch (e) { state.deleteLaunchTemplateError = e; } }), new ScenarioOutput("deleteLaunchTemplateResult", (state) => { if (state.deleteLaunchTemplateError) { console.error(state.deleteLaunchTemplateError); return MESSAGES.deleteLaunchTemplateError.replace( "${LAUNCH_TEMPLATE_NAME}", NAMES.launchTemplateName, ); } else { return MESSAGES.deletedLaunchTemplate.replace( "${LAUNCH_TEMPLATE_NAME}", NAMES.launchTemplateName, ); } }), new ScenarioAction("deleteLoadBalancer", async (state) => { try { // snippet-start:[javascript.v3.wkflw.resilient.DeleteLoadBalancer] const client = new ElasticLoadBalancingV2Client({}); const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName); await client.send( new DeleteLoadBalancerCommand({ LoadBalancerArn: loadBalancer.LoadBalancerArn, }), ); await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => { const lb = await findLoadBalancer(NAMES.loadBalancerName); if (lb) { throw new Error("Load balancer still exists."); } }); // snippet-end:[javascript.v3.wkflw.resilient.DeleteLoadBalancer] } catch (e) { state.deleteLoadBalancerError = e; } }), new ScenarioOutput("deleteLoadBalancerResult", (state) => { if (state.deleteLoadBalancerError) { console.error(state.deleteLoadBalancerError); return MESSAGES.deleteLoadBalancerError.replace( "${LB_NAME}", NAMES.loadBalancerName, ); } else { return MESSAGES.deletedLoadBalancer.replace( "${LB_NAME}", NAMES.loadBalancerName, ); } }), new ScenarioAction("deleteLoadBalancerTargetGroup", async (state) => { // snippet-start:[javascript.v3.wkflw.resilient.DeleteTargetGroup] const client = new ElasticLoadBalancingV2Client({}); try { const { TargetGroups } = await client.send( new DescribeTargetGroupsCommand({ Names: [NAMES.loadBalancerTargetGroupName], }), ); await retry({ intervalInMs: 1000, maxRetries: 30 }, () => client.send( new DeleteTargetGroupCommand({ TargetGroupArn: TargetGroups[0].TargetGroupArn, }), ), ); } catch (e) { state.deleteLoadBalancerTargetGroupError = e; } // snippet-end:[javascript.v3.wkflw.resilient.DeleteTargetGroup] }), new ScenarioOutput("deleteLoadBalancerTargetGroupResult", (state) => { if (state.deleteLoadBalancerTargetGroupError) { console.error(state.deleteLoadBalancerTargetGroupError); return MESSAGES.deleteLoadBalancerTargetGroupError.replace( "${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName, ); } else { return MESSAGES.deletedLoadBalancerTargetGroup.replace( "${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName, ); } }), new ScenarioAction("detachSsmOnlyRoleFromProfile", async (state) => { try { const client = new IAMClient({}); await client.send( new RemoveRoleFromInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, RoleName: NAMES.ssmOnlyRoleName, }), ); } catch (e) { state.detachSsmOnlyRoleFromProfileError = e; } }), new ScenarioOutput("detachSsmOnlyRoleFromProfileResult", (state) => { if (state.detachSsmOnlyRoleFromProfileError) { console.error(state.detachSsmOnlyRoleFromProfileError); return MESSAGES.detachSsmOnlyRoleFromProfileError .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName); } else { return MESSAGES.detachedSsmOnlyRoleFromProfile .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName); } }), new ScenarioAction("detachSsmOnlyCustomRolePolicy", async (state) => { try { const iamClient = new IAMClient({}); const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName); await iamClient.send( new DetachRolePolicyCommand({ RoleName: NAMES.ssmOnlyRoleName, PolicyArn: ssmOnlyPolicy.Arn, }), ); } catch (e) { state.detachSsmOnlyCustomRolePolicyError = e; } }), new ScenarioOutput("detachSsmOnlyCustomRolePolicyResult", (state) => { if (state.detachSsmOnlyCustomRolePolicyError) { console.error(state.detachSsmOnlyCustomRolePolicyError); return MESSAGES.detachSsmOnlyCustomRolePolicyError .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName); } else { return MESSAGES.detachedSsmOnlyCustomRolePolicy .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName); } }), new ScenarioAction("detachSsmOnlyAWSRolePolicy", async (state) => { try { const iamClient = new IAMClient({}); await iamClient.send( new DetachRolePolicyCommand({ RoleName: NAMES.ssmOnlyRoleName, PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", }), ); } catch (e) { state.detachSsmOnlyAWSRolePolicyError = e; } }), new ScenarioOutput("detachSsmOnlyAWSRolePolicyResult", (state) => { if (state.detachSsmOnlyAWSRolePolicyError) { console.error(state.detachSsmOnlyAWSRolePolicyError); return MESSAGES.detachSsmOnlyAWSRolePolicyError .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore"); } else { return MESSAGES.detachedSsmOnlyAWSRolePolicy .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName) .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore"); } }), new ScenarioAction("deleteSsmOnlyInstanceProfile", async (state) => { try { const iamClient = new IAMClient({}); await iamClient.send( new DeleteInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, }), ); } catch (e) { state.deleteSsmOnlyInstanceProfileError = e; } }), new ScenarioOutput("deleteSsmOnlyInstanceProfileResult", (state) => { if (state.deleteSsmOnlyInstanceProfileError) { console.error(state.deleteSsmOnlyInstanceProfileError); return MESSAGES.deleteSsmOnlyInstanceProfileError.replace( "${INSTANCE_PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName, ); } else { return MESSAGES.deletedSsmOnlyInstanceProfile.replace( "${INSTANCE_PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName, ); } }), new ScenarioAction("deleteSsmOnlyPolicy", async (state) => { try { const iamClient = new IAMClient({}); const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName); await iamClient.send( new DeletePolicyCommand({ PolicyArn: ssmOnlyPolicy.Arn, }), ); } catch (e) { state.deleteSsmOnlyPolicyError = e; } }), new ScenarioOutput("deleteSsmOnlyPolicyResult", (state) => { if (state.deleteSsmOnlyPolicyError) { console.error(state.deleteSsmOnlyPolicyError); return MESSAGES.deleteSsmOnlyPolicyError.replace( "${POLICY_NAME}", NAMES.ssmOnlyPolicyName, ); } else { return MESSAGES.deletedSsmOnlyPolicy.replace( "${POLICY_NAME}", NAMES.ssmOnlyPolicyName, ); } }), new ScenarioAction("deleteSsmOnlyRole", async (state) => { try { const iamClient = new IAMClient({}); await iamClient.send( new DeleteRoleCommand({ RoleName: NAMES.ssmOnlyRoleName, }), ); } catch (e) { state.deleteSsmOnlyRoleError = e; } }), new ScenarioOutput("deleteSsmOnlyRoleResult", (state) => { if (state.deleteSsmOnlyRoleError) { console.error(state.deleteSsmOnlyRoleError); return MESSAGES.deleteSsmOnlyRoleError.replace( "${ROLE_NAME}", NAMES.ssmOnlyRoleName, ); } else { return MESSAGES.deletedSsmOnlyRole.replace( "${ROLE_NAME}", NAMES.ssmOnlyRoleName, ); } }), ]; /** * @param {string} policyName */ async function findPolicy(policyName) { const client = new IAMClient({}); const paginatedPolicies = paginateListPolicies({ client }, {}); for await (const page of paginatedPolicies) { const policy = page.Policies.find((p) => p.PolicyName === policyName); if (policy) { return policy; } } } /** * @param {string} groupName */ async function deleteAutoScalingGroup(groupName) { const client = new AutoScalingClient({}); try { await client.send( new DeleteAutoScalingGroupCommand({ AutoScalingGroupName: groupName, }), ); } catch (err) { if (!(err instanceof Error)) { throw err; } else { console.log(err.name); throw err; } } } /** * @param {string} groupName */ async function terminateGroupInstances(groupName) { const autoScalingClient = new AutoScalingClient({}); const group = await findAutoScalingGroup(groupName); await autoScalingClient.send( new UpdateAutoScalingGroupCommand({ AutoScalingGroupName: group.AutoScalingGroupName, MinSize: 0, }), ); for (const i of group.Instances) { await retry({ intervalInMs: 1000, maxRetries: 30 }, () => autoScalingClient.send( new TerminateInstanceInAutoScalingGroupCommand({ InstanceId: i.InstanceId, ShouldDecrementDesiredCapacity: true, }), ), ); } } async function findAutoScalingGroup(groupName) { const client = new AutoScalingClient({}); const paginatedGroups = paginateDescribeAutoScalingGroups({ client }, {}); for await (const page of paginatedGroups) { const group = page.AutoScalingGroups.find( (g) => g.AutoScalingGroupName === groupName, ); if (group) { return group; } } throw new Error(`Auto scaling group ${groupName} not found.`); }

다음 코드 예제에서는 사용자를 생성하고 역할을 수임하는 방법을 보여줍니다.

주의

보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마십시오. 대신 AWS IAM Identity Center과 같은 자격 증명 공급자를 통한 페더레이션을 사용하세요.

  • 권한이 없는 사용자를 생성합니다.

  • 계정에 대한 Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할을 생성합니다.

  • 사용자가 역할을 수임할 수 있도록 정책을 추가합니다.

  • 역할을 수임하고 임시 보안 인증 정보를 사용하여 S3 버킷을 나열한 후 리소스를 정리합니다.

JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할과 IAM 사용자를 생성합니다. 사용자는 역할을 수임할 수 있는 권한만 있습니다. 역할을 수임한 후 임시 자격 증명을 사용하여 계정의 버킷을 나열합니다.

import { CreateUserCommand, CreateAccessKeyCommand, CreatePolicyCommand, CreateRoleCommand, AttachRolePolicyCommand, DeleteAccessKeyCommand, DeleteUserCommand, DeleteRoleCommand, DeletePolicyCommand, DetachRolePolicyCommand, IAMClient, } from "@aws-sdk/client-iam"; import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts"; import { retry } from "@aws-sdk-examples/libs/utils/util-timers.js"; // Set the parameters. const iamClient = new IAMClient({}); const userName = "test_name"; const policyName = "test_policy"; const roleName = "test_role"; export const main = async () => { // Create a user. The user has no permissions by default. const { User } = await iamClient.send( new CreateUserCommand({ UserName: userName }), ); if (!User) { throw new Error("User not created"); } // Create an access key. This key is used to authenticate the new user to // Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS). // It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/. const createAccessKeyResponse = await iamClient.send( new CreateAccessKeyCommand({ UserName: userName }), ); if ( !createAccessKeyResponse.AccessKey?.AccessKeyId || !createAccessKeyResponse.AccessKey?.SecretAccessKey ) { throw new Error("Access key not created"); } const { AccessKey: { AccessKeyId, SecretAccessKey }, } = createAccessKeyResponse; let s3Client = new S3Client({ credentials: { accessKeyId: AccessKeyId, secretAccessKey: SecretAccessKey, }, }); // Retry the list buckets operation until it succeeds. InvalidAccessKeyId is // thrown while the user and access keys are still stabilizing. await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => { try { return await listBuckets(s3Client); } catch (err) { if (err instanceof Error && err.name === "InvalidAccessKeyId") { throw err; } } }); // Retry the create role operation until it succeeds. A MalformedPolicyDocument error // is thrown while the user and access keys are still stabilizing. const { Role } = await retry( { intervalInMs: 2000, maxRetries: 60, }, () => iamClient.send( new CreateRoleCommand({ AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { // Allow the previously created user to assume this role. AWS: User.Arn, }, Action: "sts:AssumeRole", }, ], }), RoleName: roleName, }), ), ); if (!Role) { throw new Error("Role not created"); } // Create a policy that allows the user to list S3 buckets. const { Policy: listBucketPolicy } = await iamClient.send( new CreatePolicyCommand({ PolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: ["s3:ListAllMyBuckets"], Resource: "*", }, ], }), PolicyName: policyName, }), ); if (!listBucketPolicy) { throw new Error("Policy not created"); } // Attach the policy granting the 's3:ListAllMyBuckets' action to the role. await iamClient.send( new AttachRolePolicyCommand({ PolicyArn: listBucketPolicy.Arn, RoleName: Role.RoleName, }), ); // Assume the role. const stsClient = new STSClient({ credentials: { accessKeyId: AccessKeyId, secretAccessKey: SecretAccessKey, }, }); // Retry the assume role operation until it succeeds. const { Credentials } = await retry( { intervalInMs: 2000, maxRetries: 60 }, () => stsClient.send( new AssumeRoleCommand({ RoleArn: Role.Arn, RoleSessionName: `iamBasicScenarioSession-${Math.floor( Math.random() * 1000000, )}`, DurationSeconds: 900, }), ), ); if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) { throw new Error("Credentials not created"); } s3Client = new S3Client({ credentials: { accessKeyId: Credentials.AccessKeyId, secretAccessKey: Credentials.SecretAccessKey, sessionToken: Credentials.SessionToken, }, }); // List the S3 buckets again. // Retry the list buckets operation until it succeeds. AccessDenied might // be thrown while the role policy is still stabilizing. await retry({ intervalInMs: 2000, maxRetries: 60 }, () => listBuckets(s3Client), ); // Clean up. await iamClient.send( new DetachRolePolicyCommand({ PolicyArn: listBucketPolicy.Arn, RoleName: Role.RoleName, }), ); await iamClient.send( new DeletePolicyCommand({ PolicyArn: listBucketPolicy.Arn, }), ); await iamClient.send( new DeleteRoleCommand({ RoleName: Role.RoleName, }), ); await iamClient.send( new DeleteAccessKeyCommand({ UserName: userName, AccessKeyId, }), ); await iamClient.send( new DeleteUserCommand({ UserName: userName, }), ); }; /** * * @param {S3Client} s3Client */ const listBuckets = async (s3Client) => { const { Buckets } = await s3Client.send(new ListBucketsCommand({})); if (!Buckets) { throw new Error("Buckets not listed"); } console.log(Buckets.map((bucket) => bucket.Name).join("\n")); };