1. How to execute a shell command on an EC2 instance?


    In AWS, to execute a shell command on an EC2 instance, you use the aws.ec2.Instance class to create the instance. To run a shell command, you provide it as input to userData argument.

    Remember to replace "ami-abc12345" with the actual AMI (Amazon Machine Image) ID that you plan to create a new EC2 instance from. Also, replace "t2.micro" with the desired instance type.

    In this case, userData is a base64 encoded string. It includes a set of shell commands passed as user data to customize the instance. Please replace the shell script with the actual commands you want to execute.

    Note that the command must exit with a 0 status for Pulumi to consider it successful. Also note that these commands run at system startup and require root privileges.

    Here's a demonstration with Python:

    import pulumi import pulumi_aws as aws size = 't2.micro' ami = aws.get_ami(most_recent="true", owners=["137112412989"], # This owner ID is for Amazon filters=[{"name":"name","values":["amzn-ami-hvm-????.??.?.????????-x86_64-gp2"]}]) # Use an AWS Linux AMI user_data = '''#!/bin/bash echo "Hello, World!" > index.html nohup python -m SimpleHTTPServer 80 & ''' group = aws.ec2.SecurityGroup('web-secgrp', description='Enable HTTP access', ingress=[ { 'protocol': 'icmp', 'from_port': 8, 'to_port': 0, 'cidr_blocks': [''] }, { 'protocol': 'tcp', 'from_port': 22, 'to_port': 22, 'cidr_blocks': [''] }, { 'protocol': 'tcp', 'from_port': 80, 'to_port': 80, 'cidr_blocks': [''] }, ]) server = aws.ec2.Instance('web-server-www', instance_type=size, vpc_security_group_ids=[group.id], # reference the group object above ami=ami.id, user_data=user_data, tags={"Name": "web-server-instance"}, ) pulumi.export('publicIp', server.public_ip) pulumi.export('publicHostName', server.public_dns)

    When you run this Pulumi program, it will set up your EC2 instance and run the shell command you provided in the user_data argument. In this case, we are running a simple Python HTTP server. The server's public IP and hostname are then exported as stack outputs.