How do i continue working with Amplify on a new machine? - amazon-web-services

I'm using react native for my project. On my old machine, when i ran amplify status, i had Auth, Api and Storage services listed.
I moved to my new machine, installed node, watchman, brew etc... and then navigated to my react native project and ran: react-native run-ios, and voila, my app is running. All the calls to my AWS Api, Auth and Storage are working perfectly.
Now i can make some amplify commands. Such as amplify status. I tried: amplify env add: here's what i got:
Users-MBP-2:projectname username$ amplify env add
Note: It is recommended to run this command from the root of your app directory
? Do you want to use an existing environment? Yes
? Choose the environment you would like to use: dev
Using default provider awscloudformation
✖ There was an error initializing your environment.
init failed
Error: ENOENT: no such file or directory, open '/Users/username/.aws/credentials'
at Object.openSync (fs.js:462:3)
at Proxy.readFileSync (fs.js:364:35)
at Object.readFileSync (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/util.js:95:26)
at IniLoader.parseFile (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/shared-ini/ini-loader.js:6:47)
at IniLoader.loadFrom (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/shared-ini/ini-loader.js:56:30)
at Config.region (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/node_loader.js:100:36)
at Config.set (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/config.js:507:39)
at Config.<anonymous> (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/config.js:342:12)
at Config.each (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/util.js:507:32)
at new Config (/usr/local/lib/node_modules/#aws-amplify/cli/node_modules/aws-sdk/lib/config.js:341:19) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/Users/username/.aws/credentials'
}
Do you think credentials info needs to be brought/configured to my new machine?
When i run amplify configure project it's like doing an amplify init and building a project from scratch. I'm being asked:
? Enter a name for the project: ProjectName
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using (Use arrow keys)
angular
ember
ionic
react
❯ react-native
vue
none
etc....
I also already have a region, username and accessKey, secretAccess key etc..
I do not want to replace or ruin anything in my current backend or current project! Whats going on?

Ensure amplify-cli is installed and you're logged in with your AWS details.
npm install -g #aws-amplify/cli
amplify configure
Running amplify configure is mainly to give the cli knowledge of your AWS account so subsequent commands can have access to things.
If you get amplify: command not found errors try restarting your terminal. If still no luck, you will need to check amplify has been added to your PATH variable.
Run amplify env add , but choose an existing environment. This will let you choose the environment you created on your other machine so you can pull those settings down to your new machine.
amplify env add
? Do you want to use an existing environment? Yes
Production
Follow up with:
amplify pull
You don't need to run amplify add auth again or anything. All of that will pull down automatically after you've done the above.

You DO NOT need to do all config again, but some for sure
You have to install amplify cli npm install -g #aws-amplify/cli
use amplify pull
https://docs.amplify.aws/cli/start#amplify-pull
Follow the rest of steps -
-- provide the accessKeyId, secretAccessKey
-- region
-- select amplify project
and then rest of app related thing like IDE, directory......

I tried every solution then I found this. (in MacBook)
% sudo -i
Password:
~ root# npm install -g #aws-amplify/cli
-- Ctrl+D to exist from Root user
% amplify pull --appId xxxx --envName yyyy.
Note: To get --appId xxxx --envName yyyy
Log in to the AWS console. Choose AWS Amplify. Click your app. Go to Backend
environments. Find the backend environment you wish to pull. Click
Edit backend. See top right then click 'Local setup instructions
' ( amplify pull --appId
YOUR_APP_ID --envName YOUR_ENV_NAME )
Waiting until it request to verify your amplify.
✔ Successfully received Amplify Studio tokens.
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path: src
? Distribution Directory Path: build
? Build Command: npm run-script build
? Start Command: npm run-script start
✔ Synced UI components.
? Do you plan on modifying this backend? Yes
⠴ Building resource api/xxxx✅ GraphQL schema compiled successfully.
Edit your schema at ....
✔ Successfully pulled backend environment yyyy from the cloud.
✅
Successfully pulled backend environment staging from the cloud.
Run 'amplify pull' to sync future upstream changes.
% amplify pull
% npm install
% npm start
Hope this help every one!!
Happy Coding :)

Related

How can I configure Amplify to create a new backend environment for each branch?

I'm trying to configure Amplify to deploy every branch or PR on my Github repo to a new environment.
Using Previews:
Pull Request Previews is enabled
The configuration for the backend is "Create new backend environment for every Pull Request"
But every build skips the backend step with this message "No backend environment association found, continuing..." and because of that the frontend build fails because it requires the aws-exports file that should be generated on the backend stage.
The same occurs with Branch autodetection (With the option Create new backend environment for every connected branch selected)
I'm opening this question here because I couldn't get any answer from AWS on their repo
We were recently facing the same issue and discovered that in order to be able to automatically create new BE environments for Previews or Branch autodetection, you need to add backend build step into Build settings in Amplify (amplify.yml).
It can be found in Amplify documentation and in the most simple form it should look like this:
backend:
phases:
build:
commands:
- amplifyPush --simple
It is not very well documented or obvious, we stumbled across the solution by chance.

How to access API secrets from Next.js in AWS Amplify

I am very confused regarding how to set and access API secrets in a Next.js app within an AWS Amplify project.
The scenario is: I have a private API key that fetches data from an API. Obviously, this is a secret key and I don't want to share it in my github repo or the browser. I create a .env.local file and place my secret there.
API_KEY="qwerty123"
I am able to access this key in my code through using process.env.API_KEY
Here is an example fetch request with that API Key: https://developer.nps.gov/api/v1/parks?${parkCode}&api_key=${process.env.API_KEY}
This works perfectly when I run yarn dev and yarn build -> yarn start
This is the message I get when I run yarn start
next start
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from /Users/tmo/Desktop/Code/projects/visit-national-parks/.env.local
The env is loaded and able to be called on my local machine.
However,
When I push this code to github and start the Build process in AWS Amplify, the app builds, but the API fetch calls do not work. I get a ````500 Server Error`````
This is what I have done to try and solve this issue:
Added my API_KEY in the Environment variables tab in Amplify
2. Update my Build settings
frontend:
phases:
preBuild:
commands:
- yarn install
build:
commands:
- API_KEY=${API_KEY} '#Added my API_KEY from the environment variables tab in Amplify`
- yarn run build
I am not sure what else to do. After building the app again, I still get 500 server error
Here is the live amplify app with the server error.
We're working on something similar right now. Our dev designed it so it reads an .env file.
frontend:
phases:
preBuild:
commands:
- yarn install
build:
commands:
- echo API_KEY=$API_KEY >.env
- echo OTHERKEY=$OTHER_KEY >> .env
- yarn run build
We were able to pick it up and pass it to AWS' DynamoDB Client SDK.
Not sure if it's your call or not, but yarn can be fickle in our Amplify projects sometimes, so we usually resort to using npm if it starts acting up.

Publish artifact to AWS CodeArtifact with sbt

I'm trying to publish artifacts to AWS CodeArtifact using sbt, but I'm having some troubles;
Given an sbt project, running the command sbt publish the package is uploaded to the repo but It remains in the Unfinished state. The AWS CodeArtifact documentation says:
Unfinished: The last attempt to publish did not complete. Currently only Maven package versions can have a status of Unfinished. This can occur when the client uploads one or more assets for a package version but does not publish a maven-metadata.xml file for the package that includes that version.
I'm using sbt at version 1.3.3, I'm not using plugins, the property publishMavenStyle is true.
I know that the sbt-maven-resolver (here the repo) solves the issue, but it seems an "unfollowed plugin", and moreover, using it I lose all logs about the publishing process, I don't trust it.
Did anyone have the same issue and have solved it somehow?
Using CodeArtifact with SBT
Setting up SBT with CodeArtifact
Publishing Packages with SBT (also avoiding the artifact being in Unfinished state.)
1. Setting up SBT with CodeArtifact
Create a CodeArtifact repository with a Maven upstream. For this example we're going to use repository maven-test in domain launchops
Open up the Connection Instructions in the console and choose mvn. We will need information from this later.
Copy the command which exports the "CODEARTIFACT_AUTH_TOKEN" environment variable from the console and run it in your environment. This will set the "CODEARTIFACT_AUTH_TOKEN" to be the password for our repository, the username is always aws.
In the build.sbt file import sbt.Credentials:
import sbt.{Credentials}
Now we need to setup the credentials. To do this we're first going to read the CODEARTIFACT_AUTH_TOKEN environment variable:
val repoPass = sys.env.get("CODEARTIFACT_AUTH_TOKEN").getOrElse("")
Next, we're going to use the previously imported sbt.Credentials to setup a new set of Credentials:
credentials += Credentials("launchops/maven-test", "launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com", "aws", repoPass)
The values passed to the Credentials object are ("domain-name/repository-name", "repository hostname without protocol", "username", "password"), with username always being aws and password coming from the repoPass variable we only need to modify the first two to point to our repository.
Now we just need to instruct SBT to use our repository as a resolver. The consoles connection instructions will generate Maven settings, for example:
<repository>
<id>launchops--maven-test</id>
<url>https://launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com/maven/maven-test/</url>
</repository>
We will use these values to create a resolver in our build.sbt file:
resolvers += "launchops--maven-test" at "https://launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com/maven/maven-test"
The format of this is "resolvers += "ID From maven configuration in console" at "Repository URL from maven configuration in console".
To completely disable the use of public Maven repositories (Force CodeArtifact usage) you can add the following line to the build.sbt file:
externalResolvers := Resolver.combineDefaultResolvers(resolvers.value.toVector, mavenCentral = false)
After performing these setups steps you should be able to run sbt update and observe packages being downloaded through CodeArtifact.
Sample build.sbt for reference:
import sbt.{Credentials, Path}
name := "scala-test"
version := "0.3.0"
scalaVersion := "2.12.6"
organization := "com.abc.def"
val repoPass = sys.env.get("CODEARTIFACT_AUTH_TOKEN").getOrElse("")
credentials += Credentials("launchops/maven-test", "launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com", "aws", repoPass)
resolvers += "launchops--maven-test" at "https://launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com/maven/maven-test"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.0.0" % "test",
"io.nats" % "jnats" % "2.0.0",
"org.json4s" %% "json4s-native" % "3.6.0"
)
2. Publishing Packages
Apart from pulling dependencies, SBT can also be used to publish packages. To have SBT publish to CodeArtifact we first need to set it up in the build.sbt file:
Add the following to the file:
publishMavenStyle := true
publishTo := Some("launchops--maven-test" at "https://launchops-123456789012.d.codeartifact.us-east-1.amazonaws.com/maven/maven-test")
At this point, technically, running sbt publish will push the package to CodeArtifact, however it will end up in Unfinished state. We need to make use of sbt-maven-resolver plugin to help get the package in the correct format: https://github.com/sbt/sbt-maven-resolver
In the project/plugins.sbt file add the following line:
addSbtPlugin("org.scala-sbt" % "sbt-maven-resolver" % "0.1.0")
Now you can run sbt publish and have the package publish to CodeArtifact successfully. If you see an error make sure that you are using a recent version of SBT.
You can achieve the same without using the sbt-maven-resolver plugin by following shariqmaws' answer without the plugin.
The publish will result in an artifact in "unpublished" state.
Then use the aws codeartifact cli to publish it (https://docs.aws.amazon.com/codeartifact/latest/ug/maven-curl.html)

amplify init fails on validation caused [$LATEST] inside 'stackName' value

I developing Vue project and have problem with amplify deployment console:
I configured an Amplify project with Cognito Id Pools (Google).
Added an environment 'dev' into the project located on the 'dev' git-branch. Successfully pushed to cloud.
Then using Amplify console created Deployment project based on Github. Checked the environment and branch, and other settings properly. And tried to deploy project
'Provision' stage passed successfully
'Build' failed
After searching info about problem with no result I deleted Amplify from my project locally and on the cloud, using 'amplify delete'. Cleared my git-project from amplify's files and folder. Did all create actions again and got same error:
ValidationError: 1 validation error detected: Value '2019/08/17/[$LATEST]84c0b31765d7431faf5d8f4b51322d03' at 'stackName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z][-a-zA-Z0-9]|arn:[-a-zA-Z0-9:/._+]
Value: '2019/08/17/[$LATEST]84c0b31765d7431faf5d8f4b51322d03' is abnormal. And [$LATEST] looks like variable name, that copied directly instead of being interpreted.
I don't know what to do. And what is the reason of problem.
The problem was on version of Amplify module on the cloud is lower than my local version
My local amplify module version is 1.12.0.
Cloud's amplify version is 1.7.2.
After downgraded my local amplify version to 1.11.0 and recreated amplify project it works successfully.

Google Cloud - Wrong project id being used from different email address

Despite running gcloud auth application-default login and gcloud config set core/project CORRECT_PROJECT_ID the project keeps defaulting to an incorrect project id:
gcloud config list
[core]
account = CORRECT_EMAIL
disable_usage_reporting = True
project = CORRECT_PROJECT_ID
Your active configuration is: [default]
I can successfully run the sample code from the tutorial (below) if I run in the terminal
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
However, I didn't want to have to do this every time, so I ran the command:
gcloud auth application-default login
This opened a browser with a list of my gmail accounts, and even though I selected the correct account, the success window went to a different gmail account. So then I tried it in an incognito window, and it worked.
However, running npm start resulted in the following error:
ERROR: { Error: 7 PERMISSION_DENIED: Cloud Natural Language API has not been used in project WRONG_PROJECT_ID before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/language.googleapis.com/overview?project=WRONG_PROJECT_ID then retry.
Then I ran gcloud config set core/project CORRECT_PROJECT_ID and got the message Updated property [core/project].
When I run npm start I get the same message:
ERROR: { Error: 7 PERMISSION_DENIED: Cloud Natural Language API has not been used in project WRONG_PROJECT_ID before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/language.googleapis.com/overview?project=WRONG_PROJECT_ID then retry.
I tried gcloud auth login and got the following message (after I authenticated in an incognito window):
WARNING: `gcloud auth login` no longer writes application default credentials.
If you need to use ADC, see:
gcloud auth application-default --help
You are now logged in as [CORRECT EMAIL ADDRESS].
Your current project is [CORRECT_PROJECT_ID]. You can change this setting by running:
$ gcloud config set project PROJECT_ID
I have a few suggestions that may correct this behaviour.
1) Clear your web browser cache & cookies. Then run "gcloud auth application-default login"
2) Try re-installing the gcloud toolkit.
3) Try unsetting the project in your config first, then set the project to the correct project. i.e.
gcloud config unset project WRONG_PROJECT_ID
gcloud config set project CORRECT_PROJECT_ID
4) Check the “CLOUDSDK_CORE_PROJECT” environment variable. Set it to the correct project if it is not already.
5) Try re-running “gcloud init”
6) You can find your application default credentials in
Linux: ~/.config/gcloud/application_default_credentials.json
Windows: C:\Users\%username%\AppData\Roaming\gcloud\credentials
You can delete the file, & regenerate it using commands you had mentioned in your question such as “gcloud auth default-credentials login”
We need to find where npm start is getting its credentials from. Once we figure that out, we can figure out how to change it, & understand why it’s looking there etc.
Are you able to find the config file to see where it is looking for credentials?
Is npm start the entire command? I’m not too familiar with Node JS. I’m not sure why it is trying to use Natural Language API.
You also mentioned a tutorial but I think you may have forgotten to include it in your question. Which tutorial are you referring to?