Меню Закрыть

Использование секретов для разработки

Аутентификация методом Userpass

Этот простой способ предлагает аутентификацию пользователя с помощью логина и пароля

Для разделения выполнения команд от root токена или от имени пользователя команды будут помечаться root:# и user:$ префиксами

Для начала включим данный метод

root:# vault auth enable userpass 

Success! Enabled userpass auth method at: userpass/

Посмотрим список включенных методов

root:# vault auth list 
Path         Type        Accessor                  Description                Version
----         ----        --------                  -----------                -------
token/       token       auth_token_6677e5e1       token based credentials    n/a
userpass/    userpass    auth_userpass_733e427e    n/a                        n/a

Добавление пользователя test_user с паролем test_password

root:# vault write auth/userpass/users/test_user password=test_password

Success! Data written to: auth/userpass/users/test_user

Просмотр всех добавленных пользователей

root:# vault list auth/userpass/users/

Keys
----
test
test_user
username

Войдем под пользователем с использованием логина и пароля

user:# vault login -method=userpass username=test_user

Password (will be hidden): 
Success! You are now authenticated. The token information displayed below
is already stored in the token helper. You do NOT need to run "vault login"
again. Future Vault requests will automatically use this token.

Key                    Value
---                    -----
token                  hvs.CAESINZOw2IF4iMInUtkcsWbXgZ6g4_y_IBn6LDjZEAfnnr-Gh4KHGh2cy5qTDFRWWNXUnRkc2xqN0lYNzJ1bDZtS1E
token_accessor         TqMmEOFjomEFOLXjNbqNViQn
token_duration         768h
token_renewable        true
token_policies         ["default"]
identity_policies      []
policies               ["default"]
token_meta_username    test_user

После выполнения команды токен сохраняется в файле $HOME/.vault-token и он будет использоваться для всех операций с vault

Просмотр информации о токене

user:$ vault token lookup

Key                 Value
---                 -----
accessor            TqMmEOFjomEFOLXjNbqNViQn
creation_time       1774341237
creation_ttl        768h
display_name        userpass-test_user
entity_id           07ea4bfc-2c03-51ec-5c1b-f4f969360eca
expire_time         2026-04-25T08:33:57.362358895Z
explicit_max_ttl    0s
id                  hvs.CAESINZOw2IF4iMInUtkcsWbXgZ6g4_y_IBn6LDjZEAfnnr-Gh4KHGh2cy5qTDFRWWNXUnRkc2xqN0lYNzJ1bDZtS1E
issue_time          2026-03-24T08:33:57.362371549Z
meta                map[username:test_user]
num_uses            0
orphan              true
path                auth/userpass/login/test_user
policies            [default]
renewable           true
ttl                 710h28m32s
type                service

Получаем доступ к секретам от имени пользователя

user:$ vault kv get -mount websites example.com

Error making API request.

URL: GET http://127.0.0.1:8200/v1/sys/internal/ui/mounts/websites
Code: 403. Errors:

* preflight capability check returned 403, please ensure client's policies grant access to path "websites/"

Доступ запрещен так как не заданы политики доступа к секретам. Создадим политику developer с правами чтение и просмотра секретов для раздела websites

root:# vault policy write developer - <<EOF
path "/websites/*" {
  capabilities = ["read", "list"]
}
EOF
Success! Uploaded policy: developer

Вывод списка политик

root:# vault policy list 

default
developer
root

Обновим политику пользователю test_user

root:# vault write auth/userpass/users/test_user policies="developer"

Success! Data written to: auth/userpass/users/test_user

После этого пользователь должен заново осуществить вход

user:$ vault login -method=userpass username=test_user

Password (will be hidden): 
Success! You are now authenticated. The token information displayed below
is already stored in the token helper. You do NOT need to run "vault login"
again. Future Vault requests will automatically use this token.

Key                    Value
---                    -----
token                  hvs.CAESIF5NqMYaZdMzjHl0NyhL9LkJysmxUir3Ke3DoTyZyfR7Gh4KHGh2cy5CTUZSZVhDaHhydjRGeGdFaFhGM0JtY2o
token_accessor         AJpbleArL7mTcS9ergRlH2cm
token_duration         768h
token_renewable        true
token_policies         ["default" "developer"]
identity_policies      []
policies               ["default" "developer"]
token_meta_username    test_user
user:$ vault kv get -mount websites example.com

====== Secret Path ======
websites/data/example.com

======= Metadata =======
Key                Value
---                -----
created_time       2026-03-21T09:17:32.051902245Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            10

======= Data =======
Key           Value
---           -----
app_secret    b24b8f493088610be8902beeb0f8f771
db_pass       eiy6eWaepaeYeecohsh1
db_user       example

Так же пользователя можно создать с указанием политики

root:# vault write auth/userpass/users/john password="SecurePass123" policies="developer"

Аутентификация методом AppRole

Данные метод рекомендуется для приложений и автоматизации. Использует пару RoleID и SecretID

Включаем данный метод аутентификации

root:# vault auth enable approle 

Success! Enabled approle auth method at: approle/

Список включенных методов

root:# vault auth list

Path         Type        Accessor                  Description                Version
----         ----        --------                  -----------                -------
approle/     approle     auth_approle_9a304a17     n/a                        n/a
token/       token       auth_token_6677e5e1       token based credentials    n/a
userpass/    userpass    auth_userpass_733e427e    n/a                        n/a

Создадим роль test_approle и дадим права доступа к секретам websites, использую ранее созданую политику developer

root:# vault write auth/approle/role/test_approle policies="developer"

Success! Data written to: auth/approle/role/test_approle

Просмотр существующих ролей

root:# vault list auth/approle/role/

Keys
----
test_approle

Просмотр конфигурации роли

root:# vault read auth/approle/role/test_approle

Key                        Value
---                        -----
alias_metadata             map[]
bind_secret_id             true
local_secret_ids           false
policies                   [developer]
secret_id_bound_cidrs      <nil>
secret_id_num_uses         0
secret_id_ttl              0s
token_bound_cidrs          []
token_explicit_max_ttl     0s
token_max_ttl              0s
token_no_default_policy    false
token_num_uses             0
token_period               0s
token_policies             [developer]
token_ttl                  0s
token_type                 default

Получаем RoleID

root:# vault read auth/approle/role/test_approle/role-id

Key        Value
---        -----
role_id    a013d767-0070-8de7-93f3-e88d0d7afd52

Создаем и получаем SecretID

root:# vault write -force auth/approle/role/test_approle/secret-id

Key                   Value
---                   -----
secret_id             1b7c4732-0193-de0f-0dc3-b0393af54e46
secret_id_accessor    139295f5-ddca-c26c-8ad8-317fe54af8f0
secret_id_num_uses    0
secret_id_ttl         0s

Просмотр секретов

root:# # vault list auth/approle/role/test_approle/secret-id

Keys
----
139295f5-ddca-c26c-8ad8-317fe54af8f0

Можно добавить несколько SecretID

root:# vault write -force auth/approle/role/test_approle/secret-id

Key                   Value
---                   -----
secret_id             3cd32d29-c56d-a8ad-5c84-4bc6cc265966
secret_id_accessor    014c40eb-d80f-17af-9a5c-7383178c1432
secret_id_num_uses    0
secret_id_ttl         0s
root:# vault list auth/approle/role/test_approle/secret-id

Keys
----
014c40eb-d80f-17af-9a5c-7383178c1432
139295f5-ddca-c26c-8ad8-317fe54af8f0

Просмотреть сами секреты не предоставляется возможным, так как vault не хранит секреты в открытом виде

Удаление SecretID

root:# vault delete auth/approle/role/test_approle/secret-id-accessor/destroy secret_id_accessor="014c40eb-d80f-17af-9a5c-7383178c1432"

Success! Data deleted (if it existed) at: auth/approle/role/test_approle/secret-id-accessor/destroy
root:# vault list auth/approle/role/test_approle/secret-id

Keys
----
139295f5-ddca-c26c-8ad8-317fe54af8f0

Аутенцификация через AppRole

user:$ $ vault write auth/approle/login \
    role_id="a013d767-0070-8de7-93f3-e88d0d7afd52" \
    secret_id="1b7c4732-0193-de0f-0dc3-b0393af54e46"

Key                     Value
---                     -----
token                   hvs.CAESIBNOm4JblhMZkGdmINgCj1HL00sIE_Hti-uVmQgRTX46Gh4KHGh2cy41MWR6dFZORHFmaE5EdkJOZGdRU3drRks
token_accessor          JoWbXL8CBLq41OowvWdCAy83
token_duration          768h
token_renewable         true
token_policies          ["default" "developer"]
identity_policies       []
policies                ["default" "developer"]
token_meta_role_name    test_approle

Получение секретов, используя токен

user:$ export VAULT_TOKEN="hvs.CAESIBNOm4JblhMZkGdmINgCj1HL00sIE_Hti-uVmQgRTX46Gh4KHGh2cy41MWR6dFZORHFmaE5EdkJOZGdRU3drRks"
user:$ vault kv get -mount websites example.com

====== Secret Path ======
websites/data/example.com

======= Metadata =======
Key                Value
---                -----
created_time       2026-03-21T09:17:32.051902245Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            10

======= Data =======
Key           Value
---           -----
app_secret    b24b8f493088610be8902beeb0f8f771
db_pass       eiy6eWaepaeYeecohsh1
db_user       example

Удаление роли

root:# vault delete auth/approle/role/test_approle

Success! Data deleted (if it existed) at: auth/approle/role/test_approle
root:# vault list auth/approle/role/

No value found at auth/approle/role

Подстановка секретов в конфигурационные файлы

userpass

Предварительно необходимо получить токен по методу userpass.

Создадим шаблон конфига .sample.env

{{ with secret "/websites/example.com" }}
APP_SECRET={{ .Data.data.app_secret }}
DB_USER={{ .Data.data.db_user }}
DB_PASS={{ .Data.data.db_pass }}
{{ end }}

И конфигурацию для агента vault config.hcl

pid_file = "./pidfile"

vault {
address = "http://127.0.0.1:8200"
}

auto_auth {
method {
type = "token_file"

config = {
token_file_path = "./.vault-token"
}
}
}
template {
source = ".sample.env"
destination = ".env"
error_on_missing_key = true
}

После выполнения команды агент создаст новый файл .env с подставленными секретами

user:$ vault agent -config=config.hcl -exit-after-auth

==> Vault Agent started! Log data will stream in below:

==> Vault Agent configuration:

           Api Address 1: http://bufconn
                     Cgo: disabled
               Log Level: 
                 Version: Vault v1.21.4, built 2026-03-04T17:40:05Z
             Version Sha: ffe7023c481dc1ea2d8550bbaca8d85f8e611e0b

2026-03-26T18:25:05.004Z [INFO]  agent.exec.server: starting exec server
2026-03-26T18:25:05.004Z [INFO]  agent.exec.server: no env templates or exec config, exiting
2026-03-26T18:25:05.004Z [INFO]  agent.auth.handler: starting auth handler
2026-03-26T18:25:05.004Z [INFO]  agent.auth.handler: authenticating
2026-03-26T18:25:05.005Z [INFO]  agent.sink.server: starting sink server
2026-03-26T18:25:05.006Z [INFO]  agent.template.server: starting template server
2026-03-26T18:25:05.006Z [INFO]  agent: (runner) creating new runner (dry: false, once: false)
2026-03-26T18:25:05.006Z [INFO]  agent.auth.handler: authentication successful, sending token to sinks
2026-03-26T18:25:05.006Z [INFO]  agent.auth.handler: starting renewal process
2026-03-26T18:25:05.006Z [INFO]  agent.sink.server: sink server stopped
2026-03-26T18:25:05.006Z [INFO]  agent: sinks finished, exiting
2026-03-26T18:25:05.007Z [INFO]  agent: (runner) creating watcher
2026-03-26T18:25:05.007Z [INFO]  agent.template.server: template server received new token
2026-03-26T18:25:05.007Z [INFO]  agent: (runner) stopping
2026-03-26T18:25:05.007Z [INFO]  agent: (runner) creating new runner (dry: false, once: false)
2026-03-26T18:25:05.007Z [INFO]  agent: (runner) creating watcher
2026-03-26T18:25:05.007Z [INFO]  agent: (runner) starting
2026-03-26T18:25:05.007Z [INFO]  agent.auth.handler: renewed auth token
2026-03-26T18:25:05.011Z [INFO]  agent: (runner) stopping
2026-03-26T18:25:05.011Z [INFO]  agent.template.server: template server stopped
2026-03-26T18:25:05.011Z [INFO]  agent.exec.server: exec server stopped
2026-03-26T18:25:05.011Z [INFO]  agent.auth.handler: shutdown triggered, stopping lifetime watcher
2026-03-26T18:25:05.011Z [INFO]  agent.auth.handler: auth handler stopped
2026-03-26T18:25:05.011Z [INFO]  agent: (runner) received finish

Посмотрим, что получилось

user:$ cat .env 

APP_SECRET=b24b8f493088610be8902beeb0f8f771
DB_USER=example
DB_PASS=eiy6eWaepaeYeecohsh1

approle

Создадим новый конфигурационный файл config-approle.hcl для агента

pid_file = "./pidfile"

vault {
address = "http://127.0.0.1:8200"
retry {
num_retries = 5
}
}

auto_auth {
method {
type = "approle"

config = {
role_id_file_path = "./vault_role_id"
secret_id_file_path = "./vault_secret_id"
remove_secret_id_file_after_reading = false
}
}
}

template_config {
exit_on_retry_failure = false
}

template {
source = ".sample.env"
destination = ".env"
error_on_missing_key = true
}

Запишем полученные ранее RoleID и SecretID

user:$ echo "a013d767-0070-8de7-93f3-e88d0d7afd52" > vault_role_id
user:$ echo "1b7c4732-0193-de0f-0dc3-b0393af54e46" > vault_secret_id

Как и в предыдущем методе, выполнив команду, подставим секреты в файл

user:$ vault agent -config=config-approle.hcl -exit-after-auth

==> Vault Agent started! Log data will stream in below:

==> Vault Agent configuration:

           Api Address 1: http://bufconn
                     Cgo: disabled
               Log Level: 
                 Version: Vault v1.21.4, built 2026-03-04T17:40:05Z
             Version Sha: ffe7023c481dc1ea2d8550bbaca8d85f8e611e0b

2026-04-05T10:29:16.185Z [INFO]  agent.exec.server: starting exec server
2026-04-05T10:29:16.185Z [INFO]  agent.template.server: starting template server
2026-04-05T10:29:16.185Z [INFO]  agent: (runner) creating new runner (dry: false, once: false)
2026-04-05T10:29:16.185Z [INFO]  agent.exec.server: no env templates or exec config, exiting
2026-04-05T10:29:16.185Z [INFO]  agent.auth.handler: starting auth handler
2026-04-05T10:29:16.186Z [INFO]  agent.auth.handler: authenticating
2026-04-05T10:29:16.185Z [INFO]  agent.sink.server: starting sink server
2026-04-05T10:29:16.186Z [INFO]  agent: (runner) creating watcher
2026-04-05T10:29:16.187Z [INFO]  agent.auth.handler: authentication successful, sending token to sinks
2026-04-05T10:29:16.187Z [INFO]  agent.sink.server: sink server stopped
2026-04-05T10:29:16.187Z [INFO]  agent: sinks finished, exiting
2026-04-05T10:29:16.187Z [INFO]  agent.auth.handler: starting renewal process
2026-04-05T10:29:16.187Z [INFO]  agent.template.server: template server received new token
2026-04-05T10:29:16.187Z [INFO]  agent: (runner) stopping
2026-04-05T10:29:16.187Z [INFO]  agent: (runner) creating new runner (dry: false, once: false)
2026-04-05T10:29:16.188Z [INFO]  agent: (runner) creating watcher
2026-04-05T10:29:16.188Z [INFO]  agent: (runner) starting
2026-04-05T10:29:16.189Z [INFO]  agent.auth.handler: renewed auth token
2026-04-05T10:29:16.192Z [INFO]  agent: (runner) stopping
2026-04-05T10:29:16.192Z [INFO]  agent.template.server: template server stopped
2026-04-05T10:29:16.192Z [INFO]  agent.auth.handler: shutdown triggered, stopping lifetime watcher
2026-04-05T10:29:16.192Z [INFO]  agent.auth.handler: auth handler stopped
2026-04-05T10:29:16.192Z [INFO]  agent.exec.server: exec server stopped
2026-04-05T10:29:16.192Z [INFO]  agent: (runner) received finish
user:$ cat .env

APP_SECRET=b24b8f493088610be8902beeb0f8f771
DB_USER=example
DB_PASS=eiy6eWaepaeYeecohsh1