Configure AWS Greengrass on Amazon EC2 – Operating and Monitoring IoT Networks
Now, we can set up AWS Greengrass on our Amazon EC2 to be able to simulate our IoT Thing, which will fetch the ChatGPT API along with its responses accordingly:
Run the following command to update the necessary dependencies:
$ sudo yum update
Run the following command to install Python, pip, and boto3:
$ sudo yum install python && sudo yum install pip && sudo yum install
boto3
Now, we will install the AWS IoT Greengrass software with automatic provisioning. First, we will need to install the Java runtime as Amazon Corretto 11:
$ sudo dnf install java-11-amazon-corretto -y
Run this command afterward to verify that Java is installed successfully:
$ java -version
Establish the default system user and group that operate components on the gadget. Optionally, you can delegate the task of creating this user and group to the AWS IoT Greengrass Core software installer during the installation process by utilizing the –component-default-user installer parameter. For additional details, refer to the section on installer arguments. The commands you need to run are as follows.
$ sudo useradd –system –create-home ggc_user
$ sudo groupadd –system ggc_group
Ensure that the user executing the AWS IoT Greengrass Core software, usually the root user, has the necessary privileges to execute sudo commands as any user and any group. Use the following command to access the /etc/sudoers file:
$ sudo visudo
Ensure that the user permission looks like the following:
root ALL=(ALL:ALL) ALL
Now, you will need to provide the access key ID and secret access key for the IAM user in your AWS account to be used from the EC2 environment. Use the following commands to provide these credentials:
$ export AWS_ACCESS_KEY_ID={Insert your Access Key ID here}
$ export AWS_SECRET_ACCESS_KEY={Insert your secret access key here}
On your primary device, retrieve the AWS IoT Greengrass Core software and save it as a file named greengrass-nucleus-latest.zip:
$ curl -s https://d2s8p88vqu9w66.cloudfront.net/releases/greengrass-nucleus-latest.zip > greengrass-nucleus-latest.zip
Decompress the AWS IoT Greengrass Core software into a directory on your device. Substitute GreengrassInstaller with the name of your desired folder:
$ unzip greengrass-nucleus-latest.zip -d GreengrassInstaller && rm greengrass-nucleus-latest.zip
We now can install the AWS IoT Greengrass Core software. Replace the values as follows:
- /greengrass/v2 or C:\greengrass\v2: This location specifies where you plan to install the AWS IoT Greengrass Core software on your system, serving as the primary directory for the application.
- GreengrassInstaller: This term refers to the directory where you have unpacked the installation files for the AWS IoT Greengrass Core software.
- region: This is the specific geographical area within AWS where your resources will be provisioned and managed.
- MyGreengrassCore: This label is used to identify your Greengrass core device as a thing within AWS IoT. Should this thing not be present already, the installation process will generate it and retrieve the necessary certificates to establish its identity.
- MyGreengrassCoreGroup: This refers to the collective grouping of AWS IoT things that your Greengrass core device is part of. In the absence of this group, the installation process is designed to create it and enroll your thing within it. If the group is pre-existing and actively deploying, the core device will proceed to pull and initiate the deployment’s software.
- GreengrassV2IoTThingPolicy: This is the identifier for the AWS IoT policy that facilitates the interaction of Greengrass core devices with AWS IoT services. Lacking this policy, the installation will automatically generate one with comprehensive permissions under this name, which you can later restrict as needed.
- GreengrassV2TokenExchangeRole: This is the identifier for the IAM role that allows Greengrass core devices to secure temporary AWS credentials. In the event that this role is not pre-established, the installation will create it and assign the GreengrassV2TokenExchangeRoleAccess policy to it.
- GreengrassCoreTokenExchangeRoleAlias: This alias pertains to the IAM role that grants Greengrass core devices the ability to request temporary credentials in the future. Should this alias not be in existence, the installation process will set it up and link it to the IAM role you provide.
The following is the command you will need to run and have the values within replaced:
$ sudo -E java -Droot=”/greengrass/v2″ -Dlog.store=FILE \
-jar ./GreengrassInstaller/lib/Greengrass.jar \
–aws-region region \
–thing-name MyGreengrassCore \
–thing-group-name MyGreengrassCoreGroup \
–thing-policy-name GreengrassV2IoTThingPolicy \
–tes-role-name GreengrassV2TokenExchangeRole \
–tes-role-alias-name GreengrassCoreTokenExchangeRoleAlias \
–component-default-user ggc_user:ggc_group \
–provision true \
–setup-system-service true
Now, navigate to the root of the EC2 instance and create a file called script.py with the following command:
$ sudo vi script.py
Write the following in the script, replacing the AWS access key, secret access key, and OpenAI API key with your own values:
import json
import openai
import boto3
import time
from datetime import datetime
# Initialize AWS IoT client
def create_aws_iot_client():
iot_client = boto3.client(‘iot-data’, region_name='{ENTER_YOUR_AWS_REGION_HERE}’, aws_access_key_id='{ENTER_YOUR_ACCESS_KEY_HERE}’, aws_secret_access_key=’ENTER_YOUR_SECRET_ACCESS_KEY_HERE’) # replace ‘ap-southeast-2’ with your AWS region
return iot_client
# Initialize OpenAI client
def interact_with_chatgpt(prompt):
openai.api_key = ‘{ENTER_OPENAI_API_KEY_HERE}’
response = openai.Completion.create(
engine=”text-davinci-002″,
prompt=prompt,
temperature=0.5,
max_tokens=100)
return response.choices[0].text.strip()
def publish_to_aws_iot_topic(iot_client, topic, message):
# Convert the message into a JSON object
json_message = json.dumps({“message”: message})
return iot_client.publish(
topic=topic,
qos=0,
payload=json_message)
def main():
prompt = “Tell a joke of the day”
topic = “sensor/chat1”
iot_client = create_aws_iot_client()
while True:
chatgpt_response = interact_with_chatgpt(prompt)
publish_response = publish_to_aws_iot_topic(iot_client, topic, chatgpt_response)
print(f”{datetime.now()}: Published message to AWS IoT topic: {topic}”)
time.sleep(300) # pause for 5 minutes
if __name__ == “__main__”:
main()
Save the file and quit the vim editor.
Navigate to the AWS IoT page in the AWS Management Console. Go to MQTT test client.
Click on Subscribe to a Topic and input sensor/chat1 into the topic filter. Click on Subscribe.
If you look in the Subscriptions window at the bottom of the page, you can see the topic open. Now, navigate back to the EC2 window and run the following command:
$ python script.py
You should now see there is a new message under the topic. You will see a joke being written there, and one being generated every five minutes (or any other duration of time, depending on what you specified).
With that, we have configured AWS Greengrass on the EC2. Now, we can look at monitoring the EC2 in terms of how it publishes messages.