PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label environment-variables. Show all posts
Showing posts with label environment-variables. Show all posts

Sunday, November 13, 2022

[FIXED] How to ignore shebang "#!/usr/bin/env bash" in a chrooted SSH Plesk hosted webspace environment

 November 13, 2022     bash, environment-variables, hubzilla, plesk, shebang     No comments   

Issue

Is there any way to ignore a shebang from a script to run scripts globally via "/bin/bash"?

I have a PLESK-hosted webspace, with SSH chrooted to my web-home. I tried to install hubzilla, but most scripts in there return errors because they use the shebang

"#!/usr/bin/env bash"

In my home, "/usr" only contains a folder "/lib", and I do not have (nor will be granted) rights to create a matching directory or a symlink (bash is located in "/bin" and is standard interpreter for ssh). Adding

export PATH="$PATH:$HOME/bin"

to ".profile" does not solve the problem, either.

I could modify all scripts with that shebang to "#!/bin/bash" - But then I would have to re-do that after each update...? Is hubzilla just not for PLESK hosted webspaces? The hoster suggests a vserver, instead, but I want to avoid server administration.

Update: Problem solved by Barmar! Calling the script using bash directly works.

Overal solution for the use case at hand: Hubzilla's script (add_addon_repo - and probably others) calls further commands that are not available via SSH (next problem: git is not accessible via command line, just panel). So I guess hubzilla uses just more functionality than (at least this) webspace offers. So I will reactivate my vhost.


Solution

Run the script with bash explicitly, rather than as a command:

/bin/bash scriptname


Answered By - Barmar
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 10, 2022

[FIXED] How to access variables from .env file in React app using Firebase?

 November 10, 2022     api, environment-variables, firebase, firebase-authentication, reactjs     No comments   

Issue

Hopefully, I did put my .env file in the right place, I wanna access variables in firebase.js file for authentication to keep my API secure.

enter image description here

.env file:-

enter image description here

Here is my firebase.js file:-

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: process.env.API_KEY,
    authDomain: process.env.DOMAIN,
    projectId: process.env.PROJECT_ID,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MSG_SENDER_ID,
    appId: process.env.APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();

export { app, auth };

The error I'm getting 👇:-

enter image description here

How to use .env file here?


Solution

Add a prefix of REACT_APP to your variable names in your dotenv file. Like REACT_APP_API_KEY and to access the value in your react file use process.env.REACT_APP_API_KEY and after making changes make sure to restart your react app.



Answered By - Arman Kazi
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What environment variables are created in kubernetes by default

 November 10, 2022     containers, environment-variables, kubernetes     No comments   

Issue

I can't find this in the k8s documentation, I'm just wondering what are the default environment variables that are created in every container by k8s. Not user created defaults, but like (and this is just an example) maybe something like {service_name}_PORT or something like that. I just wanna know what information is available in a container by default.


Solution

From the K8S Documentation:

Container information - ENV's

The hostname of a Container is the name of the Pod in which the Container is running. It is available through the hostname command or the gethostname function call in libc.

The Pod name and namespace are available as environment variables.

These are the additional ENV's in a MiniKube cluster I have running:

HOSTNAME=something-api-234234234-skm70
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_SERVICE_HOST=x.x.x.x
PWD=/

User defined environment variables from the Pod definition are also available to the Container, as are any environment variables specified statically in the Docker image.

Cluster Information - ENV's

A list of all services that were running when a Container was created is available to that Container as environment variables. Those environment variables match the syntax of Docker links.

For a service named foo that maps to a container port named bar, the following variables are defined:

FOO_SERVICE_HOST=<the host the service is running on>
FOO_SERVICE_PORT=<the port the service is running on>


Answered By - ajtrichards
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 5, 2022

[FIXED] how to get environment in javascript file in rails app

 November 05, 2022     environment-variables, javascript, ruby-on-rails     No comments   

Issue

hello ive been trying to get the current environment in rails but i think im doing something wrong with my javascript, but i dont seem to know what. in my application.js i have...

var rails_env = '<%= Rails.env -%>';
alert(rails_env);
alert(rails_env.value);
if(rails_env == 'development'){
    alert('inside if')
    var indexName = "idx";
}
else{
    alert('inside else')
     var indexName = "idx_production";
}

it always goes into my else statement even if i am in development mode. what am i doing wrong? thank you

how to get environment in javascript file in rails app


Solution

Rails' asset pipeline will only preprocess assets that you mark for parsing. Whether those assets are going to end up CSS, JS, or whatever else, you can mark files for parsing by adjusting the file extension.

In this case, where you're trying to output an ERB variable, you will need to change the extension of the file to application.js.erb.

There's an extended discussion of the preprocessor here.



Answered By - rjz
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set Google bigquery environment variable on colab

 November 05, 2022     environment-variables, google-bigquery, google-colaboratory, python     No comments   

Issue

I plan to create a script to extract data from Bigquery, but I don't know how to set the environment variable.

Here is an instance from the official doc:

from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

query = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name, state
    ORDER BY total_people DESC
    LIMIT 20
"""
query_job = client.query(query)  # Make an API request.

print("The query data:")
for row in query_job:
    # Row values can be accessed by field name or index.
    print("name={}, count={}".format(row[0], row["total_people"]))

I run this but return an error:

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

I follow the official doc, but I meet an issue: the second step is setting the environment variable but it just provides instances on Windows and Linux/macOS. So, how do I set the environment variable on Colab?

Also, I notice the instances ask me to provide the key path. It is OK on the local machine, but I don't think it is an idea to upload my key file and past its link in my code online.


Solution

Instead of setting an environment variable or uploading directly to Colab, you can upload your key on your Google Drive and apply necessary restrictions there. In your code, you can then mount Google Drive to Colab, use the Drive location as key file path for authentication.

from google.cloud import bigquery
from google.oauth2 import service_account
from google.colab import drive
import json
# Construct a BigQuery client object.

drive.mount('/content/drive/') # Mount to google drive

# Define full path from Google Drive.
# This example, key is in /MyDrive/Auth/
key_path = '/content/drive/MyDrive/Auth/your_key.json' 

credentials = service_account.Credentials.from_service_account_file(
    filename=key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

client = bigquery.Client(credentials=credentials, project=credentials.project_id,)

query = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name, state
    ORDER BY total_people DESC
    LIMIT 20
"""
query_job = client.query(query)  # Make an API request.

print("The query data:")
for row in query_job:
    # Row values can be accessed by field name or index.
    print("name={}, count={}".format(row[0], row["total_people"]))

Output:

enter image description here



Answered By - Ricco D
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access Elastic Beanstalk env var in springboot application

 November 05, 2022     amazon-elastic-beanstalk, amazon-web-services, environment-variables, java, spring-boot     No comments   

Issue

We have a springboot/Tomcat server running on Elastic Beanstalk. We want to use the Env vars set in beanstalk in our springboot code. Currently we have something like

Private string getvar = System.getenv("ENV_VAR");
//and have also tried
Private string getvar = System.getProperty("ENV_VAR");

Locally this works just fine. When it's on aws, it can't find the variables. We have them set in our EB Instance -> Configuration -> Software -> Environment Variables:

Key = ENV_VAR     
Value = valueWeExpect

and I confirmed they are set via cloudShell.

Does anyone know if we are missing a dependency or referencing the variables incorrectly? Is there anything we have to add?


Solution

I get my via

@Autowired
private Environment _env;

_env.getProperty("ENV_VAR")

Environment is org.springframework.core.env.Environment



Answered By - denov
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get properties from .env file in spring boot test

 November 05, 2022     environment-variables, java, junit5, spring-boot     No comments   

Issue

I am trying to setup tests for my spring-boot application. In regular execution I get some values from .env file that I've specified in run configuration and get them like so:

 @Value("${jdbc.url}")
 private String jdbcUrl;

But when I try to run the simplest of tests, it fails with the exception :

Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext........ Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.url' in value "${jdbc.url}"

How do I load properties from the environment in SpringBootTest?

Here's my test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {App.class})
public class TestingWebApplicationTest {

    @Test
    public void contextLoads() {
    }

}

Solution

Try adding your property to this location /src/test/resources/application-test.properties

Add an @ActiveProfiles("test") annotation on the test class and it should be picked up. See screenshot below;

You can use a profile specific application-{profile}.properties file



Answered By - EfeyoPixel
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check the availability of environment variables correctly?

 November 05, 2022     environment-variables, python     No comments   

Issue

I did a token check, if at least one token is missing, 'True' will not be. Now I need to deduce which variable is missing, how to do it?

PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')


def check_tokens():
    """Checks the availability of environment variables."""
    ENV_VARS = [PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID]
    if not all(ENV_VARS):
        print('Required environment variables are missing:', ...)
    else:
        return True

Solution

I might suggest putting these values inside a class. The check tokens method can be part of the class, and you can use __dict__ to dynamically get reference to all of the tokens you defined without having to duplicate code.

class Environment:
    def __init__(self):
        self.PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')
        self.TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
        self.TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')

    def check_tokens(self):
        """Checks the availability of environment variables."""
        missing_vars = [var for var, value in self.__dict__.items() if not value]
        if missing_vars:
            print('Required environment variables are missing:', *missing_vars)
            return False
        else:
            return True

print(Environment().check_tokens())


Answered By - flakes
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why when i edit PATH(enviroment variable) in cmd, l can't find changes in system property, but i can find in cmd?(windows10))

 November 05, 2022     batch-file, cmd, environment-variables, windows-10     No comments   

Issue

here is the path before edit:

echo %path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\WDAGUtilityAccount\AppData\Local\Microsoft\WindowsApps;

Then i use cmd order path=%path%C:\Test; to add a new root to path.

After that, i echo %path% again, and i got this:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\WDAGUtilityAccount\AppData\Local\Microsoft\WindowsApps;C:\Test;

It looks good,Gight?.But when i go into system property.

I got this:

Problem:

Obviously, the new root C:\Test is not showing in the system property.

I want to know why and how to fix the problem.


Solution

To do what you were hoping to do, specifically appending to the existing System Environment %Path% variable, this is how I'd recommend you do it:

From cmd

For /F "EOL=H Tokens=2,*" %G In ('%SystemRoot%\System32\reg.exe Query "HKLM\SYSTEM\CurrentControlset\Control\Session Manager\Environment" /V Path 2^>NUL') Do @%SystemRoot%\System32\setx.exe Path "%HC:\Test;" /M

From a batch-file

@For /F "EOL=H Tokens=2,*" %%G In ('%SystemRoot%\System32\reg.exe Query
 "HKLM\SYSTEM\CurrentControlset\Control\Session Manager\Environment" /V Path
 2^>NUL') Do @%SystemRoot%\System32\setx.exe Path "%%HC:\Test;" /M

Please note: to do this, you'll need to run your cmd/batch-file elevated, i.e. "Run as administrator". Also this is designed to add your new directory location, only if there is already non space content within that variables value, (if there isn't your system is already broken). You should also note that the new variable content will only be available for future cmd.exe instances, not any currently running ones, (which were loaded prior to your change). If you wanted it available globally and local to the running session, you'd need to also include the separate command, Set "Path=%Path%C:\Test;"



Answered By - Compo
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to test dataclass that can be initialized with environment variables?

 November 05, 2022     environment-variables, pytest, python, python-3.x, python-dataclasses     No comments   

Issue

I have the following dataclass:

import os
import dataclasses

@dataclasses.dataclass
class Example:
    host: str = os.environ.get('SERVICE_HOST', 'localhost')
    port: str = os.environ.get('SERVICE_PORT', 30650)

How do I write a test for this? I tried the following which looks like it should work:

from stackoverflow import Example
import os


def test_example(monkeypatch):
    # GIVEN environment variables are set for host and port
    monkeypatch.setenv('SERVICE_HOST', 'server.example.com')
    monkeypatch.setenv('SERVICE_PORT', '12345')
    #   AND a class instance is initialized without specifying a host or port
    example = Example()
    # THEN the instance should reflect the host and port specified in the environment variables
    assert example.host == 'server.example.com'
    assert example.port == '12345'

but this fails with:

====================================================================== test session starts ======================================================================
platform linux -- Python 3.8.12, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/biogeek/tmp
collected 1 item                                                                                                                                                

test_example.py F                                                                                                                                         [100%]

=========================================================================== FAILURES ============================================================================
_________________________________________________________________________ test_example __________________________________________________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f39de559220>

    def test_example(monkeypatch):
        # GIVEN environment variables are set for host and port
        monkeypatch.setenv('SERVICE_HOST', 'server.example.com')
        monkeypatch.setenv('SERVICE_PORT', '12345')
        #   AND a class instance is initialized without specifying a host or port
        example = Example()
        # THEN the instance should reflect the host and port specified in the environment variables
>       assert example.host == 'server.example.com'
E       AssertionError: assert 'localhost' == 'server.example.com'
E         - server.example.com
E         + localhost

test_example.py:12: AssertionError
==================================================================== short test summary info ====================================================================
FAILED test_example.py::test_example - AssertionError: assert 'localhost' == 'server.example.com'
======================================================================= 1 failed in 0.05s =======================================================================

Solution

Your tests fail because your code loads the environment variables when you import the module. Module-level code is very hard to test, as the os.environ.get() calls to set the default values have already run before your test runs. You'd have to effectively delete your module from the sys.modules module cache, and only import your module after mocking out the os.environ environment variables to test what happens at import time.

You could instead use a dataclass.field() with a default_factory argument; that executes a callable to obtain the default whenever you create an instance of your dataclass:

import os
from dataclasses import dataclass, field
from functools import partial


@dataclass
class Example:
    host: str = field(default_factory=partial(os.environ.get, 'SERVICE_HOST', 'localhost'))
    port: str = field(default_factory=partial(os.environ.get, 'SERVICE_PORT', '30650'))

I used the functools.partial() object to create a callable that'll call os.environ.get() with the given name and default.

Note that I also changed the default value for SERVICE_PORT to a string; after all, the port field is annotated as a str, not an int. :-)

If you must set these defaults from environment variables at import time, then you could have pytest mock out these environment variables in a conftest.py module; these are imported before your tests are imported, so you get a chance to tweak things before your module-under-test is imported. This won't let you run multiple tests with different defaults, however:

# add to conftest.py at the same package level, or higher.

@pytest.fixture(autouse=True, scope="session")
def mock_environment(monkeypatch):
    monkeypatch.setenv('SERVICE_HOST', 'server.example.com')
    monkeypatch.setenv('SERVICE_PORT', '12345')

The above fixture example, when placed in conftest.py, would automatically patch your environment before your tests are loaded, and so before your module is imported, and this patch is automatically undone at the end of the test session.



Answered By - Martijn Pieters
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to store GOOGLE_APPLICATION_CREDENTIALS in an AWS ECS environment on Fargate?

 November 05, 2022     amazon-ecs, amazon-web-services, environment-variables, firebase-admin, google-authentication     No comments   

Issue

We have an API app that uses Firebase Admin to send messages to devices. Earlier, we used to specify the service account key using environment variable like GOOGLE_APPLICATION_CREDENTIALS="path_to_file.json". But now, since we are shifting to AWS Elastic Container Service on Fargate, I am unable to figure out how to put this file in the container for AWS ECS.

Any advice highly appreciated.

Thanks


Solution

Solved it by storing the service key as a JSON Stringified environment variable & using admin.credential.cert() instead of defaultAppCredentials. Refer: https://firebase.google.com/docs/reference/admin/node/admin.credential#cert



Answered By - Samyak Jain
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why can't python access the special linux RANDOM environment variable?

 November 05, 2022     environment-variables, python, random     No comments   

Issue

I've been refactoring a bash script that uses the special RANDOM linux environment variable. This variable provides random integers when accessed.

From another SO question:

RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Here's an example of the expected output, working correctly:

ubuntu:~$ echo ${RANDOM}
19227
ubuntu:~$ echo ${RANDOM}
31030

However, when I try to replicate its usage in python I was surprised to find that it does not seem to work.

>>> import os
>>> os.environ.get('RANDOM')
(No output)
>>> os.environ.get('RANDOM')==None
True

This is quite unexpected. Obviously I can just replicate the random integer behavior I want using

random.randint(0, 32767)

But other scripts may be relying on the environment variables specific value (You can seed RANDOM by writing to it), so why can I not simply read this variable in python as expected?


Solution

RANDOM is a shell variable, not an environment variable. You need to export it to get it into the environment:

imac:barmar $ export RANDOM
imac:barmar $ python
Python 3.9.2 (v3.9.2:1a79785e3e, Feb 19 2021, 09:06:10) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['RANDOM']
'15299'

However, this just puts the most recent value of RANDOM in the environment, it won't change each time you use os.environ['RANDOM'] the way $RANDOM does when you use it in the shell.



Answered By - Barmar
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get Environment Variable in csproj file?

 November 05, 2022     .net, appsettings, environment-variables     No comments   

Issue

I want to get the environment variable in csproj, because there I have a condition which exclude appsettings from publish.

enter image description here enter image description here
I want this because, my appsettings didn't depends to Solution Configuration, them depends only from environment variables.

Instead of '$(Configuration)' != Debug' I want something like 'envVariable != Development' etc.

Or is it another method to exclude those files regarding to env variables?

in C# is this method: Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ").


Solution

So I ran into this same problem today and got it working rather easily. This was one of the first relevant results on google when I searched for this so thought I'd share.

Actually the $() operator is used to resolve any variable within the .csproj but it's also seeded with environment variables already when MSBuild is triggered. So in your case you could do $(envVariable) or $(ASPNETCORE_ENVIRONMENT).

They're brought in like any other .csproj variable.



Answered By - Barak Gall
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you set a string of bytes from an environment variable in Python?

 November 05, 2022     binary-data, environment-variables, python     No comments   

Issue

Say that you have a string of bytes generated via os.urandom(24),

b'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'

and you'd like to store that in an environment variable,

export FOO='\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'

and retrieve the value from within a Python program using os.environ.

foo = os.environ['FOO']

The problem is that, here, foo has the string literal value '\\x1b\\xba\\x94... instead of the byte sequence b'\x1b\xba\x94....

What is the proper export value to use, or means of using os.environ to treat FOO as a string of bytes?


Solution

You can 'unescape' your bytes in Python with:

import os
import sys

if sys.version_info[0] < 3:  # sadly, it's done differently in Python 2.x vs 3.x
    foo = os.environ["FOO"].decode('string_escape')  # since already in bytes...
else:
    foo = bytes(os.environ["FOO"], "utf-8").decode('unicode_escape')


Answered By - zwer
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to recover deleted environment variables?

 November 05, 2022     environment-variables, windows-10     No comments   

Issue

In a lazy attempt to debug Visual Studio Community, I (as per recommendation from another forum) deleted all of the system's environment variables. I realized doing this was a HUGE mistake! Nothing works in the right-click menu on the start button (I have Windows 10). Can't do anything in the Settings app, can't even create new accounts or reset computer. Can't open any application that requires administrator approval, either.

Anybody know how I can restore these variables? Just the ones necessary for the OS to work, I don't care if my applications created special ones, I can un/reinstall later. As I type I get an error message after attempting to reset computer saying "The system could not find the environment option that was entered," basically confirming this is the issue.

Thank you!

Hardware: AMD A10-6700 APU with Radeon(tm) HD Graphics 3.70 GHz 12.0 GB RAM 64-bit


Solution

  1. In Windows 10 navigate to Start > Settings > Update & Security > Recovery
  2. Under Advanced Startup, click Restart Now
  3. Once the computer reboots into Advanced Startup, click Troubleshoot
  4. Click Refresh Your PC

Windows 10 restores, keeps all files and apps but removes drivers and custom settings.



Answered By - Anthony Bartolo
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get s3 env files in aws sam with github action

 November 05, 2022     amazon-web-services, environment-variables, fastapi, github-actions, sam     No comments   

Issue

These days I research SAM(Serverless Application Model) to deploy my fastapi sample. However, I can't get the s3 env file. The sam cli command is below.

$ sam build --use-container
$ sam deploy

The point of error in the code is below.

content_object = boto3.resource('s3').Object('config', 'test.json')

In the local env, I can get the env file in the s3 bucket, but when I deploy with sam, the error has occurred like this.

[ERROR] ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

How to solve this issue? Have any good sources for getting env files in SAM? I just want to make deploy in github action.


Solution

I have an issue that loads an env file with SAM (AWS Serverless Application Model) application(FastAPI). However, I can't load the env file in the python script since SAM env is different from Zappa (Zappa can env file with remote_env in the config file). So, I use the copy method in the GitHub action (workflow).



Answered By - Hans
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do configure docker compose to use a given subnet if a variable is set, or choose for itself if it isn't?

 November 05, 2022     docker, docker-compose, docker-networking, environment-variables     No comments   

Issue

I have the following networks configuration in my docker compose file.

networks:
    default:
        ipam:
            driver: default
            config:
                - subnet: ${DOCKER_SUBNET}

When DOCKER_SUBNET is set, the subnet specified in that variable is used as expected. When the variable is not set I get: ERROR: Invalid subnet : invalid CIDR address: because the variable is blank (which is entirely reasonable).

Is there a way to configure the ipam driver such that when the DOCKER_SUBNET variable is not set, docker-compose will choose an available subnet as it would normally do if the ipam configuration was not given?


Solution

Compose will only choose an available subnet if you don't provide any ipam configuration for the network. Compose doesn't have advanced functionality to modify config on the fly.

You could make the decision outside of compose, either with multiple compose files or a template based system, in shell or some other language that launches the docker-compose command.

Seperate the compose network config from the rest of the service config in files:

docker-compose-net-auto.yml

version: "2.1"
networks:
  default:

docker-compose-net-subnet.yml

version: "2.1"
networks:
  default:
    ipam:
      driver: default
      config:
        - subnet: ${DOCKER_SUBNET}

Then create a script launch.sh that makes the choice of which network file to include.

#!/bin/sh
if [ -z "$DOCKER_SUBNET" ]; then
  docker-compose -f docker-compose.yml -f docker-compose-net-auto.yml up
else
  docker-compose -f docker-compose.yml -f docker-compose-net-subnet.yml up
fi


Answered By - Matt
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to override Go environment variables with Helm

 November 05, 2022     environment-variables, go, kubernetes-helm     No comments   

Issue

How do I override environment variables in a .env file for Go with Helm?

With C# I do the following:

In appsettings.json:

{
    "Animals":{
        "Pig": "Squeek"
    },
}

In values.yaml:

animals:
  pig: "Oink"

In configmap.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: animal-configmap
pig: {{ .Values.animals.pig }}

And finally in deployment.yaml:

spec:
  ...
  template:
    ...
    spec:
      ...
      containers:
          ...
          env:
            - name: Animals__Pig
              valueFrom:
                configMapKeyRef:
                  name: animal-configmap  
                  key: pig

Not the double __. How would one go about updating an environment value for Go?

Here is the Go .env file example:

PIG=SQUEEK

Solution

If your Go code is retrieving an ordinary environment variable

pig := os.Getenv("PIG")

then the Kubernetes manifest should use that name as the environment variable name:

env:
  - name: PIG
    valueFrom: {...}

The double-underscore doesn't have any special meaning in Unix environment variables or the Kubernetes manifest, in your initial example it looks like the way the C# framework separates components when it maps environment variables to application properties. If you're using environment variables directly you don't need to do anything special.



Answered By - David Maze
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use .env in Flutter web?

 November 05, 2022     dart, environment-variables, flutter     No comments   

Issue

Short story:

I am trying to use .env file in my Flutter Web project.

I used flutter_dotenv before in Flutter mobile app but it is not working in Flutter web.

How can we use .env file in Flutter web?

Long Story:

For now, I am using dart file to save current constant values such as backend url.

Backend is in same domain like this => https://domain_for_webapp.com/api/

class Environment {

  // API URL
  static const String API_URL ='https://domain_for_webapp.com/api/';
...

But problem here is I have one more server to deploy same site https://another_domain_for_webapp.com/api/ So I tried to solve that by using relative url

class Environment {

  // API URL
  static const String API_URL ='/api/';
...

But Flutter web can't find correct full API url for each server.

To solve this I have been trying to use .env like in normal web app.

But I can't use .env in Flutter web.

Is there any proper solution for this problem?


Solution

Like mentioned here, you can rename your .env file to something that doesn't start with a dot. I've changed my .env file to "dotenv".



Answered By - Jonas Goebel
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get Powershell to run SH scripts

 November 05, 2022     environment-variables, powershell, scripting, sh     No comments   

Issue

Can someone please tell me how I get Powershell to run .sh scripts? It keeps just trying to open the file i need in Notepad when I run this command:

.\update-version.sh 123

I've added .SH to my PATHEXT environment variable and also added the Microsoft.PowerShell_profile.ps1 directory to the Path environment variable.


Solution

PowerShell scripts have a .ps1 extension (along with other supported extensions such as psm1,psd1 etc) it will not run other extensions other than that.



Answered By - Shay Levy
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing