{"id":18947637,"url":"https://github.com/yousafkhamza/ec2-infrastructure-creation-through-pyscript","last_synced_at":"2026-05-02T10:39:27.778Z","repository":{"id":195965549,"uuid":"471725638","full_name":"yousafkhamza/EC2-Infrastructure-creation-through-pyscript","owner":"yousafkhamza","description":"Here it's a python script for creating AWS infrastructure through a python script and this is only for educational purposes also, we can do anything via python.","archived":false,"fork":false,"pushed_at":"2022-03-20T04:45:27.000Z","size":15,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-01T01:19:55.268Z","etag":null,"topics":["aws","infrastructure","infrastructure-as-code","pip","python3","script"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yousafkhamza.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-03-19T14:52:05.000Z","updated_at":"2022-03-20T04:35:44.000Z","dependencies_parsed_at":"2023-09-20T20:13:37.808Z","dependency_job_id":null,"html_url":"https://github.com/yousafkhamza/EC2-Infrastructure-creation-through-pyscript","commit_stats":null,"previous_names":["yousafkhamza/ec2-infrastructure-creation-through-pyscript"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2FEC2-Infrastructure-creation-through-pyscript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2FEC2-Infrastructure-creation-through-pyscript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2FEC2-Infrastructure-creation-through-pyscript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yousafkhamza%2FEC2-Infrastructure-creation-through-pyscript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yousafkhamza","download_url":"https://codeload.github.com/yousafkhamza/EC2-Infrastructure-creation-through-pyscript/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239946876,"owners_count":19723014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","infrastructure","infrastructure-as-code","pip","python3","script"],"created_at":"2024-11-08T13:10:49.094Z","updated_at":"2026-05-02T10:39:22.753Z","avatar_url":"https://github.com/yousafkhamza.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AWS Infrastructure Creation (Pyscript)\n[![Build](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)\n\n---\n## Description\nHere it's a python script for creating AWS infrastructure through a python script and this is only for educational purposes also, we can do anything via python. \n\n----\n## Feature\n- Easy to configure for anyone \n- EC2 instance with root privilege\n- Security Group for 80 \u0026 22 (once we created other instances are using the same one)\n- Variables and Configurations are passing through as a module\n\n---\n## Architecture\n![alt_txt](https://i.ibb.co/Px9q8Xq/arch.jpg)\n\n---\n## Modules used\n- [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)\n- [os](https://docs.python.org/3/library/os.html)\n- [datetime](https://docs.python.org/3/library/datetime.html)\n\n\n----\n## Pre-Requests\n- Basic Knowledge of python \n- Basic Knowledge of AWS IAM, EC2 service\n- Need to change your IAM user creds and bucket name at config.py (region, access key, secret key)\n- EC2 details are stored into var.py (password, size, type, sg name)\n\n### IAM User Creation steps (_with screenshot_)\n1. _log into your AWS account as a root user and go to IAM user_\n2. _goto Access Managment \u003e\u003e Users_\n![alt_txt](https://i.ibb.co/Y7kzZmN/IAM-1.png)\n3. _Click Add User_ (_top right corner_)\n![alt_txt](https://i.ibb.co/wW38xvR/IAM-2.png)\n4. _Enter any username as you like and Choose \"Programmatic access\" \u003e\u003e Click Next Permissions_\n![alt_txt](https://i.ibb.co/TrCbpBh/IAM-3.png)\n5. _Set Permissions \u003e\u003e Select \"Attach existing policies directly\" \u003e\u003e Choose \"AmazonEC2FullAccess\" \u003e\u003e Click Next Tags_\n![alt_txt](https://i.ibb.co/GkXxJrQ/Screenshot-3.png)\n6. _Add Tags(Optional)_ \u003e\u003e _Enter a key and value as you like either you can leave as blank_\n![alt_txt](https://i.ibb.co/QQb9svy/IAM-5.png)\n7. _Review your user details and click \"Create User\"_\n![alt_txt](https://i.ibb.co/SJy4VJB/Screenshot-4.png)\n8. _Store your credentials to your local_\n![alt_txt](https://i.ibb.co/nPVWcXZ/IAM-7.png)\n\n_Reference URL_:: _IAM User creation [article](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)_\n\n----\n### Pre-Requested (Dependency packages)\n```sh\nyum install -y git\nyum install -y python3\nyum install -y python3-pip\n```\n\n### How to get\n```sh\ngit clone https://github.com/yousafkhamza/EC2-Infrastructure-creation-through-pyscript.git\ncd EC2-Infrastructure-creation-through-pyscript\npip3 install -r requirements.txt\n```\n\u003e Change your creds and bucket name in at config.py and ec2 details under var.py file\n\nCommand to run the script::\n```\n python3 ec2_creation.py\n```\n\n----\n## Output be like\n```sh\n$ python3 ec2_creation.py\nSecurity Group Created sg-0f13a431524032168 in vpc vpc-00c2ae623614d9504. \n\nInstance Created Successfully and Details are given below:\n----------------------------------------------------------\nID=i-02e1cbf5a1f54b6c2 PrivateIP=172.31.85.87\n```\n\n## Terminal Output\n_Screenshot_\n![alt_txt](https://i.ibb.co/267q5nx/terminal-out.png)\n\n## Console output\n_Screenshot_\n![alt_txt](https://i.ibb.co/w7qYF6T/consol-out.png)\n\n----\n## Behind the code\n_vim ec2_creation.py_\n```sh\nimport boto3\nimport datetime\nimport os\nfrom botocore.exceptions import ClientError\nimport config\nimport var\n\nec2_client = boto3.client('ec2',\n                      aws_access_key_id=config.AWS_ACCESS_KEY_ID,\n                      aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY,\n                      region_name=config.REGION\n                    )\n\nec2 = boto3.resource('ec2',\n                      aws_access_key_id=config.AWS_ACCESS_KEY_ID,\n                      aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY,\n                      region_name=config.REGION\n                    )\n\npassword = var.PASSWORD\nUSERDATA_SCRIPT = f'''\n#!/bin/bash\necho \"ClientAliveInterval 60\" \u003e\u003e /etc/ssh/sshd_config\necho \"LANG=en_US.utf-8\" \u003e\u003e /etc/environment\necho \"LC_ALL=en_US.utf-8\" \u003e\u003e /etc/environment\necho \"{password}\" | passwd root --stdin\nsed  -i 's/#PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config\nsed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config\nservice sshd restart\n'''\n\n\ndef instance_creation():\n    # AMI Finding\n    year = datetime.datetime.now().year\n\n    ami_img = []\n    ami = ec2_client.describe_images(Owners=['137112412989'])['Images']\n    for item in ami:\n        if item['ImageOwnerAlias'] == \"amazon\" and item[\"Name\"].startswith('amzn2-ami-hvm') and item['CreationDate'].startswith(str(year)):\n            ami_img.append(item['ImageId'])\n                \n    # Security Group Creation\n    group_id = []\n    sg_group = ec2_client.describe_security_groups()['SecurityGroups']\n    for item in sg_group:\n        if item['GroupName'] == var.SG_NAME:\n            print ('The Security Group \"%s\" is already created in amazon, So, we are using the same into this instance' % (var.SG_NAME))\n            group_id.append(item['GroupId'])\n        else:\n            response = ec2_client.describe_vpcs()\n            vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')\n            try:\n                response = ec2_client.create_security_group(GroupName=var.SG_NAME,\n                                                     Description='DESCRIPTION',\n                                                     VpcId=vpc_id)\n                security_group_id = response['GroupId']\n                print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))\n                group_id.append(security_group_id)\n                data = ec2_client.authorize_security_group_ingress(\n                GroupId=security_group_id,\n                    IpPermissions=[\n                        {'IpProtocol': 'tcp',\n                         'FromPort': 80,\n                         'ToPort': 80,\n                         'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},\n                        {'IpProtocol': 'tcp',\n                         'FromPort': 22,\n                         'ToPort': 22,\n                         'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}\n                    ])\n            except ClientError as e:\n                continue\n        \n    # Instance Creation\n    instances = ec2.create_instances(\n             BlockDeviceMappings=[\n                  {\n                    'DeviceName': '/dev/xvda',\n                    'Ebs': {\n                        'DeleteOnTermination': True,\n                        'VolumeSize': int(var.IN_SIZE),\n                        'VolumeType': 'gp2'\n                    },\n                },\n            ],\n         ImageId=ami_img[0],\n         MinCount=1,\n         MaxCount=1,\n         InstanceType=var.IN_TYPE,\n         SecurityGroupIds=[ group_id[0] ],\n         UserData=USERDATA_SCRIPT,\n         TagSpecifications=[\n                    {\n                        'ResourceType': 'instance',\n                        'Tags': [\n                            {\n                                'Key': 'Name',\n                                'Value': 'EC2-From-Python'\n                            },\n                        ]\n                    },\n                ]\n        )\n    print('\\nInstance Created Successfully and Details are given below:')\n    print('----------------------------------------------------------')\n    print(\"ID=\"+instances[0].id, \"PrivateIP=\"+instances[0].private_ip_address)\n    \ninstance_creation()\n```\n_vim config.py_\n```sh\nAWS_ACCESS_KEY_ID = 'YOUR ACCESS KEY HERE'\nAWS_SECRET_ACCESS_KEY = 'YOUR PRIVATE KEY HERE'\nREGION = 'REGION HERE'\n```\n_vim var.py_\n```sh\nPASSWORD = 'P@55W06D@12y' # You can modify your instance password here\nSG_NAME = 'FOREC2'        # You can modify your Security Group Name here\nIN_TYPE = 't2.micro'      # You can modify your instance type here\nIN_SIZE = '10'            # You can modify your instance size here\n```\n----\n## Conclusion\nIt's a simple python script to create AWS infrastructure like ansible/terraform but we don't use this we can able to create the same through python and it's an educational purpose. I hope you all understood the same and let me know your thoughts and comments.\n\n### ⚙️ Connect with Me \n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"mailto:yousaf.k.hamza@gmail.com\"\u003e\u003cimg src=\"https://img.shields.io/badge/Gmail-D14836?style=for-the-badge\u0026logo=gmail\u0026logoColor=white\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://www.linkedin.com/in/yousafkhamza\"\u003e\u003cimg src=\"https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge\u0026logo=linkedin\u0026logoColor=white\"/\u003e\u003c/a\u003e \n\u003ca href=\"https://www.instagram.com/yousafkhamza\"\u003e\u003cimg src=\"https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge\u0026logo=instagram\u0026logoColor=white\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://wa.me/%2B917736720639?text=This%20message%20from%20GitHub.\"\u003e\u003cimg src=\"https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge\u0026logo=whatsapp\u0026logoColor=white\"/\u003e\u003c/a\u003e\u003cbr /\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousafkhamza%2Fec2-infrastructure-creation-through-pyscript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyousafkhamza%2Fec2-infrastructure-creation-through-pyscript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyousafkhamza%2Fec2-infrastructure-creation-through-pyscript/lists"}