hashicorp identity code example

Example: Identities entities in vault hashicorp

#Policy Permissions needed to go ahead with identity entity
 $ vault policy write base - << EOF
         path "secret/data/training_*" {
   capabilities = ["create", "read"]
} 
EOF

 $ vault policy write test - << EOF 
         path "secret/data/test" {
   capabilities = [ "create", "read", "update", "delete" ]
}
EOF

 $ vault policy write team-qa - << EOF
         path "secret/data/team-qa" {
   capabilities = [ "create", "read", "update", "delete" ]
}
EOF

#Create a user Bob with policy test
 $ vault write auth/userpass/users/bob password="training" policies="test"

# Create a user Bsmith with policy team-qa
 $ vault write auth/userpass/users/bsmith password="training" policies="team-qa"

# Locate the accessor column value for userpass path in the output of below command
 $ vault auth list -detailed
# Save output to a accessor.txt file
 $ vault auth list -format=json | jq -r '.["userpass/"].accessor' > accessor.txt
 
# Create entity bob-smith
 $ vault write identity/entity name="bob-smith" policies="base" \
        metadata=organization="ACME Inc." \
        metadata=team="QA"
#From above command note the generated ID as its the canonical ID used to reference while adding users to this entity
 $ vault write identity/entity-alias name="bob" canonical_id=<ENTITY_ID from above> \
        mount_accessor=$(cat accessor.txt)
# Same for other user bsmith
 $ vault write identity/entity-alias name="bsmith" canonical_id=<ENTITY_ID from above> \
        mount_accessor=$(cat accessor.txt)

#Check the output if added or not by 
 $ vault read identity/entity/id/<ENTITY_ID>
#check for the entity details 
 $ vault read identity/entity/name/bob-smith

#In Policies the allowed permissions are for secret enable that engine 
 $ vault secrets enable -path=secret kv-v2

#Test Entity by logging in as one user bob
 $ vault login -method=userpass username=bob password=training
#Write something to the secret to verify your token is working 
 $ vault kv put secret/test owner="bob"
 
#Check if entity policy is inhertied to the user added 
 $ vault token capabilities secret/data/training_test
 
#Now we will explore the Internal group before that login with the initial token you used to log in
1. Create internal group
2. Add Entity to group along with users added as alias in entity
#Create a group Policy
 $ vault policy write team-eng - << EOF
         path "secret/data/team/eng" {
  capabilities = [ "create", "read", "update", "delete"]
}
EOF

#Create an internal group named engineers and add bob-smith entity as a group member and attach team-eng
 $ vault write identity/group name="engineers" \
        policies="team-eng" \
        member_entity_ids=<entity_id> \
        metadata=team="Engineering" \
        metadata=region="India"