How to create an EC2 instance - Using Ansible from local system
--- # Creating an EC2 Instance
- name: Creating an EC2 Instance with ansible cli
hosts: localhost
gather_facts: no
vars:
ansible_python_interpreter: /usr/bin/python3.9
region: eu-north-1
instance_type: t3.micro
ami: ami-0854d4f8e4bd6b834
key_name: ec2_ans_testkey
vpc_name: vpc-0c6fe57f34fa650aa
cidr_block: "10.10.0.0/16"
cidr: "10.10.0.0/24"
aws_access_key: AKIAQOLURWPRC63CJXWE
aws_secret_key: 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
tasks:
- name: Create a new VPC
amazon.aws.ec2_vpc_net:
name: "Ansible-Test"
cidr_block: "{{ cidr_block }}"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
region: "{{ region }}"
register: vpc
- name: Create a new Subnet
amazon.aws.ec2_vpc_subnet:
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
cidr: "{{ cidr }}"
region: "{{ region }}"
vpc_id: "{{ vpc.vpc.id }}"
register: subnet
- name: Create a Security Group
amazon.aws.ec2_security_group:
name: "Ansible-Test-Security-Group"
description: "Ansible-Testing"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
vpc_id: "{{ vpc.vpc.id }}"
region: "{{ region }}"
rules:
- proto: tcp
ports:
- 80
cidr_ip: 0.0.0.0/0
rule_desc: "allow all on port 80"
register: security_group
- name: Launch an EC2 Instance
amazon.aws.ec2_instance:
name: "Test-Ansible"
key_name: "{{ key_name }}"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
vpc_subnet_id: "{{ subnet.subnet.id }}"
instance_type: "{{ instance_type }}"
security_group: "{{ security_group.group_id }}"
count: 1
wait: yes
aws_region: "eu-north-1"
network:
assign_public_ip: true
image_id: "{{ ami }}"
- Step 1: Generate the access key and secret key from the AWS documentation.
- Step 2: Open any editor on your local machine and enter the following .yml:
- Step 3: Save and close the file.
- Step 4: Open the terminal in the directory where the file is located on your local machine.
- Step 5: Run the following command:
ansible-playbook <filename>.yml
Comments
Post a Comment