Ansible – Creating EC2 Instances, System Group, and System User

This playbook is scripted to build two ec2 instances, then:

  1. create a user group labeled teacher,
  2. create a system user named tim, and
  3. add tim to the teacher’s group.

You will obviously need to change the playbook values below in the script to match up with AWS information. The values that need to be changed are highlighted in purple. Enjoy!

- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
    - name: Provision a set of instances
      vars:
        ami_id: "ami-6871a115"
      ec2:
        region: "us-east-1"
        key_name: YOUR-PEM-KEM-NAME
        group: launch-wizard-7
        instance_type: t2.micro
        assign_public_ip: yes
        vpc_subnet_id: subnet-322345
        image: "{{ ami_id }}"
        wait: true
        exact_count: 4
        count_tag:
          Name: webserver_app
        instance_tags:
          Name: webserver_app
      register: ec2
    - debug:
        msg: "System {{ ec2.instances }}"

    - name: Add new instance to host group
      add_host:
        hostname: "{{ item.public_ip }}"
        groupname: launched
      with_items: "{{ ec2.instances }}"

    - name: Wait for SSH to come up
      wait_for:
        host: "{{ item.public_ip }}"
        port: 22
        state: started
      with_items: "{{ ec2.instances }}"

- name: Configure instances
  hosts: launched
  tasks:
    - name: Add group "teacher"
      group:
        name: teacher
      become: yes

    - name: Add the user 'tim' with a specific uid and a primary group of 'teacher'
      user:
        name: tim
        groups: teacher
        password: "{{ 'teacher1234' | password_hash('sha512') }}"
      become: yes