Created
August 30, 2017 05:57
-
-
Save lantrix/6d4935c934230df4a0d0348417128a48 to your computer and use it in GitHub Desktop.
PowerShell Create and Remove EC2 Instance Roles - with attached AWS managed policy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create EC2 Instance Role | |
$ec2RoleTrustPolicyDocument = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}' | |
$iamRole = New-IAMRole -AssumeRolePolicyDocument $ec2RoleTrustPolicyDocument -RoleName MyEC2Role | |
Register-IAMRolePolicy -RoleName $iamRole.RoleName -PolicyArn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess | |
$instanceProfile = New-IAMInstanceProfile -InstanceProfileName MyEC2InstanceRole | |
Add-IAMRoleToInstanceProfile -RoleName $iamRole.RoleName -InstanceProfileName $instanceProfile.InstanceProfileName | |
# Attach to existing instance | |
Register-EC2IamInstanceProfile -InstanceId i-0a5c81b759851230c -IamInstanceProfile_Name $instanceProfile.InstanceProfileName | |
# View role AssociationId | |
Get-EC2IamInstanceProfileAssociation -Filter @{name='instance-id'; values='i-0a5c81b759851230c'} | |
# Remove from existing instance | |
Get-EC2IamInstanceProfileAssociation -Filter @{name='instance-id'; values='i-0a5c81b759851230c'} | Unregister-EC2IamInstanceProfile | |
# Remove packer EC2 instance role | |
(Get-IAMInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName -Force | |
Remove-IAMInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName -Force | |
Get-IAMAttachedRolePolicies -RoleName $iamRole.RoleName | Unregister-IAMRolePolicy -RoleName $iamRole.RoleName -Force | |
Remove-IAMRole -RoleName $iamRole.RoleName -Force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment