Package: credopy
CredoPy aka pydo!DiscontinuedCredoPy is discontinued. Nearly all features will be available inAEnv.
All existing pip packages will stay available, feel free to keep using pydo.InstallationInstall python3 and pipInstall AWS CLIInstall pydo:pip install credopyFor YubiKey support install theYubiKey Manager CLIOn Windowssetup Boto3 credentialsNo passwords in code!Make your company more secure by using the "troy password credo"!Easier said than done working with credentials can get very messy and lead to huge security and data protection problems. So while working attroy gmbhit became clear that we had to define some fundamental rules to maintain a high level of security during fast growth phases. This brought up the "troy password credo".troy password credo:You may ask "What is the famous troy password credo?"
It's very simple:Neverstore credentials unencrypted!Let's get startedWorking with Credentials can be fun, but from a security perspective, most of the time it isn't! Especially if you have multiple systems and different environments.If you're using the AWS cloud you found the right repository!Pydo is a tool that injects aws parameter store strings and secure strings into your memory as an environment variable. With this, your important credentials/security keys/... never have to touch your disk again.And because the parameter store supports paths you can define different services with different environments.For example:/<Environment>/<KotlinApp1>/

#which could look like:
/Prod/CustomerManagement/DB/USER

#or
/Prod/CustomerManagement/DB/PASSWORDOutput these example data (The database password for CustomerManagement in production ):pydo -e Prod -s CustomerManagement echo '$SECRET_CUSTOMERMANAGEMENT_DB_PASSWORD'With both parameters, your "CustomerManagement" application/service (launched with pydo) could now access the database with the provided username and password.Details at:How to access the environment variablesUsagepydo [-s <service/application>] [-i] [-n] [-e <env>] [-t <2fa key>] [-T] [-Y] [-u <aws username>] [-a <account number>] [-p <aws profile>] [-r <region>] <command>Options:Optionexplinationsamplecomment-hShows helppydo -h-iStarts pydo in interactive modepydo -iGives you a command line that you can interact with-s <service/application>For which service should the environment variables be loaded?pydo -s CustomerService-SSets a default service for pydo and writes it to a config filepydo -S CustomerServicefrom now on "CustomerService" is the default service which means "-s CustomerService" is redundant-nDo not query the parameter store at allpydo -nCan be used to auth the current session with MFA-e <env>For which environment should the environment variables be loaded? For example Dev, Test or Prod (permission required)pydo -e Prod-t <2fa key>Takes the 2FA key from your aws accountpydo -t 987123-TLets you type in the 2FA key from your aws account during runtimepydo -TWhen you run your command pydo will ask for the token-YUses Yubikey for MFA authpydo -YDuring runtime pydo will use ykman to fetch the MFA-Key from your yubikey-r <region>Overwrites temporary the awscli default regionpydo -r eu-central-1Pydo will use the given region for example Frankfurt-qQuiet mode (less output)pydo -q-u <aws username>Sets a specific username combined with -a gives you a faster runtime (otherwise this data needs to be retrieved via aws)pydo -uuser@example.de-a <account number>Sets a specific account number combined with -u gives you a faster runtime (otherwise this data needs to be retrieved via aws)pydo -a 999999999999-p <aws profile>If multiple aws profiles are available you can choose the profile otherwise pydo will use the default profilepydo -p testUser1-c <aws profile>Container mode(enable this to make pydo work in ecs and codebuild)pydo -cpermissions<command>Is the command to execute with environment variables injected.pydo codeWill run VS Code with access to given environment variablesNote:It may be required to double escaping.Examples:Linux:pydo echo '$SECRET_CUSTOMERSERVICE_UI_URL'orWindows:pydo echo %SECRET_CUSTOMERSERVICE_UI_URL%Mac:pydo "/Applications/IntelliJ\ IDEA\ CE.app/Contents/MacOS/idea"Notethe quoting of the variable.Enforce MFA authentication for AWS feature / functionAdd the condition "MultiFactorAuthPresent" to your IAM permission:"Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}Sample for sts:AssumeRole:{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Principal": {"AWS": "ACCOUNT-B-ID"},
    "Action": "sts:AssumeRole",
    "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
  }
}Now you need MFA authentication to run assume role commands.
Sample call for this would be:pydo -q -n -Y aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/example-role" --role-session-name AWSCLI-Session

# -q removes the unnecessary output
# -n puts pydo in only authentication mode
# -Y authenticates the session with your YubiKey, alternatively you could use -t or -TEnforce MFA authentication for all Prod parametersTo enforce MFA authentication for all Prod parameters.(Do not forget to adapt to account ID(123456789098) to your own ;) ){
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ssm:PutParameter",
                "ssm:DeleteParameter",
                "ssm:GetParameterHistory",
                "ssm:GetParametersByPath",
                "ssm:GetParameters",
                "ssm:ListTagsForResource",
                "ssm:GetParameter",
                "ssm:DeleteParameters"
            ],
            "Resource": [
                "arn:aws:ssm:*:123456789098:parameter/Prod/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "true"
                }
            }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "ssm:DescribeParameters",
            "Resource": "*"
        }
    ]
}Format for these environment variables:Every environment variable that is loaded with pydo starts with "SECRET_".Then the service-name and path, separated by underliners.(of course in upper case)For example:SECRET_CUSTOMERMANAGEMENT_DB_USERMore about environment variables:Guide to Unix/Environment VariablesThis is maybe made more clear by the following example:/Prod/CustomerManagement/DB/USERwould be accessible with:SECRET_CUSTOMERMANAGEMENT_DB_USERor/Prod/CustomerManagement/DB/PASSWORDwould be accessible with:SECRET_CUSTOMERMANAGEMENT_DB_PASSWORDEnvironmentsWe now talked a lot about environments, but how can pydo differ between different environments like dev, test, or prod?Quite simply, you tell it!Parameterstore:As already mentioned you Define the environment as the first section.Let's take the previous example:/Prod/CustomerManagement/DB/PASSWORDhere "Prod" is our environment for the database(DB) password (PASSWORD) of our CustomerManagement service/application, but we could easily also set this for our test environment like this:/Test/CustomerManagement/DB/PASSWORD(When creating new parameters don't forget to create them as "SecureString's" ;) )Bonus content:Converting parameter store strings to secure strings
Found this in my old files, before using thistest and make sure it really worksbut with this snippet, you should be able to convert every normal parameter store string to a secure string.No guarantee for functionality, make sure you have a backup of the parameter store variablesimport boto3
client = boto3.client('ssm')
response = client.describe_parameters()
nameList = []
dic = {}
dic_descr = {}

for p in response['Parameters']:
    nameList.append(p['Name'])
    dic_descr[p['Name']] = p.get('Description')

nextToken_Str = response['NextToken']

while nextToken_Str:
    response = client.describe_parameters(NextToken=nextToken_Str)
    
    for p in response['Parameters']:
        nameList.append(p['Name'])
        dic_descr[p['Name']] = p.get('Description')
    
    nextToken_Str = response.get('NextToken', None)
        
for name in nameList:
    response = client.get_parameter(Name=name, WithDecryption=True)
    dic[name] = response.get('Parameter').get('Value')


for name in dic:
    if dic_descr[name] is not None:
        print(client.put_parameter(
            Name=name,
            Description=dic_descr[name],
            Value=dic[name],
            Type='SecureString',
            Overwrite=True
        ))
    else:
        print(client.put_parameter(
            Name=name,
            Value=dic[name],
            Type='SecureString',
            Overwrite=True
        ))Client/YouWithpydo -e <env>you can launch pydo for every in the parameterstore defined environment.If you don't set any pydo swtiches to "Dev"AWS Serverwhen pydo runs on an aws machine you could run it with "-e <env>" but this is rather inconvenient. So pydo queries the instance tags and searches for the key "environment" and uses its value as the current environment. If the environment tag is not set and you did not provide an environment with "-e" pydo automatically defaults to "Dev"How to access the environment variablesTo access those environment variables you have to run your application/service with pydo.pydo java -jar service.jar
//or
pydo python service2.pyNow these two services have all environment variables for their service and environment available and can work with them here are two easy examples:Python:import os
os.getenv('SECRET_CUSTOMERMANAGEMENT_DB_PASSWORD')

#or let's say you want to fetch an API, but need an API token in a header request:
....

header = { 'Api-Key' : os.getenv('SECRET_CUSTOMERMANAGEMENT_API_KEY') }
....Kotlin:val envVar : String? = System.getenv("varname")
//there are some other examples feel free to look into https://stackoverflow.com/ but I like this approach because environment variables can be null, bus null handling probably comes down to your use-case/coding style.AuthenticationAWS Server:Easy!
Done by boto3 automatically uses in instance role defined permissions.(Details "Permissions" section)Developer:boto3 uses the aws CLI's authentication so make sure you set this up before ;)AWS CLIBy default, pydo uses the aws CLI default profile, but of course, you can choose the profile, that you want to use, simply do:pydo -p <awscli profile name>
#or 
pydo -h 
#to see more configuration options(More details in the "Usage" section)MFAFirst of all multi-factor authentication is highly suggested!https://lmgtfy.com/?q=why+mfa+is+importantOk, all jokes aside especially for production parameters your IAM users should require MFA authentication at least for production parameters.So even when a password/account from one of your users gets compromised and let's be realistic here, this will definitely happen to your company/project so better prepare for that event!"How can we mitigate the damage"At least in my humble opinion, this should be a "better be safe than sorry" point.Especially for your production systems!Pydo supports multiple MFA options, details in the "Usage" section, here the short overview:# normal virtual mfa token:
pydo -t <TOKEN>

#askt for the token during runtime:
pydo -T

# leads to:
$ pydo -T
$ Please enter token: 

#Yubikey Authenticator:
pydo -YAt the moment aws-CLI only supports virtual MFA devices(so the -Y option uses the virtual MFA function of your yubikey (ykman) as a workaround until awscli supports hardware tokens ), but feel free to drop a comment or investigate here:https://github.com/aws/aws-cli/issues/3607Permissions: IAM policies / Instance rolesPermissionUsed in the codeDocumentationComment"ec2:DescribeTags"clientEC2.describe_tags()https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeTags.html"sts:GetCallerIdentity"clientSTS.get_caller_identity()https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.htmlOptional(No permissions are required to perform this operation.)"sts:GetSessionToken"clientSTS.get_session_token()https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html"ssm:GetParametersByPath"clientSSMMFA.get_parameters_by_path()https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-access.html"iam:ListMFADevices"boto3.client('iam').list_mfa_devices()https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_iam_mfa-selfmanage.htmlOptional! (At the moment not in use but as soon aws API supports hardware tokens this can be enabled to let pydo support hardware MFA's)tldr Minimal permissions:“ec2:DescribeTags”“sts:GetSessionToken”“ssm:GetParametersByPath”SetupDefine environment variables as described inFormat for these environment variablesSet environment tag's for your instances as described inAWS ServerCreate/adjust your instance roles/IAM roles with proper permissions as described inPermissionsTodointroduce new pip package "aenv" (last update tohttps://pypi.org/project/credopy/) + and rework repoUpdate and correct -h / --help outputremove -q and add -v modeUpdate initial setup instructions + consol output for this(ykman + output for missing service)Option to list all available environments / services(discover/list env / list services)Check for ykman on -Y calls improve outputget rid of environment detection and only rely on -e flag (also no default + better output for missing environment)Currently only the fist MFA device of any given account is used -> add mfa device selection + option for default selectioncleanup/refactor documentation / improve overal structureadd only only auth modeAdd more information about container mode and necessary IAM permissionsEnhance local profile/config setup/usageLoad multiple services at once instead of concatenating multiple pydo calls ( "pydo -s Service1 pydo -s Service2 ")Load environment tags for ECS container / for taskAdd testingAdd feature for only loading certain variables to speed up loadingAcknowledgmentsInspired by:Gunnar Zarncke-LinkedInand his/troy gmbh's opensource credo projekt -Git CredoBug reports:Arif PEHLİVANCarlos FreundLicenseMITLinkSupport me :heart: :star: :money_with_wings:If this project provided value, and you want to give something back, you can give the repo a star or support by buying me a coffee.