Claude Codeで1Password管理のAWS認証情報を用いてAWSの操作をする方法

Claude Codeで1Password管理のAWS認証情報を用いてAWSの操作をする方法

Claude CodeにAWSの認証情報を渡すには一工夫が必要
Clock Icon2025.07.01

1Password CLIでAWSの認証情報を管理している環境にて、Claude Codeのセッション内でAWS CLIやAWS CDKの操作をしたい

こんにちは、のんピ(@non____97)です。

皆さんは1Password CLIでAWSの認証情報を管理している環境にて、Claude Codeのセッション内でAWS CLIやAWS CDKの操作をしたいなと思ったことはありますか? 私はあります。

AIエージェントを介してAWS操作をするときに気になる要素の一つに認証情報の渡し方があります。

以下記事で紹介されているとおり、Claude Codeのセッション内で認証情報を渡すのは一工夫必要そうです。

https://dev.classmethod.jp/articles/claude-code-switch-role/

上述の記事ではAWSumeを使っています。

私は以下記事で紹介しているように1Password CLIユーザーです。

https://dev.classmethod.jp/articles/1password-shell-plugins-aws-cli-cdk/

1Password CLI固有の要素があるのか確認してみましょう。

いきなりまとめ

  • Claude Code上でインタラクティブな入力は受け付けられない
  • 対応方法としては以下の2パターンがある
    1. 事前に認証情報を .claude/settings.local.json にセットする
    2. Claude Codeのセッション内で .claude/settings.local.json にセットする
  • 前者は少し手間だが、トークン数を節約したいのであれば前者が良さそう

Claude Codeのセッションの中で1Password CLIのShell PluginsでAWS CLIを操作しようとしてみる

まずは純粋にClaude Codeのセッションの中で1Password CLIのShell PluginsでAWS CLIを操作しようとしてみます。

以下のようなプロンプトを渡します。

> `op plugin run -- aws sts get-caller-identity` を実行してください。

すると、Touch IDによる認証が求められました。

1.1Password.png

認証をして、しばらくすると、interactive IO not availableとエラーになりました。

> `op plugin run -- aws sts get-caller-identity` を実行してください。

⏺ Bash(op plugin run -- aws sts get-caller-identity)
  ⎿  Error: [ERROR] 2025/07/01 11:02:17 interactive IO not available

⏺ Bash(op --version)2.31.1

⏺ Bash(op plugin list)
  ⎿  EXECUTABLE         NAME                  REQUIRED FIELDS
     akamai             Akamai                Client Secret, Host, Access Token, Client Token
     argocd             Argo CD               Auth Token
     … +63 lines (ctrl+r to expand)

⏺ 1Password プラグインでAWSが利用可能ですが、インタラクティブモードが無効なため認証できません。通常のAWS CLIで実行してみます。

⏺ Bash(aws sts get-caller-identity)
  ⎿  Error: /opt/homebrew/Cellar/python@3.13/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/getpass.py:90: GetPassWarning: Can not control echo on the terminal.
       passwd = fallback_getpass(prompt, stream)
     Warning: Password input may be echoed.
     Enter MFA code for arn:aws:iam::<IAMユーザーのAWSアカウントID>:mfa/<MFAデバイス名>:

⏺ MFA認証が必要です。1Passwordプラグインを使用するか、AWS認証情報を設定する必要があります。

これは1Password CLIのShell PluginsでAWS CLIを操作する際に使用する認証情報として、1Password上のどのアイテムを使用するのかを選択するときの入力です。

また、op plugin runには特に1Passwordのアイテムを渡すオプションは存在しません。

>  op plugin run --help
Provision credentials from 1Password and run this command.

'op plugin run' passes your credentials saved in 1Password to the
underlying CLI and runs the provided command. If you haven't configured
your default credentials, 1Password CLI will prompt you to select an
item that contains your credentials.

After this, you will be automagically authenticated with this CLI, and your
selection will be recorded for future calls to this plugin in the current
terminal session.

To configure a default credential, see 'op plugin init --help'.

Usage:  op plugin run <command>... [flags]

Flags:
  -h, --help   help for run

To list the global flags available on every command, run  'op --help'.

そのため、普通に1Password CLIのShell PluginsでAWS CLIを操作するのは出来なさそうです。

1Password CLIのShell PluginsでAWS CLIの認証をした後にClaude CodeのセッションからAWS CLIの操作をしてみる

続いて、1Password CLIのShell PluginsでAWS CLIの認証をした後にClaude CodeのセッションからAWS CLIの操作をしてみます。

まず、ターミナルの通常のセッションで以下のように実行します。

>  aws sts get-caller-identity
? Locate your AWS Access Key: AWS - Classmethod  (Employee) - <IAMユーザー名>

{
    "UserId": "AROA6KUFAVPUZTMI6DMFH:<IAMユーザー名>",
    "Account": "<Assum Role先AWSアカウントID>",
    "Arn": "arn:aws:sts::<Assum Role先AWSアカウントID>:assumed-role/<IAMロール名>/<セッション名>"
}

問題なく、実行できましたね。

途中Locate your AWS Access Keyの前段で、Touch IDによる認証が求められました。

1.1Password.png

続いて、Claude Codeのセッション内でop plugin run -- aws sts get-caller-identityを実行します。

> op plugin run -- aws sts get-caller-identity

⏺ Bash(op plugin run -- aws sts get-caller-identity)
  ⎿  Error: [ERROR] 2025/07/01 11:41:47 interactive IO not available

⏺ 1Password CLIプラグインでインタラクティブ認証ができない状況です。別の方法でAWS認証を設定する必要があります。

やはりダメですね。

aws sts get-caller-identityも実行します。

> aws sts get-caller-identity

⏺ Bash(aws sts get-caller-identity)
  ⎿  Error: /opt/homebrew/Cellar/python@3.13/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/getpass.py:90: GetPassWarning: Can not control echo on the terminal.
       passwd = fallback_getpass(prompt, stream)
     Warning: Password input may be echoed.
     Enter MFA code for arn:aws:iam::<IAMユーザーのAWSアカウントID>:mfa/<MFAデバイス名>:

⏺ MFAコードの入力が必要です。MFAコードを入力してください。

こちらももちろんできませんした。

事前に認証情報を .claude/settings.local.json にセットする

解決策を考えます。

まず挙げられるのは事前に認証情報を.claude/settings.local.jsonにセットすることです。

.claude/settings.local.jsonに環境変数を設定することで、Claude Codeのセッションの中で読み取ってくれます。

具体的には以下のような処理を実行することになります。

$ mkdir -p .claude && \
    aws configure export-credentials | \
    jq '{permissions: {allow: [], deny: []}, env: {AWS_ACCESS_KEY_ID: .AccessKeyId, AWS_SECRET_ACCESS_KEY: .SecretAccessKey, AWS_SESSION_TOKEN: .SessionToken}}' > .claude/settings.local.json

実際に実行しましょう。

>  mkdir -p .claude && \
    aws configure export-credentials | \
    jq '{permissions: {allow: [], deny: []}, env: {AWS_ACCESS_KEY_ID: .AccessKeyId, AWS_SECRET_ACCESS_KEY: .SecretAccessKey, AWS_SESSION_TOKEN: .SessionToken}}' > .claude/settings.local.json

>  ls -l .claude/settings.local.json
-rw-r--r--@ 1 <ユーザー名>  staff  993  7  1 11:48 .claude/settings.local.json

>  cat .claude/settings.local.json
{
  "permissions": {
    "allow": [],
    "deny": []
  },
  "env": {
    "AWS_ACCESS_KEY_ID": "<アクセスキー>",
    "AWS_SECRET_ACCESS_KEY": "<シークレットアクセスキー>",
    "AWS_SESSION_TOKEN": "<セッショントークン>"
  }
}

認証情報がセットされていますね。

Claude CodeのセッションでAWS関連の環境変数を確認します。

! env | grep AWS
  ⎿ AWS_PROFILE=<プロファイル名>
    AWS_DEFAULT_REGION=us-east-1
    AWS_DEFAULT_PROFILE=<プロファイル名>
    AWS_DEFAULT_OUTPUT=json
    AWS_CLI_AUTO_PROMPT=on-partial
    AWS_PAGER=
    AWS_ACCESS_KEY_ID=<アクセスキー>
    AWS_SECRET_ACCESS_KEY=<シークレットアクセスキー>
    AWS_SESSION_TOKEN=<セッショントークン>

環境変数がセットされていますね。

この状態でAWS CLIを叩けられるか確認します。

> `aws sts get-caller-identity`を実行してください。

⏺ Bash(aws sts get-caller-identity){
         "UserId": "AROA6KUFAVPUZTMI6DMFH:<IAMユーザー名>",
         "Account": "<Assum Role先AWSアカウントID>",
         "Arn": "arn:aws:sts::<Assum Role先AWSアカウントID>:assumed-role/<IAMロール名>/<セッション名>"
     }

11:53

⏺ 現在のAWS認証情報:
  - アカウントID: <Assum Role先AWSアカウントID>
  - ユーザー: <IAMユーザー名> (assumed-role)
  - リージョン: us-east-1

はい、問題なくできました。

毎回このコマンドをコピペで入力するのも手間なので、エイリアスを設定しておくと良いでしょう。

私は以下のように設定しています。

alias export-aws-credential-to-claude='mkdir -p .claude && \
  aws configure export-credentials | \
  jq '\''{permissions: {allow: [], deny: []}, env: {AWS_ACCESS_KEY_ID: .AccessKeyId, AWS_SECRET_ACCESS_KEY: .SecretAccessKey, AWS_SESSION_TOKEN: .SessionToken}}'\'' > .claude/settings.local.json'

Claude Codeのセッション内で .claude/settings.local.json にセットする

毎回毎回Claude Codeを実行する前に認証情報をセットするのも面倒です。

できることならClaaude Codeのセッション内で認証情報をセットしたいです。

ということで、CLAUDE.mdにその指示を記載しましょう。

CLAUDE.md
## AWS Authentication

### Claude Code Session Limitations

Claude's code execution environment has specific constraints:
- Each Bash command runs in an isolated session
- Environment variables don't persist between commands
- Standard `export` commands won't work across different code blocks

### Solution: Environment Configuration Method

This approach stores AWS credentials in Claude's local settings file, allowing them to be loaded on-demand for each command.

#### Step 1: Setup Credentials Storage

```bash
# Extract AWS credentials from 1Password and store in Claude settings
# This command handles both new files and updates to existing configurations
expect -c "
  set timeout 30
  spawn bash -c \
    {mkdir -p .claude && \
     existing=\$(cat .claude/settings.local.json 2>/dev/null || echo '{}') && \
     op plugin run -- aws configure export-credentials | \
     jq --argjson existing \"\$existing\" \
     '. as \$creds | \$existing | .env.AWS_ACCESS_KEY_ID = \$creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = \$creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = \$creds.SessionToken | if has(\"permissions\") | not then .permissions = {allow: [], deny: []} else . end' \
     > .claude/settings.local.json}
  expect {
      {*AWS - Classmethod*} {
          send \"\\r\"
          exp_continue
      }
      eof
  }
"
\```

#### Step 2: Secure the Credentials (IMPORTANT)

```bash
# Prevent credentials from being committed to version control
# These commands check for existing entries before adding to avoid duplicates
grep -qxF ".claude/settings.local.json" .gitignore || echo ".claude/settings.local.json" >> .gitignore
grep -qxF ".op" .gitignore || echo ".op" >> .gitignore
\```

#### Step 3: Usage Patterns

For first-time authentication in a session:

```bash
# Load AWS credentials from Claude settings if not already set, then verify with STS
# If this fails with "No such file" or authentication errors, run Step 1 first
source <(jq -r '.env | to_entries[] | "export \(.key)=\(.value)"' .claude/settings.local.json) && \
  aws sts get-caller-identity
\```

IMPORTANT: After updating credentials in Step 1:

```bash
# Always reload credentials after running Step 1 - old environment variables persist
# Do NOT use 'aws sts get-caller-identity' directly after credential updates
source <(jq -r '.env | to_entries[] | "export \(.key)=\(.value)"' .claude/settings.local.json) && \
  aws sts get-caller-identity
\```

For subsequent AWS commands (when credentials are loaded AND you haven't updated .claude/settings.local.json in this session):

```bash
# Use AWS CLI directly - only when no credential updates occurred in current session
aws sts get-caller-identity
\```

**Troubleshooting**: If the above command fails with:

- `No such file or directory`: Run Step 1 to create the credentials file
- `Invalid credentials` or `ExpiredToken`: Run Step 1 to refresh expired credentials

**CRITICAL**: Environment Variable Persistence

- Claude remembers environment variables throughout the entire session
- Updating `.claude/settings.local.json` does NOT automatically update environment variables
- You MUST explicitly reload credentials after any Step 1 execution
- Using `aws sts get-caller-identity` directly after Step 1 will use OLD credentials

### How It Works

1. **Credential Extraction**: Uses 1Password CLI to get temporary AWS credentials
2. **Storage**: Saves credentials in `.claude/settings.local.json` with proper Claude format
3. **Loading**: Sources credentials into environment variables when needed
4. **Verification**: Confirms authentication with AWS STS

### Security Notes

- Credentials are temporary and will expire
- Files are automatically excluded from git commits
- Each session requires fresh credential loading due to Claude's isolation

以下が一番のキモです。

expect -c "
  set timeout 30
  spawn bash -c \
    {mkdir -p .claude && \
     existing=\$(cat .claude/settings.local.json 2>/dev/null || echo '{}') && \
     op plugin run -- aws configure export-credentials | \
     jq --argjson existing \"\$existing\" \
     '. as \$creds | \$existing | .env.AWS_ACCESS_KEY_ID = \$creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = \$creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = \$creds.SessionToken | if has(\"permissions\") | not then .permissions = {allow: [], deny: []} else . end' \
     > .claude/settings.local.json}
  expect {
      {*AWS - Classmethod*} {
          send \"\\r\"
          exp_continue
      }
      eof
  }
"

expectを用いて、1Passwordのアイテムを選択をしています。これでインタラクティブな入力ができない問題を回避しています。

コマンド内の*AWS - Classmethod*が1Passwordのアイテム名になります。

また、既に.claude/settings.local.jsonが存在している場合もあるでしょう。その場合は、.envのみを上書きするようにしています。

こちらの動作確認の内容は以下のとおりです。

.claude/settings.local.json が既に存在している場合
>  cat .claude/settings.local.json
{
  "permissions": {
    "allow": [
      "Bash(aws:*)"
    ],
    "deny": [
      "Bash(rm:*)"
    ]
  }
}

>  expect -c "
    set timeout 30
    spawn bash -c \
      {mkdir -p .claude && \
      existing=\$(cat .claude/settings.local.json 2>/dev/null || echo '{}') && \
      op plugin run -- aws configure export-credentials | \
      jq --argjson existing \"\$existing\" \
      '. as \$creds | \$existing | .env.AWS_ACCESS_KEY_ID = \$creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = \$creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = \$creds.SessionToken | if has(\"permissions\") | not then .permissions = {allow: [], deny: []} else . end' \
      > .claude/settings.local.json}
    expect {
        {*AWS - Classmethod*} {
            send \"\\r\"
            exp_continue
        }
        eof
    }
  "
spawn bash -c mkdir -p .claude &&      existing=$(cat .claude/settings.local.json 2>/dev/null || echo '{}') &&      op plugin run -- aws configure export-credentials |      jq --argjson existing "$existing"      '. as $creds | $existing | .env.AWS_ACCESS_KEY_ID = $creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = $creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = $creds.SessionToken | if has("permissions") | not then .permissions = {allow: [], deny: []} else . end'      > .claude/settings.local.json
? Locate your AWS Access Key:  [Use arrows to move, type to filter, ? for more help]
? Locate your AWS Access Key: AWS - Classmethod  (Employee) - <IAMユーザー名>

# permissions は変更されず、env の AWS_ACCESS_KEY_ID や AWS_SECRET_ACCESS_KEY などが設定されていることを確認
>  cat .claude/settings.local.json
{
  "permissions": {
    "allow": [
      "Bash(aws:*)"
    ],
    "deny": [
      "Bash(rm:*)"
    ]
  },
  "env": {
    "AWS_ACCESS_KEY_ID": "ASIA6KUFAVPUVZPEYPE3",
    "AWS_SECRET_ACCESS_KEY": "<シークレットアクセスキー>",
    "AWS_SESSION_TOKEN": "<セッショントークン>"
  }
}
時間を空けて再実行した場合
>  expect -c "
    set timeout 30
    spawn bash -c \
      {mkdir -p .claude && \
      existing=\$(cat .claude/settings.local.json 2>/dev/null || echo '{}') && \
      op plugin run -- aws configure export-credentials | \
      jq --argjson existing \"\$existing\" \
      '. as \$creds | \$existing | .env.AWS_ACCESS_KEY_ID = \$creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = \$creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = \$creds.SessionToken | if has(\"permissions\") | not then .permissions = {allow: [], deny: []} else . end' \
      > .claude/settings.local.json}
    expect {
        {*AWS - Classmethod*} {
            send \"\\r\"
            exp_continue
        }
        eof
    }
  "
spawn bash -c mkdir -p .claude &&      existing=$(cat .claude/settings.local.json 2>/dev/null || echo '{}') &&      op plugin run -- aws configure export-credentials |      jq --argjson existing "$existing"      '. as $creds | $existing | .env.AWS_ACCESS_KEY_ID = $creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = $creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = $creds.SessionToken | if has("permissions") | not then .permissions = {allow: [], deny: []} else . end'      > .claude/settings.local.json
? Locate your AWS Access Key:  [Use arrows to move, type to filter, ? for more help]
? Locate your AWS Access Key: AWS - Classmethod  (Employee) - <IAMユーザー名>

# env の AWS_ACCESS_KEY_ID や AWS_SECRET_ACCESS_KEY のみが更新されていることを確認
>  cat .claude/settings.local.json
{
  "permissions": {
    "allow": [
      "Bash(aws:*)"
    ],
    "deny": [
      "Bash(rm:*)"
    ]
  },
  "env": {
    "AWS_ACCESS_KEY_ID": "ASIA6KUFAVPU273XJQOT",
    "AWS_SECRET_ACCESS_KEY": "<シークレットアクセスキー>",
    "AWS_SESSION_TOKEN": "<セッショントークン>"
  }
}
.claude/settings.local.json が存在しない場合
>  rm .claude/settings.local.json

>  expect -c "
    set timeout 30
    spawn bash -c \
      {mkdir -p .claude && \
      existing=\$(cat .claude/settings.local.json 2>/dev/null || echo '{}') && \
      op plugin run -- aws configure export-credentials | \
      jq --argjson existing \"\$existing\" \
      '. as \$creds | \$existing | .env.AWS_ACCESS_KEY_ID = \$creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = \$creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = \$creds.SessionToken | if has(\"permissions\") | not then .permissions = {allow: [], deny: []} else . end' \
      > .claude/settings.local.json}
    expect {
        {*AWS - Classmethod*} {
            send \"\\r\"
            exp_continue
        }
        eof
    }
  "
spawn bash -c mkdir -p .claude &&      existing=$(cat .claude/settings.local.json 2>/dev/null || echo '{}') &&      op plugin run -- aws configure export-credentials |      jq --argjson existing "$existing"      '. as $creds | $existing | .env.AWS_ACCESS_KEY_ID = $creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = $creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = $creds.SessionToken | if has("permissions") | not then .permissions = {allow: [], deny: []} else . end'      > .claude/settings.local.json
? Locate your AWS Access Key:  [Use arrows to move, type to filter, ? for more help]
? Locate your AWS Access Key: AWS - Classmethod  (Employee) - <IAMユーザー名>


>  cat .claude/settings.local.json
{
  "env": {
    "AWS_ACCESS_KEY_ID": "ASIA6KUFAVPU273XJQOT",
    "AWS_SECRET_ACCESS_KEY": "<シークレットアクセスキー>",
    "AWS_SESSION_TOKEN": "<セッショントークン>"
  },
  "permissions": {
    "allow": [],
    "deny": []
  }
}

実際にClaude Codeで指示してみましょう。なお、.claude/settings.local.jsonは存在しない状態です。

> 現在のAWSの認証情報を教えてください

⏺ Bash(source <(jq -r '.env | to_entries[] | "export \(.key)=\(.value)"' .claude/settings.local.json) && aws sts get-caller-identity)
  ⎿  Error: jq: error: Could not open file .claude/settings.local.json: No such file or directory
     /opt/homebrew/Cellar/python@3.13/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/getpass.py:90: GetPassWarning: Can not control echo on the terminal.
       passwd = fallback_getpass(prompt, stream)
     Warning: Password input may be echoed.
     Enter MFA code for arn:aws:iam::<IAMユーザーのAWSアカウントID>:mfa/<MFAデバイス名>:

⏺ 認証情報の設定が必要です。まず設定を行います。

⏺ Bash(expect -c "
        set timeout 30…)
  ⎿ spawn bash -c mkdir -p .claude &&      existing=$(cat .claude/settings.local.json 2>/dev/null || echo '{}') &&      op plugin run -- aws configure export-credentials |      jq --argjson exist
    ing "$existing"      '. as $creds | $existing | .env.AWS_ACCESS_KEY_ID = $creds.AccessKeyId | .env.AWS_SECRET_ACCESS_KEY = $creds.SecretAccessKey | .env.AWS_SESSION_TOKEN = $creds.SessionToke
    n | if has("permissions") | not then .permissions = {allow: [], deny: []} else . end'      > .claude/settings.local.json
    … +7 lines (ctrl+r to expand)



⏺ Bash(grep -qxF ".claude/settings.local.json" .gitignore || echo ".claude/settings.local.json" >> .gitignore)
  ⎿  (No content)

⏺ Bash(source <(jq -r '.env | to_entries[] | "export \(.key)=\(.value)"' .claude/settings.local.json) && aws sts get-caller-identity)
  ⎿  {
         "UserId": "AROA6KUFAVPUZTMI6DMFH:<IAMユーザー名>",
         "Account": "<Assum Role先AWSアカウントID>",
     … +2 lines (ctrl+r to expand)

⏺ 現在のAWS認証情報:

  - ユーザーID: <IAMユーザー名>
  - アカウント: <Assum Role先AWSアカウントID>
  - ロール: <IAMロール名>
  - ARN: arn:aws:sts::<Assum Role先AWSアカウントID>:assumed-role/<IAMロール名>/<セッション名>

  認証は正常に完了しています。

CLAUDE.mdで指示したとおりに認証情報を取得して、コマンドを実行できました。

VPCのNameタグ一覧でも教えてもらいましょう。

> バージニア北部リージョンの各VPCのNameタグを教えてください。

⏺ Bash(aws ec2 describe-vpcs --region us-east-1 --query 'Vpcs[*].{VpcId:VpcId,Name:Tags[?Key==`Name`].Value|[0]}' --output table)
  ⎿  Error: /opt/homebrew/Cellar/python@3.13/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/getpass.py:90: GetPassWarning: Can not control echo on the terminal.
       passwd = fallback_getpass(prompt, stream)
     Warning: Password input may be echoed.
     Enter MFA code for arn:aws:iam::<IAMユーザーのAWSアカウントID>:mfa/<MFAデバイス名>:

⏺ 認証情報が期限切れのため、1PasswordからAWS認証情報を更新します。

⏺ Bash(expect -c "
        set timeout 30)
  ⎿  No (tell Claude what to do differently)

先ほど認証情報を取得したばかりにも関わらず、souceコマンドを実行せずにAWS CLIを叩いてエラーになっています。

.claude/settings.local.json内の環境変数の更新をしても、Claude Codeの接続中には影響を与えません。

! env | grep AWS_ACCESS_KEY_ID
  ⎿  (No content)

そのため、認証情報を更新した接続ではsouce.claude/settings.local.jsonを実行する必要があります。

実際に指示しましょう。

> 認証情報はまだ切れていません。sourceコマンドを用いて認証情報を読み込んでください。

⏺ CLAUDE.mdの指示に従って、認証情報を環境変数に読み込みます。

⏺ Bash(source <(jq -r '.env | to_entries[] | "export \(.key)=\(.value)"' .claude/settings.local.json) && aws ec2 describe-vpcs --region us-east-1 --query 'Vpcs[*].{Vpc…)
  ⎿  --------------------------------------------
     |               DescribeVpcs               |
     +----------------+-------------------------+
     … +10 lines (ctrl+r to expand)

⏺ バージニア北部リージョン(us-east-1)のVPCのNameタグ:

  - a-vpc (vpc-07a0a78e0fe1d581c)
  - test-A-vpc (vpc-0d54cbe88a44ffd04)
  - c-vpc (vpc-0816a238d4f2e114e)
  - b-vpc (vpc-0ea4c2c1688c06aea)
  - FsxnStack/VPC (vpc-08b84da1f793ed513)
  - dx-test-vpc (vpc-0517e49e397a0c7da)
  - Nameタグなし (vpc-0e0796981cea634c1)

今度は正常に実行できました。

一度セッションを切って、claude -cで再度最新セッションの続きから操作をします。

! env | grep AWS_ACCESS_KEY_ID
  ⎿  AWS_ACCESS_KEY_ID=ASIA6KUFAVPU4CKCYFGN

> バージニア北部リージョンの各VPCのNameタグを教えてください。

⏺ Bash(aws ec2 describe-vpcs --region us-east-1 --query 'Vpcs[*].{VpcId:VpcId,Name:Tags[?Key==`Name`].Value|[0]}' --output table)
  ⎿  --------------------------------------------
     |               DescribeVpcs               |
     +----------------+-------------------------+
     … +10 lines (ctrl+r to expand)

⏺ バージニア北部リージョン(us-east-1)のVPCのNameタグ:

  - a-vpc (vpc-07a0a78e0fe1d581c)
  - test-A-vpc (vpc-0d54cbe88a44ffd04)
  - c-vpc (vpc-0816a238d4f2e114e)
  - b-vpc (vpc-0ea4c2c1688c06aea)
  - FsxnStack/VPC (vpc-08b84da1f793ed513)
  - dx-test-vpc (vpc-0517e49e397a0c7da)
  - Nameタグなし (vpc-0e0796981cea634c1)

正常に実行できましたね。

Claude CodeにAWSの認証情報を渡すには一工夫が必要

Claude Codeで1Password管理のAWS認証情報を用いて操作する方法を紹介しました。

  1. 事前に認証情報を.claude/settings.local.jsonにセットする
  2. Claude Codeのセッション内で.claude/settings.local.jsonにセットする

の2パターンを紹介しましたが、個人的には前者推しです。

前者は少し手間でああるのですが、後者はClaude Codeとやりとりが発生するので、それなりにトークン数がかかります。また、意外と指示どおり動いていないこともありました。

この記事が誰かの助けになれば幸いです。

以上、クラウド事業本部 コンサルティング部の のんピ(@non____97)でした!

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.