Last active
June 23, 2020 20:12
-
-
Save jumpeiMano/f44ef7ae6f8dcdf19bbe07480b13c103 to your computer and use it in GitHub Desktop.
Create a bastion instance via CDK
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
import cdk = require("@aws-cdk/core"); | |
import ec2 = require("@aws-cdk/aws-ec2"); | |
import iam = require("@aws-cdk/aws-iam"); | |
export class BastionStack extends cdk.Stack { | |
constructor(app: cdk.App, id: string, props?: cdk.StackProps) { | |
super(app, id, props); | |
const vpc = new ec2.Vpc(this, "vpc", { | |
cidr: "10.0.0.0/16", | |
subnetConfiguration: [ | |
{ | |
name: "vpc-public-subnet", | |
cidrMask: 24, | |
subnetType: ec2.SubnetType.PUBLIC | |
}, | |
{ | |
name: "vpc-private-subnet", | |
cidrMask: 24, | |
subnetType: ec2.SubnetType.PRIVATE | |
} | |
] | |
}); | |
const bastion = new ec2.BastionHostLinux(this, "bastion", { | |
vpc: vpc, | |
instanceName: "bastion" | |
}); | |
bastion.instance.addToRolePolicy( | |
new iam.PolicyStatement({ | |
actions: ["secretsmanager:GetSecretValue"], | |
resources: [ | |
`arn:${this.partition}:secretsmanager:${this.region}:${this.account}:secret:bastion-secret*` | |
] | |
}) | |
); | |
bastion.instance.addUserData( | |
"sudo yum update -y", | |
"sudo yum install -y jq", | |
`echo -e $(aws secretsmanager get-secret-value --secret-id bastion-secret --region ${this.region} | jq -r .SecretString | jq -r .key) > /home/ec2-user/.ssh/id_rsa`, | |
"chown ec2-user:ec2-user /home/ec2-user/.ssh/id_rsa", | |
"chmod 400 /home/ec2-user/.ssh/id_rsa" | |
); | |
const bastionSg = new ec2.SecurityGroup(this, "allow-from-bastion", { | |
securityGroupName: "allow-from-bastion", | |
vpc: vpc | |
}); | |
new cdk.CfnOutput(this, "bastion-sg-output", { | |
value: bastionSg.securityGroupId, | |
exportName: "allow-from-bastion" | |
}); | |
cdk.Tag.add(bastionSg, "Name", "allow-from-bastion"); | |
bastionSg.addIngressRule( | |
ec2.Peer.ipv4(bastion.instancePrivateIp.concat("/32")), | |
ec2.Port.tcp(22) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment